WordPress | Post Запрос | Запрос к категориям сообщений для создания фильтра подкатегорий и применения его к Ajax-фильтру в моем функциональном файле

#php #ajax #wordpress

#php #ajax #wordpress

Вопрос:

Я изо всех сил пытаюсь заставить фильтр страницы моего портфолио работать. Я довольно хорошо разбираюсь в WordPress и, похоже, не могу…

Цели:

  • Создайте фильтр только с категориями, которые являются подкатегорией указанной категории.

  • Используйте выбранную опцию из фильтра подкатегорий, чтобы отобразить соответствующие записи для выбранного фильтра.

Итак, к соответствующему коду:

Страница моего портфолио, которая успешно удаляет сообщения из категории моего портфолио:

 <div class="portfolio-filters">

    <?php
    $filtercategory = get_template_directory() . "/template-parts/category-filter.php";
    include_once($filtercategory);
    ?>

</div>

<div class="portfolio-pieces">

    <div class="portfolio-pieces-inner">

        <div id="response">

            <!-- DEFAULT PORTFOLIO PAGE DISPLAY -->
            <?php
            $args = array(
                'post_type' => 'post',
                'post_status' => 'publish',
                'category_name' => 'portfolio',
                'posts_per_page' => '-1',
                'orderby' => 'post_date',
                'order' => 'DESC'
            ); ?>

            <?php $the_query = new WP_Query( $args ); ?>

            <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>

                <div class="portfolio-piece" <?php if(has_post_thumbnail()) : ?>style="background-image: url(<?php echo get_the_post_thumbnail_url(); ?>);"<?php endif; ?>>
                    <a href="<?php the_permalink(); ?>" class="box-link" target="_blank"></a>

                    <div class="portfolio-piece-hover">

                    </div>

                    <div class="portfolio-piece-inner">
                        <h4><?php the_title(); ?></h4>
                    </div>
                </div>

            <?php
                endwhile;
                wp_reset_postdata();
            ?>

        </div>

    </div>

</div>
  

Во фрагменте выше я вызываю свой файл фильтра. Создайте область ответов и загрузите полный список элементов портфолио.

Мой файл фильтра категорий выглядит следующим образом:

 <form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
    <?php
        $args = array(
            'taxonomy' => 'category',
            'category_name' => 'portfolio-category',
            'orderby' => 'name',
            'order' => 'DESC',
            'parent' => 0
        ); 
        if( $terms = get_terms( $args ) ) :
            echo '<select name="categoryfilter"><option>Select category...</option>';
        foreach ( $terms as $term ) :
            echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
        endforeach;
            echo '</select>';
        endif;
    ?>

    <button>Apply filters</button>
    <input type="hidden" name="action" value="customfilter">
</form>

<script>
    jQuery(function($) {
        $('#filter').submit(function(){
            var filter = $('#filter');
            $.ajax({
                url:filter.attr('action'),
                data:filter.serialize(), // form data
                type:filter.attr('method'), // POST
                beforeSend:function(xhr){
                    filter.find('button').text('Applying Filters...');
                },
                success:function(data){
                    filter.find('button').text('Apply filters');
                    $('#response').html(data);
                }
            });
            return false;
        });
    });
</script>
  

Где приведенный выше фрагмент «пытается» создать форму с действием, которое указывает на admin-ajax.php файл в моей папке wp-admin (он там).

Then loops through my get_terms args to present the sub-categories I wish into a drop-down list, with an apply button.

The last snippet handles it all. Changing the text of the button depending on its state and gives my response div as the return place.

My functions file is like this:

 /* Filter Post Results */
function catfilter_filter_function(){
    $args = array(
        'orderby' => 'date', // we will sort posts by date
        'order' => $_POST['date'] // ASC or DESC
    );

    // for taxonomies / categories
    if( isset( $_POST['categoryfilter'] ) )
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'category',
                'field' => 'id',
                'terms' => $_POST['categoryfilter']
            )
        );

    $query = new WP_Query( $args );

    if( $query->have_posts() ) :
        while( $query->have_posts() ): $query->the_post();

            echo "<div class="portfolio-piece" style="background-image: url(" . get_the_post_thumbnail_url() . ");">";

                echo "<a href="" . the_permalink() . "" class="box-link" target="_blank"></a>";

                echo "<div class="portfolio-piece-hover">";

                echo "</div>";

                echo "<div class="portfolio-piece-inner">";

                    echo "<h4>" . the_title() . "</h4>";

                echo "</div>";

            echo "</div>";

        endwhile;
        wp_reset_postdata();
    else :
        echo 'No posts found';
    endif;

    die();
}
add_action('wp_ajax_customfilter', 'catfilter_filter_function');
add_action('wp_ajax_nopriv_customfilter', 'catfilter_filter_function');
/* END Filter Post Results */
  

The functions file script works will pull the posts stated in the filter through.

Can someone please help me narrow down my category filter to only have the relevant sub-categories in it? — They are sub-categories of the ‘Portfolio Categories’ category that has the slug ‘portfolio-category’

I am able to show the complete list of categories, or just the base parent categories, not the subcategories…

My categories are set up like this:

 — Portfolio Piece

— — Portfolio Category

— — — Automation

— — — Design

— — — Digital

— — — Exhibitions

— — — PR / Social

— — — Strategy

— — — Tech Insights

— — Sector

— — — Construction

— — — Manufacturing

— — — Oil amp; Gas

— — — Science
  

I have had no joke 50 attempts at different articles and cannot for the life of me narrow this list down.

Заранее огромное спасибо!

Ответ №1:

Вы можете указать родительский элемент, для которого должны выполняться get_terms, используя:

 parent => cat_ID
  

Где cat_ID — это идентификатор категории.

Вы можете узнать идентификатор категории, наведя указатель мыши на ссылку на категорию в списке категорий, затем проверив URL, на который вы будете перенаправлены, в примечании к ссылке в левом нижнем углу вашего браузера.