X

Cómo crear una página cuando el tema está activado

Snippets by IsItWP

¿Está buscando una manera de crear una nueva página (s) de forma automática en la activación del tema? Si bien es probable que haya un plugin para esto, hemos creado un fragmento de código rápido que puede utilizar para crear una nueva página en WordPress.

Si quieres que tu tema o plugin cree una nueva página (o dos o tres) por sí mismo, aquí tienes un código rápido para hacerlo. wp_insert_post devuelve el ID de la página recién creada. En caso de error, devolverá 0 si $wp_error es falso, o un objeto WP_Error si $wp_error es verdadero.

Instrucciones:

Todo lo que tienes que hacer es añadir este código al archivo index.php de tu tema por encima del hook.

Y por supuesto, este código podría ser utilizado para crear un POST o cualquier otro contenido Custom Post Type con sólo cambiar el valor de post_type.

<?php
$new_page = array(
	'slug' => 'this-is-my-new-page',
	'title' => 'Write a Headline that Captivates',
	'content' => "Enter the body Content for your Page here"
);
$new_page_id = wp_insert_post( array(
	'post_title' => $new_page['title'],
	'post_type' 	=> 'page',
	'post_name'	 => $new_page['slug'],
	'comment_status' => 'closed',
	'ping_status' => 'closed',
	'post_content' => $new_page['content'],
	'post_status' => 'publish',
	'post_author' => 1,
	'menu_order' => 0
));
?>

O, usted podría utilizar este código en su lugar. Este fragmento comprueba si ya existe una página con el título de la línea 3, y crea la página si aún no existe. También establece una plantilla de página si se da una plantilla de página en la línea 5.

Todo lo que tienes que hacer es añadir este código al archivo functions.php de tu tema o en un plugin específico del sitio:

if (isset($_GET['activated']) && is_admin()){
 
    $new_page_title = 'This is the page title';
    $new_page_content = 'This is the page content';
    $new_page_template = ''; //ex. template-custom.php. Leave blank if you don't want a custom page template.
 
    //don't change the code bellow, unless you know what you're doing
 
    $page_check = get_page_by_title($new_page_title);
    $new_page = array(
        'post_type' => 'page',
        'post_title' => $new_page_title,
        'post_content' => $new_page_content,
        'post_status' => 'publish',
        'post_author' => 1,
    );
    if(!isset($page_check->ID)){
        $new_page_id = wp_insert_post($new_page);
        if(!empty($new_page_template)){
            update_post_meta($new_page_id, '_wp_page_template', $new_page_template);
        }
    }
 
}

Nota: Si es la primera vez que añades fragmentos de código en WordPress, consulta nuestra guía sobre cómo añadir correctamente fragmentos de código en WordPress, para no romper accidentalmente tu sitio.

Si te ha gustado este fragmento de código, por favor, considere revisar nuestros otros artículos en el sitio como: 27 mejores temas de WordPress para blogs de viajes y cómo asegurar tus formularios de WordPress.

Comentarios   Deja una respuesta

  1. Suman Samanta marzo 3, 2019 en 5:37 am

    If I had to give a prime example of great quality content, this article would be one. It’s well-written material that keeps your interest well.

  2. Thanks. I exactly need this. Let me know with which hook, This code should be hooked?

  3. Thanks man! U have solution for insert auto taxonomies?

  4. Hi in my plugin automatic page generated and short code also automatic generated. i want in detail page no need to display header footer and sidebar.. any idea please ?

  5. Hi Kevin. How to create multiple pages with this method?Thankss..

  6. I don’t suppose there’s a way of directing users to the page after activation is there no matter what permalnk they have set is?

    I wanted to use this to create a theme FAQ page and direct the user to it after activation.

    1. I’m don’t think that is the best way to do things what you could do is create an admin page much like people do when they create a plugin and add your FAQ or other details in that. This tutorial on net.tuts has details about creating the admin panel for a plugin but the idea is the same.

      http://net.tutsplus.com/tutorials/wordpress/creating-a-custom-wordpress-plugin-from-scratch/

      1. Yeah You’re probably right. I’m using a child theme for Twenty Eleven and haven’t figure out how to hook into the current theme options yet. I’ll probably just create a html page with the info I need on it and link it but will check that link out, thanks

        1. Hi Zeaks,

          The tutorial I posted should work fine! Should not matter the theme
          you are using, the code in the tutorial will just have you add code to
          your functions.php to create the admin panel then it is just html to
          style and display your faq or other information.

    2. I’m don’t think that is the best way to do things what you could do is create an admin page much like people do when they create a plugin and add your FAQ or other details in that. This tutorial on net.tuts has details about creating the admin panel for a plugin but the idea is the same.

      http://net.tutsplus.com/tutorials/wordpress/creating-a-custom-wordpress-plugin-from-scratch/

  7. Nice! Big thanks!
    Just used your code to add menu items as well.
    (‘post_type’ => ‘nav-menu-item’)

    1. Hi Tyson, Cool glad I could help. Don’t forget to follow on twitter, facebook or RSS I post new snippets regularly.

  8. Sorry if a dumb question, but why would you want to do this?
    I have a test WP installation where I manually create a new post (or sometimes a page) whenever I activate a new plugin – to test out what it can do. I can see the benefit of a page/post generator for that action, but I’m not sure why a new page for activating a theme. Please help me understand. Thanks!

    1. No such thing as a dumb question on wpsnipp, this is a good question. Lets say that I have a new theme that will function more like a CMS with a default static front page. You could use this in your theme to create the needed pages for the person rather then asking them to do it by hand. This way I could create any number of pages needed for a theme I was creating then all the person would need to do is link pages to templates required. But this is just one example could be reasons we can’t even think of.

      1. Vignesh Diwakar febrero 20, 2014 en 2:15 am

        How I add this new page created by your code in main menu. (‘post_type’ => ‘nav-menu-item’) not working for me

    2. This is kind of old, but for me I am making a theme and setting up a custom page that will make a site map, and I want to link to that sitemap in the footer.

      This is a great bit of code, it lets me know for sure that this sitemap page will be there all the site.

  9. Tweets that mention Wordpress Create page on theme activation – wpsnipp.com Wordpress code snippets for your blog -- Topsy.com noviembre 24, 2010 en 4:32 pm

    […] This post was mentioned on Twitter by wp_freak, WPSNIPP. WPSNIPP said: #wordpress Create page on theme activation http://bit.ly/gTZHVl #blog please RT 🙂 […]

Añadir un comentario

Nos alegra que haya decidido dejar un comentario. Tenga en cuenta que todos los comentarios se moderan de acuerdo con nuestra política de privacidad , y que todos los enlaces son nofollow. NO utilice palabras clave en el campo del nombre. Tengamos una conversación personal y significativa.

WordPress Launch Checklist

La lista definitiva para lanzar WordPress

Hemos recopilado todos los elementos esenciales de la lista de comprobación para el lanzamiento de su próximo sitio web de WordPress en un práctico ebook.
Sí, envíeme el ¡gratuito!