Cara untuk menginstal halaman secara otomatis pada instalasi tema?


8

Saya mencoba membangun tema yang membutuhkan halaman tertentu untuk disertakan. Apakah ada cara untuk secara otomatis membuat halaman dan menetapkannya ke template halaman mereka ketika sebuah tema diinstal?


1
Saya cukup yakin pertanyaan yang sama persis telah diajukan di sini. Cari saja lebih banyak.
Steven

Saya tidak dapat menemukan apa pun, itu sebabnya saya bertanya. Jika Anda tahu sebuah posting, silakan bagikan.
JonnyPlow

Jawaban:



3

Saya mendapat situasi serupa di mana saya perlu menambahkan halaman pada aktivasi tema dan menjadikannya sebagai beranda secara otomatis.

Begini cara saya melakukannya:

add_action('after_setup_theme', 'mytheme_setup');

function mytheme_setup(){

 if(get_option('page_on_front')=='0' && get_option('show_on_front')=='posts'){
        // Create homepage
        $homepage = array(
            'post_type'    => 'page',
            'post_title'    => 'Home',
            'post_content'  => '',
            'post_status'   => 'publish',
            'post_author'   => 1
        ); 
        // Insert the post into the database
        $homepage_id =  wp_insert_post( $homepage );
        // set this page as homepage
        update_option('show_on_front', 'page');
        update_option('page_on_front', $homepage_id);
    }

}

Semoga ini bisa membantu seseorang.

Memperbarui:

add_action('after_setup_theme', 'mytheme_setup');

function mytheme_setup(){

 if(get_option('page_on_front')=='0' && get_option('show_on_front')=='posts'){
        // Create homepage
        $homepage = array(
            'post_type'    => 'page',
            'post_title'    => 'Home',
            'post_content'  => '',
            'post_status'   => 'publish',
            'post_author'   => 1
        ); 
        // Insert the post into the database
        $homepage_id =  wp_insert_post( $homepage );
        //set the page template 
        //assuming you have defined template on your-template-filename.php
        update_post_meta($homepage_id, '_wp_page_template', 'your-template-filename.php');
    }

}

Terima kasih Maruti Mohanty .


Meskipun Anda telah menyebutkan detail solusi, tetapi ini bukan sesuatu yang dicari pengguna. Tetapi jika Anda juga dapat menambahkan bagaimana Anda dapat menambahkan / menentukan templat halaman ke posting baru, yang mungkin memberi pengguna wawasan untuk dikerjakan
Maruti Mohanty

1
Diedit. Dan terima kasih telah mengarahkan saya ke arah yang benar.
Dharma Poudel

1

Ini praktik buruk. Tema adalah untuk presentasi, mereka visual, mereka tidak boleh mendikte konten yang sebenarnya. Jika mereka melakukannya, maka Anda salah melakukannya dan kode Anda akan lebih baik sebagai plugin.

Namun, jika tema Anda memiliki pengaturan konten yang 'dimaksudkan', Anda tidak boleh membuat halaman / konten secara otomatis, Anda tidak boleh ikut campur dengan konten pengguna sama sekali, Anda bisa melanggar hal-hal lain.

Alih-alih, izinkan pengguna untuk memilih halaman mana yang harus digunakan, dengan cara yang sama pengaturan memungkinkan Anda untuk memilih halaman statis alih-alih posting terbaru, dan bagaimana plugin seperti Woocommerce atau Jigoshop memungkinkan Anda memilih halaman mana yang merupakan halaman checkout dll (yaitu plugin, tidak apa-apa bagi mereka untuk membuat halaman seperti itu).

Bagaimanapun ini menunjukkan kelemahan mendasar dalam pendekatan Anda untuk membangun tema Anda (atau Anda sedang membangun sesuatu untuk klien, dan telah memutuskan untuk membuatnya mudah bagi mereka untuk menginstal, menciptakan lebih banyak pekerjaan untuk Anda, sedangkan Anda akan lebih baik menawarkan untuk pasang sendiri untuk biaya, yang akan lebih menguntungkan).

Jika Anda cukup bodoh untuk benar-benar mencobanya ...

Lihat http://codex.wordpress.org/Function_Reference/wp_insert_post

Tapi, Anda perlu memeriksa setiap 'init' untuk melihat apakah halaman ada. Jika mereka tidak membuatnya, dan perbarui opsi di suatu tempat sehingga Anda ingat mereka telah dibuat dan tidak memeriksa waktu berikutnya, jika tidak, Anda akan berakhir dengan lebih banyak halaman yang dibuat pada setiap pemuatan halaman.


0

Menggunakan kode dalam jawaban ini dan wp_insert_postsaya temukan di tema ini .

wp_register_theme_activation_hook('twentyten', 'wpse_25885_theme_activate');
wp_register_theme_deactivation_hook('twentyten', 'wpse_25885_theme_deactivate');

/**
 *
 * @desc registers a theme activation hook
 * @param string $code : Code of the theme. This can be the base folder of your theme. Eg if your theme is in folder 'mytheme' then code will be 'mytheme'
 * @param callback $function : Function to call when theme gets activated.
 */
function wp_register_theme_activation_hook($code, $function) {
    $optionKey="theme_is_activated_" . $code;
    if(!get_option($optionKey)) {
        call_user_func($function);
        update_option($optionKey , 1);
    }
}

/**
 * @desc registers deactivation hook
 * @param string $code : Code of the theme. This must match the value you provided in wp_register_theme_activation_hook function as $code
 * @param callback $function : Function to call when theme gets deactivated.
 */
function wp_register_theme_deactivation_hook($code, $function)
{
    // store function in code specific global
    $GLOBALS["wp_register_theme_deactivation_hook_function" . $code]=$function;

    // create a runtime function which will delete the option set while activation of this theme and will call deactivation function provided in $function
    $fn=create_function('$theme', ' call_user_func($GLOBALS["wp_register_theme_deactivation_hook_function' . $code . '"]); delete_option("theme_is_activated_' . $code. '");');

    // add above created function to switch_theme action hook. This hook gets called when admin changes the theme.
    // Due to wordpress core implementation this hook can only be received by currently active theme (which is going to be deactivated as admin has chosen another one.
    // Your theme can perceive this hook as a deactivation hook.)
    add_action("switch_theme", $fn);
}

function wpse_25885_theme_activate()
{
    $default_pages = array(
        array(
            'title' => 'Home',
            'content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum consequat, orci ac laoreet cursus, dolor sem luctus lorem, eget consequat magna felis a magna. Aliquam scelerisque condimentum ante, eget facilisis tortor lobortis in. In interdum venenatis justo eget consequat. Morbi commodo rhoncus mi nec pharetra. Aliquam erat volutpat. Mauris non lorem eu dolor hendrerit dapibus. Mauris mollis nisl quis sapien posuere consectetur. Nullam in sapien at nisi ornare bibendum at ut lectus. Pellentesque ut magna mauris. Nam viverra suscipit ligula, sed accumsan enim placerat nec. Cras vitae metus vel dolor ultrices sagittis.'
            ),
        array(
            'title' => 'Contact',
            'content' => 'Duis venenatis augue sed risus laoreet congue ac ac leo. Donec fermentum accumsan libero sit amet iaculis. Duis tristique dictum enim, ac fringilla risus bibendum in. Nunc ornare, quam sit amet ultricies gravida, tortor mi malesuada urna, quis commodo dui nibh in lacus. Nunc vel tortor mi. Pellentesque vel urna a arcu adipiscing imperdiet vitae sit amet neque. Integer eu lectus et nunc dictum sagittis. Curabitur commodo vulputate fringilla. Sed eleifend, arcu convallis adipiscing congue, dui turpis commodo magna, et vehicula sapien turpis sit amet nisi.'
            )
    );
    $existing_pages = get_pages();
    $existing_titles = array();

    foreach ($existing_pages as $page) 
    {
        $existing_titles[] = $page->post_title;
    }

    foreach ($default_pages as $new_page) 
    {
        if( !in_array( $new_page['title'], $existing_titles ) )
        {
            // create post object
            $add_default_pages = array(
                'post_title' => $new_page['title'],
                'post_content' => $new_page['content'],
                'post_status' => 'publish',
                'post_type' => 'page'
              );

            // insert the post into the database
            $result = wp_insert_post($add_default_pages);   
        }
    }
}

function wpse_25885_theme_deactivate() 
{
   // code to execute on theme deactivation
}
Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.