Skip to content
Advertisement

AJAX function in the widget class

I created a WordPress Widget which get the recent posts, first get a specific number of posts, then there is a button to get more posts by AJAX.

The full Widget code

/* recent posts Widget
 ================================*/
 class recent_posts extends WP_Widget {

public function __construct() {
    // widget actual processes  
    parent::__construct(
        'recent_posts', // Base ID
        'recent posts', // Name
        array( 'description' => __( 'Show the recent posts', 'foo'))
         // Args
    );
    add_action('wp_ajax_ajaxloadMore', array($this,'ajaxloadMore'));
    add_action('wp_ajax_nopriv_ajaxloadMore', array($this,'ajaxloadMore'));
}

// i remove form and update functions to reduce the code :)
public function widget( $args, $instance ) {
    extract( $args );
    $title = $instance['title'];
    $number = $instance['num'];
    // function for filter posts list where first post is the current post 
    if(is_single()){
        function filter_where( $where = ''){
            $where .= " AND post_date <= '" .get_the_date('Y-m-d H:i:s'). "'";
            return $where;
        }
        add_filter( 'posts_where', 'filter_where' );
    }
    //select the current category ID
    $category = get_the_category($post->ID);
    $catid = $category[0]->cat_ID;
    query_posts('cat='.$catid.'&showposts='.$number.'');

    echo $before_widget;
    echo $before_title .$title.$after_title;
    echo '<ul class="recent_posts">';
    while(have_posts()) : the_post();
        echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li><br>';
    endwhile;
    wp_reset_query();
    echo '</ul>';
    echo '<br><input type="button" id="loadMoreW" value="Load More" data-offset="'.$number.'">';
    echo $after_widget;
}
// the ajax function
public function ajaxloadMore(){
    // first need to get $catid and $number values from function widget
    // second need to declare filter_where function to filter the query_posts here
    query_posts('cat='.$catid.'&showposts='.$number.'&offset='.$_POST['offset'].'');

    while(have_posts()) : the_post();
        echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li><br>';
    endwhile;
    wp_reset_query();
    die();
 }
}

And this is the AJAX code to get ajaxloadMore function output and append to the ul tag

$('#loadMoreW').on('click',function(){
    $.ajax({
        url: 'wp-admin/admin-ajax.php',
        type: 'POST',
        data: {
            action : 'ajaxloadMore',
            offset: $('#loadMoreW').data('offset') 
            },

        success: function(data){
            $('#loadMoreW').data('offset', $('#loadMoreW').data('offset')+4);
            $(data).appendTo('.recent_posts');
        }
    });

  });

How to get $catid and $number variables from the function widget and put them in ajaxloadMore function?

How to filter query_posts in ajaxloadMore function like the function widget by the same function filter_where?

Advertisement

Answer

Both questions have the same answer, use the same method as in data-offset:

printf(
    '<br><input type="button" id="loadMoreW" value="Load More" data-offset="%s" data-catid="%s" data-where="%s">',
    $number,
    $catid,
    get_the_date('Y-m-d H:i:s')
);

then

$.ajax({
    url: '{$ajax_url}',
    type: 'POST',
    data: {
        action : 'ajaxloadMore',
        offset: $('#loadMoreW').data('offset') ,
        catid: $('#loadMoreW').data('catid') ,
        where: $('#loadMoreW').data('where')
        },

and finally use $_POST['catid'] and $_POST['where'] in the ajaxloadMore() function.

I built the $ajax_url with $ajax_url = admin_url('admin-ajax.php');.

But, nonetheless, try to use AJAX in WordPress like this and don’t use query_posts.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement