0

everyone. I have 10 custom post types and they are sharing 5 taxonomies. Right now I am working on the archive page template where I want to create ajax filters based on taxonomies for each of the post types.

For example, we have post types Jewelry and Watches. Both of them have shared taxonomy Brand (by shared I mean, that every time I add the brand to the watches, it will also show up on the jewelry brands choice). Now, on the archive page of the watches, I want to show only brands that used by the watch custom posts.

To create a taxonomy I used the CPT UI plugin.

This is the code I came up with, but it shows all the terms:

<?php
// Retrieve the taxonomies for your custom post type
$cpt_taxes = get_object_taxonomies($current_post_type->name, 'object');

// Build an array of taxonomies slugs to be used in our $args array below to filter only taxes we need.
foreach ($cpt_taxes as $cpt_tax) {
    $cpt_tax_name = $cpt_tax->name;
    $cpt_tax_label = $cpt_tax->labels->singular_name;

    ?>
    <li class="accordion-item " data-accordion-item>
        <!-- Accordion tab title -->
        <a href="#" class="accordion-title"><span><?php echo $cpt_tax_label; ?></span></a>
        <!-- Accordion tab content -->
        <div class="accordion-content" data-tab-content>

            <?php
            foreach ((array)get_terms(array(
                                          'taxonomy' => $cpt_tax_name,
                                          'orderby'    => 'name',
                                          'hide_empty' => true
                                      )) as $term_data) {
                echo '<input id="' . $term_data->name . '" type="checkbox" name="' . $term_data->name . '"><label for="' . $term_data->name . '">' . $term_data->name . ' <small>(' . $term_data->count . ')</small></label> <br>'; // ID of the category as the value of an option

            }?>
        </div>
    </li>
<?php } ?>
0

You need to send param post_id in ajax of data. Then in your plugin parse it and and search by taxomony. My simple example:

<?php 
// in ajax handler
// get post_id from requst data
$post_id = filter_var($_POST['post_id'], FILTER_VALIDATE_INT);
// find post
$post = get_post($post_id);

But before you need register the taxomony.

register_taxonomy('auto', array($post->post_type), array(
    'label'                 => '', // определяется параметром $labels->name
    'labels'                => array(
        'name'              => 'auto',
        'singular_name'     => 'auto',
        'search_items'      => 'Search auto',
        'all_items'         => 'All auto',
        'view_item '        => 'View auto',
        'parent_item'       => 'Parent auto',
        'parent_item_colon' => 'Parent auto:',
        'edit_item'         => 'Edit auto',
        'update_item'       => 'Update auto',
        'add_new_item'      => 'Add New auto',
        'new_item_name'     => 'New auto Name',
        'menu_name'         => 'Auto',
    ),
    'description'           => '', // описание таксономии
    'public'                => true,
    'publicly_queryable'    => null, // равен аргументу public
    'show_in_nav_menus'     => true, // равен аргументу public
    'show_ui'               => true, // равен аргументу public
    'show_tagcloud'         => true, // равен аргументу show_ui
    'show_in_rest'          => null, // добавить в REST API
    'rest_base'             => null, // $taxonomy
    'hierarchical'          => false,
    'update_count_callback' => '',
    'rewrite'               => true,
    'capabilities'          => array(),
    'meta_box_cb'           => null, // callback функция. Отвечает за html код метабокса (с версии 3.8): post_categories_meta_box или post_tags_meta_box. Если указать false, то метабокс будет отключен вообще
    'show_admin_column'     => false, // Позволить или нет авто-создание колонки таксономии в таблице ассоциированного типа записи. (с версии 3.5)
    '_builtin'              => false,
    'show_in_quick_edit'    => null, // по умолчанию значение show_ui
) );

and register terms

wp_set_object_terms($post_id, ['audi', 'bmw', 'kia'], 'auto');

Finaly you need send response

    ob_start();
// Build an array of taxonomies slugs to be used in our $args array below to filter only taxes we need.
foreach ($cpt_taxes as $cpt_tax) {
    $cpt_tax_name = $cpt_tax->name;
    $cpt_tax_label = $cpt_tax->labels->singular_name;
    ?>
    <li class="accordion-item " data-accordion-item>
        <!-- Accordion tab title -->
        <a href="#" class="accordion-title"><span><?php echo $cpt_tax_label; ?>
    </span></a>
        <!-- Accordion tab content -->
        <div class="accordion-content" data-tab-content>
            <?php
            $terms_list = (array)get_terms([
                                               'taxonomy'   => $cpt_tax_name,
                                               'orderby'    => 'name',
                                               'hide_empty' => true,
                                           ]);
            foreach ($terms_list as $term_data) {
                echo '<input id="' . $term_data->name . '" type="checkbox" name="' . $term_data->name . '"><label for="' . $term_data->name . '">' . $term_data->name . ' <small>(' . $term_data->count . ')</small></label> <br>'; // ID of the category as the value of an option
            } ?>
        </div>
    </li>
    <?php
}
$html = ob_get_clean();

wp_send_json_success($html);
wp_die();

My code on github https://github.com/ggmanuilov/wpajaxtaxomony/tree/master

I hope I could help you.

  • Hi. Thk you for your answer, but probably I didn't explain myself clear enough. The taxonomy already exists and its accumulates terms from 10 different custom posts. This is what we have. --------- Now I want to show terms that was only used by particular post type. – Tanya Oct 11 '17 at 16:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.