Question

I'm using wp_localize_script to send post data to ajax.

wp_localize_script( 'my-script.js', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
add_action( 'wp_ajax_load_more_posts', 'ajax_posts' );

Sending post data to ajax:

function ajax_posts(){
    global $post;
    $args = array('post_type'=>'post', 'posts_per_page'=> 2);
    $posts_arr=[];
    $query = new WP_Query($args);
    if($query->have_posts()):
        while($query->have_posts()):$query->the_post();

            $posts_arr[] = $post;

        endwhile;
        wp_reset_postdata();

    endif;
    wp_send_json_success(array('post'=>$posts_arr));
}

In my ajax success function I'm using the following to append posts to the HTML:

success:function(response){

     var post_data = response.data.post;

     $.each(post_data, function(index, value) {

        $("#content").append('<a href="How can I get the post URL here?">' + value.post_title + '</a>');

    });          

}

It adds 2 posts to the HTML. It works well but how can I also add the post url to the ajax_posts() php function and pass it to ajax and use?

This is the data I'm getting from ajax:

enter image description here

Is it possible to also add the post urls to the post arrays?

Note: I'm using ajax for loading more posts when clicking a button but simplified the code here. I cannot add php directly to the js. It must be sent from the ajax_posts() php function to ajax in my js.

Was it helpful?

Solution

Yes that would be easy. You can use the get_the_permalink() function to retrieve a post's link. Here's how to do it:

// You are storing the post data here
$posts_arr[] = $post;

// Add the URL to the same array element
$posts_arr[]['url'] = get_the_permalink();

You can get the index of the current post in the loop by using the $query->current_post method, so I suggest you use that as the key of your array:

// You are storing the post data here
$posts_arr[ $query->current_post ] = $post;

// Add the URL to the same array element
$posts_arr[ $query->current_post ]['url'] = get_the_permalink();
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top