admin管理员组

文章数量:1122846

I want to get posts with ajax by click function.

Jquery

$(".get-posts").click(function(){

  $.ajax({  
    type: 'POST',  
    url: '<?php echo admin_url('admin-ajax.php');?>',  
    data: { action : 'get_ajax_posts' },  
    success: function(){  
       // ???
    }
  });  
});

Php

function get_ajax_posts() {
    // Query Arguments
    $args = array(
        'post_type' => array('products'),
        'post_status' => array('publish'),
        'posts_per_page' => 40,
        'nopaging' => true,
        'order' => 'DESC',
        'orderby' => 'date',
        'cat' => 1,
    );

    // The Query
    $ajaxposts = new WP_Query( $args );

    // The Loop
    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
                get_template_part('products');
        }
    } else {
        get_template_part('none');
    }
    /* Restore original Post Data */
    wp_reset_postdata();
}
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');

I'm blocked here.

I want to get posts with ajax by click function.

Jquery

$(".get-posts").click(function(){

  $.ajax({  
    type: 'POST',  
    url: '<?php echo admin_url('admin-ajax.php');?>',  
    data: { action : 'get_ajax_posts' },  
    success: function(){  
       // ???
    }
  });  
});

Php

function get_ajax_posts() {
    // Query Arguments
    $args = array(
        'post_type' => array('products'),
        'post_status' => array('publish'),
        'posts_per_page' => 40,
        'nopaging' => true,
        'order' => 'DESC',
        'orderby' => 'date',
        'cat' => 1,
    );

    // The Query
    $ajaxposts = new WP_Query( $args );

    // The Loop
    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
                get_template_part('products');
        }
    } else {
        get_template_part('none');
    }
    /* Restore original Post Data */
    wp_reset_postdata();
}
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');

I'm blocked here.

Share Improve this question asked Apr 29, 2018 at 7:11 wpdevwpdev 5492 gold badges13 silver badges28 bronze badges 3
  • read this api.jquery.com/jQuery.ajax. and then use .done(... and read what is in data. – mmm Commented Apr 29, 2018 at 7:25
  • 1 And what's the question?? PS. You don't have to do wp_reset_postdata() in AJAX callbacks, but you do have to do die in there. – Krzysiek Dróżdż Commented Apr 29, 2018 at 7:39
  • How i can print template_part? With echo? – wpdev Commented Apr 29, 2018 at 7:51
Add a comment  | 

1 Answer 1

Reset to default 11

Option 1

The simple way - return all the posts in JSON format and loop through them in JavaScript

PHP:

function get_ajax_posts() {
    // Query Arguments
    $args = array(
        'post_type' => array('products'),
        'post_status' => array('publish'),
        'posts_per_page' => 40,
        'nopaging' => true,
        'order' => 'DESC',
        'orderby' => 'date',
        'cat' => 1,
    );

    // The Query
    $ajaxposts = get_posts( $args ); // changed to get_posts from wp_query, because `get_posts` returns an array

    echo json_encode( $ajaxposts );

    exit; // exit ajax call(or it will return useless information to the response)
}

// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');

JavaScript:

$.ajax({
    type: 'POST',
    url: '<?php echo admin_url('admin-ajax.php');?>',
    dataType: "json", // add data type
    data: { action : 'get_ajax_posts' },
    success: function( response ) {
        $.each( response, function( key, value ) {
            console.log( key, value ); // that's the posts data.
        } );
    }
});

Option 2

Get HTML content and print it to the screen.

PHP:

function get_ajax_posts() {
    // Query Arguments
    $args = array(
        'post_type' => array('products'),
        'post_status' => array('publish'),
        'posts_per_page' => 40,
        'nopaging' => true,
        'order' => 'DESC',
        'orderby' => 'date',
        'cat' => 1,
    );

    // The Query
    $ajaxposts = new WP_Query( $args );

    $response = '';

    // The Query
    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
            $response .= get_template_part('products');
        }
    } else {
        $response .= get_template_part('none');
    }

    echo $response;

    exit; // leave ajax call
}

// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');

JavaScript:

   $.ajax({
        type: 'POST',
        url: '<?php echo admin_url('admin-ajax.php');?>',
        dataType: "html", // add data type
        data: { action : 'get_ajax_posts' },
        success: function( response ) {
            console.log( response );

            $( '.posts-area' ).html( response ); 
        }
    });

In the second example, change the .posts-area selector to the one you want to print in.

The console.log is just that you will be able to see the returning information from the AJAX call in the console. You should remove it after you finished.

本文标签: Get posts with ajax