简体   繁体   English

WordPress | 发布查询| 查询帖子类别以创建子类别过滤器并将其应用于我的功能文件中的Ajax过滤器

[英]WordPress | Post Query | Query on post categories to create sub-category filter and applying it to an Ajax filter in my function file

I'm struggling to get my portfolio page's filter to work. 我正在努力使我的投资组合页面的过滤器正常工作。 I have quite a good knowledge of WordPress and cannot seem to... 我对WordPress非常了解,似乎无法...

Aims: 目的:

  • Create a filter with only the categories that are a subcategory of a specified category. 创建仅包含属于指定类别的子类别的类别的过滤器。

  • Use the selected option from the sub-category filter to Ajax the relevant posts for the chosen filter into view. 使用子类别过滤器中的选定选项将Ajax选定过滤器的相关帖子显示在视图中。

So onto the relevant code: 因此,进入相关代码:

My portfolio page that successfully pulls the posts from my portfolio category: 我的投资组合页面成功地从我的投资组合类别中提取了帖子:

<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>

In the snippet above, I call my filter file. 在上面的代码段中,我称为过滤器文件。 Create the response area and load in the complete list of portfolio pieces. 创建响应区域并装入完整的投资组合清单。

My Category Filter file looks like this: 我的类别过滤器文件如下所示:

<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>

Where the above snippet is 'attempting' to create a form with an action that points to the admin-ajax.php file in my wp-admin folder (it is there). 上面的代码片段试图“尝试”创建一个表单,该表单的动作指向我的wp-admin文件夹中的admin-ajax.php文件(位于该文件夹中)。

Then loops through my get_terms args to present the sub-categories I wish into a drop-down list, with an apply button. 然后循环遍历我的get_terms args,以应用按钮将我希望的子类别显示在一个下拉列表中。

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. 根据按钮的状态更改按钮的文本,并将响应div作为返回位置。

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 & Gas

— — — Science

I have had no joke 50+ attempts at different articles and cannot for the life of me narrow this list down. 我没有在不同文章上开玩笑50多次,而且我一生也无法缩小此列表的范围。

So massive thanks in advance! 非常感谢!

You are able to specify the parent for which the get_terms should iterate through by using: 您可以使用以下命令指定get_terms要为其迭代的父对象:

parent => cat_ID

Where cat_ID is the ID of the category. 其中cat_ID是类别的ID。

You can find out the category ID by hovering over the link to the category in the category list, then checking the URL you will be directed to in the link note in the bottom left of your browser. 您可以通过以下方式找到类别ID:将鼠标悬停在类别列表中类别的链接上,然后在浏览器左下方的链接注释中检查将要定向到的URL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM