Как правильно сделать страницу таксономии и попасть на нее?

Ссылка скопирована
PHP
1 ответ

Есть свой тип записи book, есть таксономия book-categories.
На одной странице есть блок, который должен вести на термы book-categories.

<div class="row book-categories">    <?php    // your taxonomy name $tax = 'book-categories';  // get the terms of taxonomy $terms = get_terms( $tax, [   'hide_empty' => false, // do not hide empty terms ]);  // loop through all terms foreach( $terms as $term ) {   // if no entries attached to the term   if( 0 == $term->count )     // display only the term name     echo '<h4>' . $term->name . '</h4>';   // if term has more than 0 entries   elseif( $term->count > 0 )     // display link to the term archive     echo '<h4><a href="'. get_term_link( $term ) .'">'. $term->name .'</a></h4>'; }?>                 </div>

<div class="row book-categories"> <?php // your taxonomy name $tax = 'book-categories'; // get the terms of taxonomy $terms = get_terms( $tax, [ 'hide_empty' => false, // do not hide empty terms ]); // loop through all terms foreach( $terms as $term ) { // if no entries attached to the term if( 0 == $term->count ) // display only the term name echo '<h4>' . $term->name . '</h4>'; // if term has more than 0 entries elseif( $term->count > 0 ) // display link to the term archive echo '<h4><a href="'. get_term_link( $term ) .'">'. $term->name .'</a></h4>'; }?> </div>

В корне темы я создал файл taxonomy-book-categories.php.
При открытии ссылок блока из кода ведет на шаблон ПРОСТО ЛЮБОЙ таксономии.

Мне попадается все одно и то же - как СОЗДАТЬ свой тип записи и таксономию, и что надо пересохранить пермалинки.
А мне надо чтобы именно при переходе по ссылкам из того блока открывалась страница каждой категории таксономии book-categories.
ТИП ЗАПИСИ БЫЛ СОЗДАН ДО МЕНЯ

add_action( 'init', 'register_group_post_type' );    function register_group_post_type() {          register_post_type('book', array(     'label'               => 'book',     'labels'              => array(       'name'          => 'Livre',       'singular_name' => 'Livre',       'menu_name'     => 'Livre',       'all_items'     => 'All Livre',       'add_new'       => 'Add Livre',       'add_new_item'  => 'Add new Livre',       'edit'          => 'Edit',       'edit_item'     => 'Edit Livre',       'new_item'      => 'New Livre',     ),     'description'         => 'Livre',     'public'              => true,     'publicly_queryable'  => true,     'show_ui'             => true,     'show_in_rest'        => true,     'rest_base'           => '',     'show_in_menu'        => true,     'exclude_from_search' => false,     'capability_type'     => 'post',     'map_meta_cap'        => true,     'menu_icon'           => 'dashicons-format-image',     'hierarchical'        => false,     'rewrite'             => false,     'has_archive'         => true,     'query_var'           => true,     'supports'            => array( 'title', 'thumbnail','editor'),   ) );   }

add_action( 'init', 'register_group_post_type' ); function register_group_post_type() { register_post_type('book', array( 'label' => 'book', 'labels' => array( 'name' => 'Livre', 'singular_name' => 'Livre', 'menu_name' => 'Livre', 'all_items' => 'All Livre', 'add_new' => 'Add Livre', 'add_new_item' => 'Add new Livre', 'edit' => 'Edit', 'edit_item' => 'Edit Livre', 'new_item' => 'New Livre', ), 'description' => 'Livre', 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_rest' => true, 'rest_base' => '', 'show_in_menu' => true, 'exclude_from_search' => false, 'capability_type' => 'post', 'map_meta_cap' => true, 'menu_icon' => 'dashicons-format-image', 'hierarchical' => false, 'rewrite' => false, 'has_archive' => true, 'query_var' => true, 'supports' => array( 'title', 'thumbnail','editor'), ) ); }

Таксономию добавил уже я - вставил перед типом записи.

add_action( 'init', 'create_subjects_hierarchical_taxonomy', 0 );     function create_subjects_hierarchical_taxonomy() {       $labels = array(     'name' => _x( 'Book Categories ', 'taxonomy general name' ),     'singular_name' => _x( 'Book Category', 'taxonomy singular name' ),     'search_items' =>  __( 'Search Book Category' ),     'all_items' => __( 'All Book Categories' ),     'parent_item' => __( 'Parent Book Category' ),     'parent_item_colon' => __( 'Parent Book Category:' ),     'edit_item' => __( 'Edit Book Category' ),      'update_item' => __( 'Update Book Category' ),     'add_new_item' => __( 'Add New Book Category' ),     'new_item_name' => __( 'New Book Category Name' ),     'menu_name' => __( 'Book Categories' ),  );        // Now register the taxonomy   register_taxonomy('book-categories',array('book'), array(     'hierarchical' => true,     'labels' => $labels,     'show_ui' => true,     'show_in_rest' => true,     'show_admin_column' => true,     'query_var' => true,     'rewrite' => array( 'slug' => 'book-categories' ),   ));   }

add_action( 'init', 'create_subjects_hierarchical_taxonomy', 0 ); function create_subjects_hierarchical_taxonomy() { $labels = array( 'name' => _x( 'Book Categories ', 'taxonomy general name' ), 'singular_name' => _x( 'Book Category', 'taxonomy singular name' ), 'search_items' => __( 'Search Book Category' ), 'all_items' => __( 'All Book Categories' ), 'parent_item' => __( 'Parent Book Category' ), 'parent_item_colon' => __( 'Parent Book Category:' ), 'edit_item' => __( 'Edit Book Category' ), 'update_item' => __( 'Update Book Category' ), 'add_new_item' => __( 'Add New Book Category' ), 'new_item_name' => __( 'New Book Category Name' ), 'menu_name' => __( 'Book Categories' ), ); // Now register the taxonomy register_taxonomy('book-categories',array('book'), array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_in_rest' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'book-categories' ), )); }

Как мне сделать, чтобы при клике на ссылки блока row book-categories переводило на страницу, где выведены посты этих категорий?

Дополнительно:

я код особо не читал но часто пересохранить пермалинки решают проблему с путями.
а для понимания в каком шаблоне вы находитесь есть хороший плагин show current template

  • Антон Литвиненко, пересохранял. оно не хотело видеть шаблон отдельной тексономии со слагом. пришлось в общем шаблоне taxonomy.php делать отдельный if. А теперь другая проблема - не работает пагинация. Пермалики тоже пересохранял. а оно на станицах больше, чем 1, например на 2,3, 4 выводит 404. Код тут , не знаете что может быть?
  • Нужно решить такую задачу?

    Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.

    Заказать помощь
    Лучший ответ
    1
    Backend-редакция Ответ

    Страница таксономии в WordPress появляется автоматически, если таксономия публичная, имеет rewrite и у неё есть термины. Для неё не нужно создавать обычную страницу в админке с таким же slug — это часто создаёт конфликт URL.

    Регистрация таксономии:

    add_action('init', function () {
        register_taxonomy('brand', ['product'], [
            'label' => 'Бренды',
            'public' => true,
            'hierarchical' => true,
            'show_ui' => true,
            'show_admin_column' => true,
            'show_in_rest' => true,
            'rewrite' => [
                'slug' => 'brand',
                'with_front' => false,
            ],
        ]);
    });

    add_action('init', function () { register_taxonomy('brand', ['product'], [ 'label' => 'Бренды', 'public' => true, 'hierarchical' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_rest' => true, 'rewrite' => [ 'slug' => 'brand', 'with_front' => false, ], ]); });

    После регистрации зайдите в «Настройки → Постоянные ссылки» и нажмите «Сохранить». Это сбросит rewrite rules.

    Шаблон для вывода можно сделать в теме:

    • taxonomy-brand.php — для всей таксономии brand;
    • taxonomy-brand-nike.php — для конкретного термина nike;
    • taxonomy.php — общий шаблон для таксономий.

    Если получаете 404, проверьте: slug не конфликтует со страницей, таксономия зарегистрирована на init, rewrite rules сброшены, термин существует, у записи действительно назначен этот термин.

    Другие ответы (0)

    Пока нет других ответов. Будьте первым, кто поможет автору.

    Ответить на вопрос

    комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    Вам также может быть интересно