0

После создания произвольного типа записи bonuses

////// BONUSES
///

add_action( 'init', 'register_post_type_bonuses' ); // Использовать функцию только внутри хука init

function register_post_type_bonuses() {
    $labels = array(
        'name' => 'Бонусы',
        'singular_name' => 'Бонус',
        'add_new' => 'Добавить бонус',
        'add_new_item' => 'Добавить новый бонус', // заголовок тега <title>
        'edit_item' => 'Редактировать бонус',
        'new_item' => 'Новый бонус',
        'all_items' => 'Все бонусы',
        'view_item' => 'Просмотр бонуса на сайте',
        'search_items' => 'Искать бонус',
        'not_found' =>  'Бонус не найдено.',
        'not_found_in_trash' => 'В корзине нет бонусов.',
        'menu_name' => 'Бонусы' // ссылка в меню в админке
    );
    $args = array(
        'label' => __( 'bonus', 'casinoempt' ),
        'description' => __( 'Каталог Бонусов', 'casinoempt' ),
        'labels' => $labels,
        'public' => true,
        'show_ui' => true, // показывать интерфейс в админке
        'has_archive' => true,
        'menu_icon' => 'dashicons-money-alt', // иконка в меню
        'menu_position' => 20, // порядок в меню
        'rewrite' => array('slug' => 'bonuses'),
        'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields',),
        'publicly_queryable' => true,

    );
    register_post_type('bonuses', $args);
}

Ищу простой способ что бы все посты данного типа отображали информацию с определенного шаблона. Попробовал создать шаблон single-bonuses.php page-bonuses.php но WP не выводит по умолчанию информацию с этих страниц. Только если добавить строку

/*
Template Name: Bonus
Template Post Type: bonuses

*/

Получается назначить

введите сюда описание изображения

Как сделать чтобы по-умолчанию отображалось с указанных шаблонов страниц?

3
  • 1
    single-bonuses.php должен подключатся по умолчанию. Заголовки в этом случае не нужны и в админке он не выбирается.
    – SeVlad
    8 июл 2021 в 16:09
  • Постоянные ссылки обновлены в админке? 8 июл 2021 в 16:27
  • И rewrite уберите 8 июл 2021 в 16:27

1 ответ 1

1

Вот несколько видоизменённый класс из одного моего рабочего плагина.

<?php
/**
 * CPT class file.
 *
 * @package my-plugin
 */

namespace MyPlugin\CPT;

/**
 * Class CPT
 */
class CPT {

    /**
     * Custom post type.
     *
     * @var string
     */
    protected string $custom_post_type = '';

    /**
     * Post taxonomy name.
     *
     * @var string
     */
    protected string $post_tax = '';

    /**
     * Prefix in url.
     *
     * @var string
     */
    protected string $prefix = '';

    /**
     * Taxonomy label.
     *
     * @var string
     */
    protected string $tax_label = '';

    /**
     * Post label.
     *
     * @var string
     */
    protected string $post_label = '';

    /**
     * Projects constructor.
     */
    public function __construct() {
        $this->custom_post_type = 'bonuses';
        $this->post_tax         = 'bonus_type';
        $this->prefix           = 'bonuses';

        $this->tax_label  = __( 'Bonus Types', 'my-domain' );
        $this->post_label = __( 'Bonuses', 'my-domain' );
    }

    /**
     * Init class.
     */
    public function init(): void {
        add_filter( 'init', [ $this, 'register_cpt' ] );

        // Register activation hook to flush rewrite rules.
        register_activation_hook( WTEI_FILE, [ $this, 'activate_plugin' ] );

        // Register deactivation hook to flush rewrite rules.
        register_deactivation_hook( WTEI_FILE, [ $this, 'deactivate_plugin' ] );
    }

    /**
     * Create custom post type.
     */
    public function register_cpt(): void {
        register_taxonomy(
            $this->post_tax,
            [ $this->custom_post_type ],
            [
                'label'             => $this->tax_label,
                'public'            => true,
                'show_tagcloud'     => false,
                'show_in_rest'      => true,
                'hierarchical'      => false,
                'rewrite'           => [
                    'slug'         => $this->prefix,
                    'hierarchical' => false,
                    'with_front'   => false,
                ],
                'show_admin_column' => true,
                'query_var'         => true,
            ]
        );

        register_post_type(
            $this->custom_post_type,
            [
                'label'             => $this->post_label,
                'public'            => true,
                'capability_type'   => 'post',
                'show_in_rest'      => true,
                'hierarchical'      => false,
                'rewrite'           => [
                    'slug'       => $this->prefix . '/%' . $this->post_tax . '%',
                    'with_front' => false,
                    'feeds'      => false,
                ],
                'supports'          => [
                    'title',
                    'tags',
                    'excerpt',
                    'editor',
                    'custom-fields',
                    'thumbnail',
                    'page-attributes',
                ],
                'has_archive'       => false,
                'taxonomies'        => [ $this->post_tax ],
                'show_in_nav_menus' => true,
                'menu_icon'         => 'dashicons-admin-site',
            ]
        );
    }

    /**
     * Plugin activation hook.
     */
    public function activate_plugin(): void {
        // Register entities as they do not exist when activation hook is fired.
        // Otherwise flush_rewrite_rules() has nothing to do.
        $this->register_cpt();

        flush_rewrite_rules();
    }

    /**
     * Plugin deactivation hook.
     */
    public function deactivate_plugin(): void {
        // Unregister entities here as they do already exist when deactivation hook is fired.
        // Otherwise flush_rewrite_rules() has nothing to do.

        // This also unregisters taxonomies.
        unregister_post_type( $this->custom_post_type );

        flush_rewrite_rules();
    }
}

Здесь важно то, надо регистрировать тип поста до flush_rewrite_rules(), иначе в хуке активации flush не сработает. То же самое по поводу хука деактивации.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.