AJAX自定义发布筛选器未进行筛选

时间:2021-01-19 作者:Amaterasu_u

我试图编写一个ajax自定义后过滤器,但结果似乎不是过滤,我不确定哪里做错了。我将在下面提供相关代码。

archive-projetos.php

<div class="categories">
    <ul>
        <li><a href="" class="js-filter-item">Todos</a></li>
        <?php
        $cat_args = array(
            \'exclude\' => array(1),
            \'option_all\' => \'All\',
            \'taxonomy\' => \'Tipos de Construção\'
        );
        $categories = get_categories($cat_args);

        foreach($categories as $cat): ?>
            <li><a class="js-filter-item" href="<?= get_category_link($cat->term_id);?>"><?= $cat->name;?></a></li>
        <?php endforeach;?>
    </ul>
</div>
<div class="content-wrapper js-filter row">
    <?php
    $args = array (
        \'post_type\' => array(\'projetos\'),
        \'post_status\' => array(\'publish\')
    );

    $query = new WP_Query($args);

    if($query->have_posts()):
        while ($query->have_posts()) : $query->the_post();?>
        <div class="post-thumbnail-container col-sm">
            <a href="<?php the_permalink();?>">
                <div class="thumbnail-container"><?php the_post_thumbnail();?></div>
                <div class="title-overlay"><?php the_title();?></div>
            </a>
        </div>
        <?php endwhile; else: endif; wp_reset_postdata();?>
</div>

filter.js

(function($){
    $(document).ready(function(){
        $(document).on(\'click\', \'.js-filter-item\', function(e){
            e.preventDefault();
            
            var category =$(this).data(\'category\');

            $.ajax({
                url: wpajax.ajaxurl,
                data: {action: \'filter\', category: category},
                type: \'post\',
                success: function(result) {
                    $(\'.js-filter\').html(result);
                },
                error: function(result) {
                    console.warn(result);
                }
            });
        });
    });
})(jQuery);

functions.php

function load_scripts() {
    wp_enqueue_script(\'ajax\', get_template_directory_uri() . \'/js/filter.js\', array (\'jquery\'), NULL, true);

    wp_localize_script(\'ajax\',\'wpajax\',
        array(\'ajaxurl\' => admin_url(\'admin-ajax.php\'))
    );
}

add_action(\'wp_enqueue_scripts\', \'load_scripts\');

add_action(\'wp_ajax_nopriv_filter\', \'filter_ajax\');
add_action(\'wp_ajax_filter\', \'filter_ajax\');

function filter_ajax() {

    $category = $_POST[\'projetos\'];

    $args = array (
        \'post_type\' => array(\'projetos\'),
        \'post_status\' => array(\'publish\')
    );

    $query = new WP_Query($args);

    if(isset($category)) {
        $args[\'category__in\'] = array($category);
    }

    if($query->have_posts()):
        while ($query->have_posts()) : $query->the_post();?>
        <div class="post-thumbnail-container col-sm">
            <a href="<?php the_permalink();?>">
                <div class="thumbnail-container"><?php the_post_thumbnail();?></div>
                <div class="title-overlay"><?php the_title();?></div>
            </a>
        </div>
        <?php endwhile; else: endif; wp_reset_postdata();

    die();
}
我认为没有必要包括自定义帖子和类别,但也有必要包括:

function projetos()
{
    $args = array(
        \'labels\' => array(
            \'name\'=> \'Projetos\',
            \'singular_name\'=>\'Projeto\'
        ),
        \'public\' => true,
        \'has_archive\' => true,
        \'menu_icon\' => \'dashicons-category\',
        \'supports\' => array(\'title\',\'editor\',\'thumbnail\')
    );
    register_post_type(\'projetos\', $args);
}
add_action(\'init\', \'projetos\');

function tipos_construcao() 
{

    $args = array(
        \'labels\' => array (
            \'name\' => \'Tipos de Construção\',
            \'singular_name\'=>\'Tipo de Construção\'
        ),
        \'public\'=> true,
        \'hierarchical\'=> true
        );
    register_taxonomy(\'Tipos de Construção\',array(\'projetos\'), $args);
}
add_action(\'init\', \'tipos_construcao\');
任何帮助都将不胜感激!我一直在尝试几种解决方案,并尝试浏览其他网站,但没有找到解决方案。

我做了控制台。在筛选器中记录(结果)。js检查结果是什么,它只是不过滤,结果是所有的帖子。

再次感谢您!

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

如何使AJAX过滤器正常工作:正如我在评论中所说的,添加data-category 属性到<a> 拥有CSS类js-filter-itemforeach 在您的archive-projetos.php 模板:

// * Wrapped for brevity.
foreach ( $categories as $cat ) : ?>
    <li><a class="js-filter-item"
        href="<?= get_category_link( $cat->term_id ); ?>"
        data-category="<?= $cat->term_id; ?>"
    ><?= $cat->name; ?></a></li>
<?php endforeach; ?>
如果你想知道为什么要添加这个属性,那是因为filter.js, 脚本正在通过读取类别ID$(this).data(\'category\') 相当于$( this ).attr( \'data-category\' ).

中的filter_ajax() 中的函数functions.php, 替换此:

$query = new WP_Query($args);

if(isset($category)) {
    $args[\'category__in\'] = array($category);
}
使用此选项:

if ( ! empty( $category ) ) {
    $args[\'tax_query\'] = array(
        array(
            \'taxonomy\' => \'Tipos de Construção\',
            \'terms\'    => $category,
        ),
    );
}

$query = new WP_Query( $args );
一、 e.切换(的)位置new WP_Query() 电话和if 块),然后use the tax_query parameter 而不是category__in 这是默认值category 仅分类法。

也就是说filter_ajax() 功能,更换$category = $_POST[\'projetos\']; 具有$category = $_POST[\'category\']; 因为您的JS脚本正在名为category 而不是projetos.

但是,在尝试使用某个数组项之前,应该始终检查该数组项是否已实际设置,因此需要使用$category = $_POST[\'category\'] ?? \'\'; 或旧方法(PHP 7之前):$category = isset( $_POST[\'category\'] ) ? $_POST[\'category\'] : \'\';.

尽管Tipos de Construção 用作分类名称,即传递给的第一个参数register_taxonomy(), 你应该用一个像tipos_de_construcao 因为文档says:

$taxonomy is the name of the taxonomy. Name should only contain lowercase letters and the underscore character, and not be more than 32 characters long (database structure restriction). Default: None

因此,您应该尝试修复分类名称,即使用slug。这需要时间,但从长远来看,这将是一个更好的选择。=)

相关推荐

未发送从PHP文件到AJAX的响应

我试图从Php脚本向Ajax发送一些响应,但没有发送。下面是我的代码。目前,我正在发送虚拟数据,稍后将进行更改。。Php脚本。。 $response = [\'Successfull callback\',\'ndnvnvnsobdboi\',\'ijjijbujbhu\']; echo json_encode($response); die(); Ajax脚本。。。jQuery(do