当查询没有返回任何结果时,为什么没有显示“无结果”?

时间:2021-07-16 作者:Eland

I\'ve been following this tutorial for a simple AJAX filter search within wordpress:

https://itsmereal.com/simple-ajax-filter-search-for-wordpress/?unapproved=3915&moderation-hash=039ff3c1d56b57d1456ededcfa5ea219#comment-3915

I\'ve added some checkboxes into my form for the user to select one or more categories (custom taxonomy) to search the custom post type (courses)

if I search for something that exists, the checkbox filters work fine, but if I search for something I know doesn\'t exist, It does nothing and I just get a 200 code in XHR in inspector.

note: I tried deleting the wp_die(); function within the Ajax callback, this makes the no result message come up if the query yields no results, however if the query will yield results, nothing happens.

Here\'s my code in full

functions.php

// Scripts for Ajax Filter Search

function my_ajax_filter_search_scripts() {
    wp_enqueue_script( \'my_ajax_filter_search\', get_stylesheet_directory_uri(). \'/js/search-script.js\', array(), \'1.0\', true );
        wp_localize_script( \'my_ajax_filter_search\', \'jsData\',[
        \'ajaxUrl\' => admin_url(\'admin-ajax.php\'),
    ]);
}

// Shortcode: [my_ajax_filter_search]
function my_ajax_filter_search_shortcode() {

    my_ajax_filter_search_scripts(); // Added here

    ob_start(); ?>

        <div id="my-ajax-filter-search" class="text-left">
        <form action="" method="get">

            <input type="text" name="search" class="quicksearch mb-4" id="search-input" value="" placeholder="Search for a course..."><br>
                        <div class=" btn-group-toggle" data-toggle="buttons">

                            <?php
                            // Get the custom taxonomy\'s terms
                            $terms = get_terms(
                                array(
                                    \'taxonomy\'   => \'course_category\',
                                    \'hide_empty\' => false,
                                )
                            );

                            // Check if any term exists
                            if ( ! empty( $terms ) && is_array( $terms ) ) {
                                // Run a loop and print them all
                                foreach ( $terms as $term ) { ?>
                                    <?php echo \'<label class="btn btn-outline-secondary">
                                    <input type="checkbox" id="category" name="category" value="\' . $term->slug . \'">\' . $term->name . \'</label>\'; ?>
                                    <?php
                                }
                            }
                            ?>

                    </div><br>
            <input class="btn btn-primary" type="submit" id="submit" name="submit" value="Search">
        </form>

    </div>

    <?php
    return ob_get_clean();
}

add_shortcode (\'my_ajax_filter_search\', \'my_ajax_filter_search_shortcode\');


// Ajax Callback

add_action(\'wp_ajax_my_ajax_filter_search\', \'my_ajax_filter_search_callback\');
add_action(\'wp_ajax_nopriv_my_ajax_filter_search\', \'my_ajax_filter_search_callback\');

function my_ajax_filter_search_callback() {

    header("Content-Type: application/json");

    $meta_query = array(\'relation\' => \'AND\');

    if(isset($_GET[\'year\'])) {
        $year = sanitize_text_field( $_GET[\'year\'] );
        $meta_query[] = array(
            \'key\' => \'year\',
            \'value\' => $year,
            \'compare\' => \'=\'
        );
    }

    if(isset($_GET[\'rating\'])) {
        $rating = sanitize_text_field( $_GET[\'rating\'] );
        $meta_query[] = array(
            \'key\' => \'rating\',
            \'value\' => $rating,
            \'compare\' => \'>=\'
        );
    }

    if(isset($_GET[\'language\'])) {
        $language = sanitize_text_field( $_GET[\'language\'] );
        $meta_query[] = array(
            \'key\' => \'language\',
            \'value\' => $language,
            \'compare\' => \'=\'
        );
    }

    $tax_query = array();

        if(isset($_GET[\'catNames\'])) {
            $catNames = $_GET[\'catNames\'];
                error_log( \'MY STUFF var $catNames: \' . print_r( $catNames, true ) );
            foreach( $catNames as $catName ) {
                $tax_query[] = array(
                    \'taxonomy\'   => \'course_category\',
                                \'field\' => \'slug\',
                    \'terms\' => $catNames,
                );
            }
        }

    $args = array(
        \'post_type\' => \'courses\',
        \'posts_per_page\' => -1,
        \'meta_query\' => $meta_query,
        \'tax_query\' => $tax_query
    );

    if(isset($_GET[\'search\'])) {
        $search = sanitize_text_field( $_GET[\'search\'] );
        $search_query = new WP_Query( array(
            \'post_type\' => \'courses\',
            \'posts_per_page\' => -5,
            \'meta_query\' => $meta_query,
            \'tax_query\' => $tax_query,
            \'s\' => $search
        ) );

                //error_log( \'MY STUFF var $search_query: \' . print_r( $search_query, true ) );

    }

        else {
        $search_query = new WP_Query( $args );
    }

        error_log( \'MY STUFF: \' . print_r( $tax_query, true ) );

    if ( $search_query->have_posts() ) {

        $result = array();

        while ( $search_query->have_posts() ) {
            $search_query->the_post();

            $cats = strip_tags( get_the_category_list(", ") );
            $result[] = array(
                "id" => get_the_ID(),
                "title" => get_the_title(),
                "content" => get_the_content(),
                "permalink" => get_permalink(),
                "year" => get_field(\'year\'),
                "rating" => get_field(\'rating\'),
                "director" => get_field(\'director\'),
                "language" => get_field(\'language\'),
                "coursecats" => $cats,
                "imageUrl" => wp_get_attachment_url(get_post_thumbnail_id(get_the_ID()),\'full\')
            );
        }
        wp_reset_query();

        echo json_encode($result);

    } else {
        // no posts found
    }

    wp_die();

}

search-script.js

$ = jQuery;

var mafs = $("#my-ajax-filter-search");
var mafsResults = $("#my-ajax-filter-search-results");
var mafsForm = mafs.find("form");

mafsForm.submit(function(e){
    e.preventDefault();

   console.log("form submitted");

    if(mafsForm.find("#search-input").val().length !== 0) {
    var search = mafsForm.find("#search-input").val();
}

//console.log(\'search:\', search);

var catNames = [];
$.each($("input[name=\'category\']:checked"), function(){
    catNames.push($(this).val());
});

console.log(\'cats :\', catNames);

var data = {
    action : "my_ajax_filter_search",
    search : search,
    catNames: catNames
}

$.ajax({
        url : jsData.ajaxUrl,
        data : data,
        success : function(response) {
            mafsResults.find("div.results").empty();
            //$(\'.pagination\').hide();
            if(response) {
                for(var i = 0 ;  i < response.length ; i++) {
                     var html  = "<div class=\'col-md-4\' id=\'course-" + response[i].id + "\'>";
                         html += "  <a href=\'" + response[i].permalink + "\' title=\'" + response[i].title + "\'>";
                         html += "      <img src=\'" + response[i].imageUrl + "\' alt=\'" + response[i].title + "\' />";
                         html += "      <div class=\'movie-info\'>";
                         html += "          <h4>" + response[i].title + "</h4>";
                         html += "      </div>";
                         html += "  </a>";
                         html += "</div>";
                     mafsResults.find("div.results").append(html);
                }
            } else {
              mafsResults.find("div.results").empty();
                var html  = "<div class=\'no-result\'>No matching movies found. Try a different filter or search keyword</div>";
                mafsResults.find("div.results").append(html);
            }

        }
    });

});

Template File

<div class="filters">
    <?php echo do_shortcode(\'[my_ajax_filter_search]\'); ?>
</div>


<div id="my-ajax-filter-search-results">

    <?php
        $args = array(
            \'post_type\' => \'courses\',
            \'posts_per_page\' => 16
        );

        $default_query = new WP_Query( $args );
        if ( $default_query->have_posts() ) {
            echo \'<div class="results row">\';
            while ( $default_query->have_posts() ) {
                $default_query->the_post();
                ?>
                        
                                <div class="col-md-4 mb-4 mb-md-3">
                                    <a class="home-image-link" href="<?php the_permalink(); ?>">
                                        <div class="link-image">
                                            <div style="background:url(\'<?php echo get_the_post_thumbnail_url(); ?>\') center center no-repeat; background-size:cover; min-height:200px;">
                                            </div>
                                            <span class="bg-primary text-light mt-1 p-2 full-width d-inline-block">
                                                <?php the_title(); ?> <span class="float-right"><img src="/wp-content/themes/allintraining/img/chevron-right.svg" style="height:15px;" alt="chevron right"></span>
                                            </span>
                                        </div>
                                    </a>
                                </div>

                        <?php
            }
            wp_reset_postdata();
            echo \'</div>\';
        }
    ?>
</div>

Any help would be gratefully received, thanks in advance!

1 个回复
SO网友:Eland

设法解决了这个问题,因为@vancoder提到wp\\u die导致仍然有响应,并说改用die()。这不起作用,所以我改了json的发送方式。通过使用wp\\u send\\u json()uinstead,我们不需要在函数末尾使用die()或wp\\u die(),因为wp\\u send\\u json()包含wp\\u die()。这一切似乎都很有效。

update the callback in functions.php

    if ( $search_query->have_posts() ) {

        $result = array();

        while ( $search_query->have_posts() ) {
            $search_query->the_post();

            $cats = strip_tags( get_the_category_list(", ") );
            $result[] = array(
                "id" => get_the_ID(),
                "title" => get_the_title(),
                "content" => get_the_content(),
                "permalink" => get_permalink(),
                "year" => get_field(\'year\'),
                "rating" => get_field(\'rating\'),
                "director" => get_field(\'director\'),
                "language" => get_field(\'language\'),
                "coursecats" => $cats,
                "imageUrl" => wp_get_attachment_url(get_post_thumbnail_id(get_the_ID()),\'full\')
            );
        }
        wp_reset_query();

        //echo json_encode($result); - Old way
                wp_send_json($result); // new way (includes wp_die())

    } else {

    }

}

相关推荐

WP AJAX帖子过滤器>使用空值执行某些操作

我的AJAX帖子分类过滤器在我的网站上运行良好,这要感谢像你们这样的人的慷慨帖子。我似乎找不到的是,如果所选值为空,如何在AJAX/jQuery脚本中执行某些操作。以下是我的脚本:$(function(){ var event_change = $(\'#event-change\'); $( ".select" ).selectCF({ change: function(){ var value = $(this).val(