最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - How to hook the pre_get_posts filter via ajax call

programmeradmin5浏览0评论

I need to add the filter option on search page in wordpress site. Created dropdown with two options. one is 'Recently Added' and 'Last Updated'. We need to filter the courses by selecting dropdown.

I have created dropdown and written jquery to hook the filter using ajax call method. Created filter.php file and hook the pre_get_posts method inside this file. If we select the dropdown it need to hook that filter but it is not get hooked. Also i have tried to Pass the parameter via ajax call but it's not working. Please share ideas to achieve the filter options.

HTML

<select id="filter">
    <option value='last_updated_posts' id='recently_added'>
        Last Updated
    </option>
    <option value="recently_added_posts" id='last_updated'>
        Recently Added
    </option>
</select>

Custom.js

  jQuery("#filter").change(function(){
      var selected_option=jQuery("#filter option:selected").val();
        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {'action' :selected_option },
            success: function(response){alert(response);}
        });
    });

filter.php

<?php
add_action('wp_ajax_recently_added_posts', 'recently_added_posts');
add_action('wp_ajax_nopriv_recently_added_posts', 'recently_added_posts');
if($_POST['action'] =='recently_added_posts' ){
function recently_added_posts($query) {
     if ($query->is_search() && !is_admin() ) {
        $query->set('post_type',array('sfwd-courses','sfwd-lessons','sfwd-topic'));
        $query->set('orderby',array(
        'post_type'=> 'ASC',
        'date' => 'DESC')
    );
    return $query;         
    die();
}
add_filter('pre_get_posts','recently_added_posts'); 
}
}
add_action('wp_ajax_last_updated_posts', 'last_updated_posts');
add_action('wp_ajax_nopriv_last_updated_posts', 'last_updated_posts');
if($_POST['action'] =='last_updated_posts' ){
function last_updated_posts($query) {
    if ($query->is_search() && !is_admin() ) {
        $query->set('post_type',array('sfwd-courses','sfwd-lessons','sfwd-topic'));
        $query->set('orderby',array(
        'post_type'=> 'ASC',
        'modified' => 'DESC')
    );
    }
    return $query;
    die();
} 
add_filter('pre_get_posts','last_updated_posts');
}
function ajaxurl_filter() {
   echo '<script type="text/javascript">
           var ajaxurl = "' . admin_url('admin-ajax.php') . '";
         </script>';
}
add_action('wp_head', 'ajaxurl_filter');
?>

Thanks in advance!

I need to add the filter option on search page in wordpress site. Created dropdown with two options. one is 'Recently Added' and 'Last Updated'. We need to filter the courses by selecting dropdown.

I have created dropdown and written jquery to hook the filter using ajax call method. Created filter.php file and hook the pre_get_posts method inside this file. If we select the dropdown it need to hook that filter but it is not get hooked. Also i have tried to Pass the parameter via ajax call but it's not working. Please share ideas to achieve the filter options.

HTML

<select id="filter">
    <option value='last_updated_posts' id='recently_added'>
        Last Updated
    </option>
    <option value="recently_added_posts" id='last_updated'>
        Recently Added
    </option>
</select>

Custom.js

  jQuery("#filter").change(function(){
      var selected_option=jQuery("#filter option:selected").val();
        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: {'action' :selected_option },
            success: function(response){alert(response);}
        });
    });

filter.php

<?php
add_action('wp_ajax_recently_added_posts', 'recently_added_posts');
add_action('wp_ajax_nopriv_recently_added_posts', 'recently_added_posts');
if($_POST['action'] =='recently_added_posts' ){
function recently_added_posts($query) {
     if ($query->is_search() && !is_admin() ) {
        $query->set('post_type',array('sfwd-courses','sfwd-lessons','sfwd-topic'));
        $query->set('orderby',array(
        'post_type'=> 'ASC',
        'date' => 'DESC')
    );
    return $query;         
    die();
}
add_filter('pre_get_posts','recently_added_posts'); 
}
}
add_action('wp_ajax_last_updated_posts', 'last_updated_posts');
add_action('wp_ajax_nopriv_last_updated_posts', 'last_updated_posts');
if($_POST['action'] =='last_updated_posts' ){
function last_updated_posts($query) {
    if ($query->is_search() && !is_admin() ) {
        $query->set('post_type',array('sfwd-courses','sfwd-lessons','sfwd-topic'));
        $query->set('orderby',array(
        'post_type'=> 'ASC',
        'modified' => 'DESC')
    );
    }
    return $query;
    die();
} 
add_filter('pre_get_posts','last_updated_posts');
}
function ajaxurl_filter() {
   echo '<script type="text/javascript">
           var ajaxurl = "' . admin_url('admin-ajax.php') . '";
         </script>';
}
add_action('wp_head', 'ajaxurl_filter');
?>

Thanks in advance!

Share Improve this question asked Jan 30, 2020 at 14:18 saravanan kanagarajsaravanan kanagaraj 12 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

You can apply a custom filter on your WP_Query that is on your ajax callback function like this:

$my_query = apply_filters('my_plugin_pre_get_posts', (new WP_Query($args)));

Now you can use your existing pre_get_posts function for ajax calls also,

add_action('pre_get_posts', 'myplugin_filter_posts'); // For All WP_Query instances
add_filter('my_plugin_pre_get_posts', 'myplugin_filter_posts'); // For ajax

function myplugin_filter_posts($query) {
    if (defined('DOING_AJAX') && DOING_AJAX) {
        // Your code executed only on ajax requests
    }

    // Codes here Execute everywhere

    return $query; // Return $query is required for the filter we defined
}

You can tweak it to achieve what you wish

You're not actually executing a new WP_Query so no results are being returned. Try this...

<?php
add_action('wp_ajax_recently_added_posts', 'recently_added_posts');

if ($_POST['action'] =='recently_added_posts' ) {
    function recently_added_posts( $query ) {
        // Setup query
        global $wp_query;

        // Define arguments
        $query_args = array( 
            'post_type' => array( 
                'sfwd-courses', 
                'sfwd-lessons', 
                'sfwd-topic' ),
            'orderby' => array(
                'post_type'=> 'ASC',
                'date' => 'DESC'
            ),
            'posts_per_page' => 10, // (change if needed)

        );

        $wp_query = new WP_Query($query_args);

        // You can then loop through the posts in your themes template file
        // NOTE: may need to play around this but if you just return the query you'll see all the posts in the front end
        $_template_file = THEME_DIR . 'search.php';
        load_template( $_template_file, $require_once = true );

        die();
    }

    // This will now work because the query was instantiated...
    add_filter('pre_get_posts','recently_added_posts'); 
}
?>
发布评论

评论列表(0)

  1. 暂无评论