Разработка плагинов, крючки, генерация контента


Я создаю свой первый плагин. Этот плагин активирует тему, настроит главную страницу по умолчанию, зарегистрирует tax./cpt и создаст некоторый контент. (cpt = пользовательские типы записей)

Я заставил все это работать в файле functions.php, используя: if (isset($_GET['activated']) && is_admin()), просто активировав тему. Но мне нужно, чтобы это был плагин, поэтому плагин активирует тему и сделает все остальное.

Я добился выполнения почти всей работы, но у меня возникли некоторые проблемы в процессе создания контента. КПП которые генерируются автоматически, должны быть назначены одному термину wp_set_object_terms(, но это не работает. Я видел, что термин успешно создан, но, возможно, таксономия недоступна, когда выполняется wp_set_object_terms(, и поэтому не может быть назначена на должности. Мне нужна ваша помощь..., Я не знаю, как это решить, и я не нахожу альтернативных способов сделать это.

Это сценарий:

<?php  
/* 
Plugin Name: -- CGS Theme Functionality --
Plugin URI: http://www.cgs.com
Version: 1.0
Author: Roy Guadalupe
Description: This plugin implent all functionlaities for CGS Theme
*/  

////////////// Create Page
function cgs_create_page() {
$new_page_title = 'Home - Front Tiles';
$new_page_content = 'Please click <a>here</a> to get more info about how to config this theme';
$new_page_template = 'page-frontiles.php';
$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);
            }
        }
}
add_action('init','cgs_create_page');

////////////// Set default home page
function set_static_front_page(){
// set the static front page
$home = get_page_by_title('Home - Front Tiles');
update_option('page_on_front',$home->ID);
update_option('show_on_front','page');
// set the blog page
// $blog = get_page_by_title('Blog');
// update_option('page_for_posts',$blog->ID);
}
  add_action('init','set_static_front_page');

////////////// Register Custom Post Types and Taxonomies
require_once('inc/cpt-taxonomies.php');

////////////// Add term "mosaic-home" to custom taxonomy "tiles_categories"
  function insert_term() {
    wp_insert_term(
      'Mosaic - Home',
      'tiles_categories',
      array(
        'description' => 'Add Tiles here to load in first term',
        'slug'    => 'mosaic-home'
        )
      );
    }
  add_action('init','insert_term');

////////////// Switch Theme
function updateTheme($theme){
    update_option('template', $theme);
    update_option('stylesheet', $theme);
    update_option('current_theme', $theme);
}

////////////// Make loop for creating 24 posts
function create_frontles_posts() {
  $x = 1;

  do {
    $post_id = wp_insert_post(array(
        'comment_status'  =>  'closed',
        'ping_status'   =>  'closed',
        'post_author'   =>  1,
        'post_name'   =>  'tile'.$x,
        'post_title'    =>  'Tile',
        'post_status'   =>  'publish',
        'post_type'   =>  'frontiles',
      ));
    $term_taxonomy_ids = wp_set_object_terms( $post_id, array('mosaic-home'), 'tiles_categories' );

      $x++;
    } while ($x <= 24);
    }
register_activation_hook( __FILE__, 'create_frontles_posts' );

function activation_callback() {
//The code inside this function is executed only on plugin activation


// Create Posts
$post_id = -1;
$title='';
// If the page doesn't already exist, then create it
if( null == get_page_by_title( $title ) ) {
    create_frontles_posts();
    } else {
          // Otherwise, we'll stop
          $post_id = -2;
  } 



    updateTheme('Creative_Grid');
    // programmatically_create_post();
}
register_activation_hook( __FILE__, 'activation_callback' );

?>

Этот код включен в качестве файла для создания пользовательских таксономий и cpt (он работает без проблемы):

<?php

// Custom Post Type Front tiles
add_action('init', 'cptui_register_my_cpt_frontiles');
function cptui_register_my_cpt_frontiles() {
register_post_type('frontiles', array(
'label' => 'Tiles',
'description' => 'Create tiled elements for the front page.',
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'capability_type' => 'post',
'map_meta_cap' => true,
'hierarchical' => false,
'rewrite' => array('slug' => 'tiles', 'with_front' => true),
'query_var' => true,
'exclude_from_search' => true,
'menu_position' => 3,
'supports' => array('title','editor','excerpt','thumbnail'),
'taxonomies' => array('tiles_categories'),
'labels' => array (
  'name' => 'Tiles',
  'singular_name' => 'Tile',
  'menu_name' => 'Tiles Posts',
  'add_new' => 'Add Tile',
  'add_new_item' => 'Add New Tile',
  'edit' => 'Edit',
  'edit_item' => 'Edit Tile',
  'new_item' => 'New Tile',
  'view' => 'View Tile',
  'view_item' => 'View Tile',
  'search_items' => 'Search Tiles',
  'not_found' => 'No Front Tiles Found',
  'not_found_in_trash' => 'No Front Tiles Found in Trash',
  'parent' => 'Parent Tile',
)
) ); }

// Taxonomies Front tiles
add_action('init', 'cptui_register_my_taxes_tiles_categories');
function cptui_register_my_taxes_tiles_categories() {
register_taxonomy( 'tiles_categories',array (
  0 => 'frontiles',
),
array( 'hierarchical' => true,
  'label' => 'Tile Categories',
  'show_ui' => true,
  'query_var' => true,
  'show_admin_column' => true,
  'labels' => array (
  'search_items' => 'Search Tile Categories',
  'popular_items' => '',
  'all_items' => 'All Categories',
  'parent_item' => 'Parent Tile Category',
  'parent_item_colon' => 'Parent Tile Category',
  'edit_item' => 'Edit Tile Category',
  'update_item' => 'Update Tile Category',
  'add_new_item' => 'Add Tile Category',
  'new_item_name' => 'New Tile Category',
  'separate_items_with_commas' => 'Separate tile categories with commas',
  'add_or_remove_items' => 'Add Categories...',
  'choose_from_most_used' => 'Choose from the most used Tiles Categories',
)
) ); 
}
?>
Author: Dedalos01, 2014-12-21

1 answers

Я вижу проблему в функции register_taxonomy. Второй аргумент, который вы используете, это:

array ( 0 => 'frontiles' )

Но это должно быть:

array ( 'frontiles' )

Или, поскольку вы передаете только один CPT, это может быть также строка:

'frontiles'

Кроме того, вы выполняете insert_term() при каждой загрузке страницы, но в вашем коде я вижу, что всегда вставляется один и тот же термин. Как только термин был создан в первый раз, нет причин повторять этот процесс при каждой загрузке страницы. Я предлагаю удалить add_action('init','insert_term'); и выполнить insert_term() на крючке действия регистрации прямо перед wp_insert_post.

Кроме того, поскольку вы хотите вставить термин и создать записи во время активации, вам необходимо зарегистрировать пользовательский тип записи и таксономию также в register_activation_hook, а не только в init. Это связано с тем, что следующее событие init происходит, когда плагин все еще неактивен. Я создал этот плагин с вашим кодом и моими предложениями, и он работает:

<?php  
/* 
Plugin Name: Test
Plugin URI: http://wordpress.stackexchange.com/questions/172888/plugin-development-hooks-generate-content
Version: 1.0
Author: CybMeta
Description: Test
*/ 

// Custom Post Type Front tiles
add_action('init', 'cptui_register_my_cpt_frontiles');
function cptui_register_my_cpt_frontiles() {
    register_post_type('frontiles', array(
        'label' => 'Tiles',
        'description' => 'Create tiled elements for the front page.',
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'capability_type' => 'post',
        'map_meta_cap' => true,
        'hierarchical' => false,
        'rewrite' => array('slug' => 'tiles', 'with_front' => true),
        'query_var' => true,
        'exclude_from_search' => true,
        'menu_position' => 3,
        'supports' => array('title','editor','excerpt','thumbnail'),
        'taxonomies' => array('tiles_categories'),
        'labels' => array (
            'name' => 'Tiles',
            'singular_name' => 'Tile',
            'menu_name' => 'Tiles Posts',
            'add_new' => 'Add Tile',
            'add_new_item' => 'Add New Tile',
            'edit' => 'Edit',
            'edit_item' => 'Edit Tile',
            'new_item' => 'New Tile',
            'view' => 'View Tile',
            'view_item' => 'View Tile',
            'search_items' => 'Search Tiles',
            'not_found' => 'No Front Tiles Found',
            'not_found_in_trash' => 'No Front Tiles Found in Trash',
            'parent' => 'Parent Tile',
        )
    ) );
}

// Taxonomies Front tiles
add_action('init', 'cptui_register_my_taxes_tiles_categories');
function cptui_register_my_taxes_tiles_categories() {
    register_taxonomy( 'tiles_categories',array (
            'frontiles'
        ),
        array( 'hierarchical' => true,
            'label' => 'Tile Categories',
            'show_ui' => true,
            'query_var' => true,
            'show_admin_column' => true,
            'labels' => array (
                'search_items' => 'Search Tile Categories',
                'popular_items' => '',
                'all_items' => 'All Categories',
                'parent_item' => 'Parent Tile Category',
                'parent_item_colon' => 'Parent Tile Category',
                'edit_item' => 'Edit Tile Category',
                'update_item' => 'Update Tile Category',
                'add_new_item' => 'Add Tile Category',
                'new_item_name' => 'New Tile Category',
                'separate_items_with_commas' => 'Separate tile categories with commas',
                'add_or_remove_items' => 'Add Categories...',
                'choose_from_most_used' => 'Choose from the most used Tiles Categories',
            )
    ) ); 
}

////////////// Add term "mosaic-home" to custom taxonomy "tiles_categories"
function insert_term() {
    wp_insert_term(
     'Mosaic - Home',
     'tiles_categories',
      array(
          'description' => 'Add Tiles here to load in first term'
        )
      );
}

function create_frontles_posts() {

    cptui_register_my_cpt_frontiles();
    cptui_register_my_taxes_tiles_categories();
    insert_term();

    $x = 1;

    do {
        $post_id = wp_insert_post(array(
            'comment_status'  =>  'closed',
            'ping_status'   =>  'closed',
            'post_author'   =>  1,
            'post_name'   =>  'tile'.$x,
            'post_title'    =>  'Tile',
            'post_status'   =>  'publish',
            'post_type'   =>  'frontiles',
      ));
     $term_taxonomy_ids = wp_set_object_terms( $post_id, array('mosaic-home'), 'tiles_categories' );

      $x++;
    } while ($x <= 24);
}
register_activation_hook( __FILE__, 'create_frontles_posts' );
 0
Author: cybmeta, 2015-06-16 11:46:36