Dans cette article je vous propose une fonction à usage unique qui créer des pages, des termes et des menus Wordpress pendant l'activation d'un plugin ou d'un thème.

Lors de l'activation d'un thème

Placer ce bout de code dans le fichier functions.php situé à la racine de votre thème. J'utiliserai le hook 'after_switch_theme' qui se déclenche seulement après l'activation d'un thème.

<?php

function init_settings(){

    /* Code */

}
add_action('after_switch_theme', 'init_settings');

Je développerai la partie plugin.

Lors de l'installation d'un plugin

J'utiliserai la fonction register_activation_hook() dans le fichier principal du plugin mon-plugin.php qui ne s'exécute seulement après avoir vérifié que le plugin n'est pas installé.

<?php

class Mon_Plugin{

    public function __construct(){
        $this->define_constants();
        $this->includes();
        register_activation_hook( __FILE__, array( 'Install', 'install' ) );
    }


    private function define_constants(){
        if( ! defined('MYPATH') ){
	    define('MYPATH', dirname( __FILE__ ).'/');
	}
    }


    public function includes(){
        include_once(MYPATH.'includes/class-taxonomies.php');
        include_once(MYPATH.'includes/class-install.php');
    }
}

return new Mon_Plugin();

Création des pages et des termes

Le code suivant est à mettre dans le fichier includes/class-install.php.

<?php

class Install{

    public static function install(){

        if( ! is_blog_installed() ) return;

        add_action('init', array(__CLASS__, 'init_hook') );
    }


    public static function init_hook(){

        $pages = array( 
	    array('title' => 'ACCUEIL', 'page_template' => 'tpl-accueil.php', 'home_page' => true),
	    array('title' => 'ANIMATIONS', 'page_template' => 'tpl-animations.php'), 
	    array('title' => 'CONTACT', 'page_template' => 'tpl-contact.php'), 
	    array('title' => 'PRÉSENTATION', 'page_template' => 'tpl-presentation.php'), 
	    array('title' => 'MENTIONS LÉGALES', 'page_template' => 'tpl-mentions.php')
	);
	self::create_pages( $pages );

	$taxonomies = array(
	    'Système Solaire' => array(
                'Terre' => array(
		    'description' => 'Petite bourgade à 150 millions de km du Soleil.'
		),
                'Lune' => array(
		    'description' => 'Petite bourgade à 150 millions de km du Soleil.',
		    'parent' => 'Terre'
		),
		'Jupiter' => array(
		    'description' => 'Géante gazeuse.'
		)
	    ), 
	    'mangas' => array(
		'Shônen', 'Seinen', 'Josei'
	    )
	);
	self::create_terms( $taxonomies );
    }


    public static function create_pages( $pages = array(), $template_folder = 'page-templates/' ){

        if( empty($pages) || ! is_array($pages) ) return;

	global $wpdb;

	foreach($pages as $slug => $page){

	    if( empty($page['title']) ) continue;

	    $page_name = sanitize_title($page['title']);
	    $page_content = '';
	    $page_template = 'default';
	    $page_id = $page_parent_id = $page_found_id = 0;
	    if( ! empty($page['content']) ) $page_content = $page['content'];
	    if( ! empty($page['page_template']) ) $page_template = $template_folder.$page['page_template'];

	    if( ! empty($page['page_parent']) ){
		$page_parent_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_type='page' AND post_title='%s'", $page['page_parent'] ) );
	    }

	    $page_found_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_type='page' AND post_title='%s'", $page['title'] ) );

	    if( empty($page_found_id) ){

		$page_data = array(
		    'post_status'    => 'publish',
		    'post_type'      => 'page',
		    'post_author'    => 1,
		    'post_title'     => $page['title'],
		    'post_name'      => $page_name,
		    'post_content'   => $page_content,
		    'post_parent'    => $page_parent_id,
		    'page_template'  => $page_template,
		    'comment_status' => 'closed',
		    'ping_status'    => 'closed'
		);
		$page_id = wp_insert_post( $page_data );

	    }else{

		$page_data = array(
		    'ID'             => $page_found_id,
		    'post_title'     => $page['title'],
		    'post_name'      => $page_name,
		    'post_content'   => $page_content,
		    'post_parent'    => $page_parent_id,
		    'page_template'  => $page_template,
		);
		$page_id = wp_update_post( $page_data );
	    }

	    if( $page['home_page'] ){
		update_option('show_on_front', 'page');
		update_option('page_for_posts', 0);
		update_option('page_on_front', $page_id);
	    }
	}
    }


    public static function create_terms( $taxonomies = array() ){

        if( empty($taxonomies) ) return;

        foreach($taxonomies as $taxonomy => $terms){
	    foreach($terms as $term => $args){
		if( ! term_exists($term, $taxonomy) ){
		    if( is_string($args['parent']) ){
			$args_term['name'] = $args['parent'];
			$terms_args = @get_terms($args_term);
			$term_args = array_shift($terms_args);
			$args['parent'] = (int) $term_args->term_id;
		    }
		    wp_insert_term($term, $taxonomy, $args);
		}
	    }
	}
    }

}

Création d'un menu

Cette méthode permet de créer plusieurs menus, pour l'exemple je n'en créerai qu'un seul.

<?php

class Install{

    /* Code précédent */

    public static function init_hook(){

        /* Code précédent */

        $menus = array(
	    array(
	        'menu' => array('name' => 'Menu Principal'), 
	        'items' => array(
		    array(
		        'menu-item-title' => 'PRÉSENTATION', 
		        'menu-item-object-id' => get_page_by_title('presentation')->ID, 
		        'menu-item-object' => 'page', 
		        'menu-item-status' => 'publish',
		        'menu-item-type' => 'post_type', 
		        'menu-item-position' => 1), 
		    array(
		        'menu-item-title' => 'SITES WEB', 
		        'menu-item-object-id' => 0, 
		        'menu-item-object' => 'site-web', 
		        'menu-item-status' => 'publish',
		        'menu-item-type' => 'post_type_archive', 
		        'menu-item-position' => 2), 
		    array(
		        'menu-item-title' => 'ANIMATIONS', 
		        'menu-item-object-id' => get_page_by_title('animations')->ID, 
		        'menu-item-object' => 'page', 
		        'menu-item-status' => 'publish',
		        'menu-item-type' => 'post_type', 
		        'menu-item-position' => 3), 
	            array(
		        'menu-item-title' => 'INFOGRAPHIE', 
		        'menu-item-object-id' => get_term_by('slug', 'pro', 'taxographie')->term_id, 
		        'menu-item-object' => 'taxographie', 
		        'menu-item-status' => 'publish',
		        'menu-item-type' => 'taxonomy', 
		        'menu-item-position' => 4), 
		    array(
		        'menu-item-title' => 'CONTACT', 
		        'menu-item-object-id' => get_page_by_title('contact')->ID, 
		        'menu-item-object' => 'page', 
		        'menu-item-status' => 'publish',
		        'menu-item-type' => 'post_type', 
		        'menu-item-position' => 5)
	        )
	    )
        );
	self::create_nav_menu( $menus );
    }


    public static function create_nav_menu( $menus = array() ){

        foreach($menus as $menu){
            $menu_id = 0;
	    $term = get_term_by('name', $menu['menu']['name'], 'nav_menu');
	    if( $term !== false && ! is_wp_error($term) ){
	        $menu_id = $term->term_id;
	    }else{
	        $term_menu = wp_insert_term($menu['menu']['name'] );
                if( ! is_wp_error($term_menu) ){
		    $menu_id = (int) $term_menu['term_id'];
		}
	    }

	    if( $menu_id > 0 ){

	        $menu_items = wp_get_nav_menu_items($menu_id);

	        foreach($menu['items'] as $item_data){

		    $item_id = 0;
		    if( ! empty($menu_items) ){
		        foreach($menu_items as $item){
			    if( $item_data['menu-item-title'] == $item->title && is_nav_menu_item($item->ID) ){
			        $item_id = $item->ID;
			        break;
			    }
		        }
		    }
		    wp_update_nav_menu_item( $menu_id, $item_id, $item_data );
	        }

	        $locations = get_theme_mod('nav_menu_locations');
	        $menu_location = sanitize_title($menu['menu']['name']);
	        $locations[$menu_location] = $menu_id;
	        set_theme_mod('nav_menu_locations', $locations);
	    }
        }
    }

}

Fonctions utilisées dans cet article