简体   繁体   中英

WordPress send post URL to ajax

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:

图片链接

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.

You could simply do something like this:

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[] = array(
                'permalink' => get_permalink(),
                'ID' => $post->ID,
                'post_title' => $post->post_title,
                'post_content' => $post->post_content,
                'post_author' => $post->post_author,
                'post_date' => $post->post_date
                // Add more fields as needed here
            );

        endwhile;
        wp_reset_postdata();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM