Создание и отображение пользовательских типов записей в Wordpress Functions.php - PullRequest
0 голосов
/ 01 июня 2019

Чтение книги http://shop.oreilly.com/product/0636920027508.do, и я нахожусь на странице 511, где мы определяем пользовательский тип записи в PHP. Используя приведенный ниже код, он должен отображать созданный тип записи: «продукт» на страницах.

Мой нет.

Точный ли это код или я что-то не так делаю?

 function create_product_post_type() {
   $labels = array (
      'name' => 'Products', 'singular_name'  => 'Product'
  );

    $args = array (
    'labels'  => $labels, 
    'public'  => true, 
    'supports'  => array('title', 'editor', 'thumbnail', 'excerpt'),
    'taxonomies' => array( 'category') );
   register_post_type('product', $args );
 }

add_action( 'init', 'create_product_post_type' );



   function add_product_to_archives( $wp_query ) {
       $types_array = array( 'post', 'product');
   if( is_archive() && empty( $query->query_vars['suppress_filters'] ) ) {
       set_query_var( 'post_type', $types_array );


  }
}
  add_action('pre_get_posts', 'add_product_to_archives');

Этой книге пять лет, и сейчас я использую самую последнюю версию WordPress. Как вы думаете, это проблема?

1 Ответ

0 голосов
/ 01 июня 2019

Возможно, вам не хватает обязательного ключа для 'register_post_type'. Вы можете проверить полную документацию здесь: https://developer.wordpress.org/reference/functions/register_post_type/

(я бы рекомендовал вам использовать Wordpress Codex и Developer Code Reference вместо автономных книг. Информация меняется по сравнению с версиями, и именно здесь можно обновлять ее):

Попробуйте этот код:

if ( ! function_exists('products_post_type') ) {

// Register Custom Post Type
function products_post_type() {

    $labels = array(
        'name'                  => _x( 'Products', 'Post Type General Name', 'your_text_domain' ),
        'singular_name'         => _x( 'Product', 'Post Type Singular Name', 'your_text_domain' ),
        'menu_name'             => __( 'Products', 'your_text_domain' ),
        'name_admin_bar'        => __( 'Products', 'your_text_domain' ),
        'archives'              => __( 'Products Archives', 'your_text_domain' ),
        'attributes'            => __( 'Products Attributes', 'your_text_domain' ),
        'parent_item_colon'     => __( 'Parent Item:', 'your_text_domain' ),
        'all_items'             => __( 'All Items', 'your_text_domain' ),
        'add_new_item'          => __( 'Add New Item', 'your_text_domain' ),
        'add_new'               => __( 'Add New', 'your_text_domain' ),
        'new_item'              => __( 'New Item', 'your_text_domain' ),
        'edit_item'             => __( 'Edit Item', 'your_text_domain' ),
        'update_item'           => __( 'Update Item', 'your_text_domain' ),
        'view_item'             => __( 'View Item', 'your_text_domain' ),
        'view_items'            => __( 'View Items', 'your_text_domain' ),
        'search_items'          => __( 'Search Item', 'your_text_domain' ),
        'not_found'             => __( 'Not found', 'your_text_domain' ),
        'not_found_in_trash'    => __( 'Not found in Trash', 'your_text_domain' ),
        'featured_image'        => __( 'Featured Image', 'your_text_domain' ),
        'set_featured_image'    => __( 'Set featured image', 'your_text_domain' ),
        'remove_featured_image' => __( 'Remove featured image', 'your_text_domain' ),
        'use_featured_image'    => __( 'Use as featured image', 'your_text_domain' ),
        'insert_into_item'      => __( 'Insert into item', 'your_text_domain' ),
        'uploaded_to_this_item' => __( 'Uploaded to this item', 'your_text_domain' ),
        'items_list'            => __( 'Items list', 'your_text_domain' ),
        'items_list_navigation' => __( 'Items list navigation', 'your_text_domain' ),
        'filter_items_list'     => __( 'Filter items list', 'your_text_domain' ),
    );
    $args = array(
        'label'                 => __( 'Product', 'your_text_domain' ),
        'description'           => __( 'Products', 'your_text_domain' ),
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'thumbnail' ),
        'taxonomies'            => array( 'product_category' ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'menu_icon'             => 'dashicons-products',
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'page',
        'show_in_rest'          => false,
    );
    register_post_type( 'product', $args );

}
add_action( 'init', 'products_post_type', 0 );

}

На панели инструментов должен отображаться пункт «Продукты».

Также возможно, что вам потребуется создать собственную таксономию для категорий продуктов. Попробуйте:

if ( ! function_exists( 'products_category' ) ) {

// Register Custom Taxonomy
function products_category() {

    $labels = array(
        'name'                       => _x( 'Product Categories', 'Taxonomy General Name', 'your_text_domain' ),
        'singular_name'              => _x( 'Product Category', 'Taxonomy Singular Name', 'your_text_domain' ),
        'menu_name'                  => __( 'Category', 'your_text_domain' ),
        'all_items'                  => __( 'All Items', 'your_text_domain' ),
        'parent_item'                => __( 'Parent Item', 'your_text_domain' ),
        'parent_item_colon'          => __( 'Parent Item:', 'your_text_domain' ),
        'new_item_name'              => __( 'New Item Name', 'your_text_domain' ),
        'add_new_item'               => __( 'Add New Item', 'your_text_domain' ),
        'edit_item'                  => __( 'Edit Item', 'your_text_domain' ),
        'update_item'                => __( 'Update Item', 'your_text_domain' ),
        'view_item'                  => __( 'View Item', 'your_text_domain' ),
        'separate_items_with_commas' => __( 'Separate items with commas', 'your_text_domain' ),
        'add_or_remove_items'        => __( 'Add or remove items', 'your_text_domain' ),
        'choose_from_most_used'      => __( 'Choose from the most used', 'your_text_domain' ),
        'popular_items'              => __( 'Popular Items', 'your_text_domain' ),
        'search_items'               => __( 'Search Items', 'your_text_domain' ),
        'not_found'                  => __( 'Not Found', 'your_text_domain' ),
        'no_terms'                   => __( 'No items', 'your_text_domain' ),
        'items_list'                 => __( 'Items list', 'your_text_domain' ),
        'items_list_navigation'      => __( 'Items list navigation', 'your_text_domain' ),
    );
    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => true,
        'show_tagcloud'              => true,
        'show_in_rest'               => false,
    );
    register_taxonomy( 'product_category', array( 'products' ), $args );

}
add_action( 'init', 'products_category', 0 );

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...