[英]WordPress send post URL to ajax
我正在使用wp_localize_script
將發布數據發送到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' );
發送帖子數據到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));
}
在我的ajax成功函數中,我使用以下內容將帖子追加到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>');
});
}
它將2個帖子添加到HTML。 它運作良好,但如何將發布網址也添加到ajax_posts()
php函數並將其傳遞給ajax並使用?
這是我從ajax獲取的數據:
是否還可以將帖子網址添加到帖子數組?
注意:單擊按鈕時,我正在使用ajax加載更多帖子,但此處簡化了代碼。 我無法將php直接添加到js中。 它必須從php函數ajax_posts()
發送到我的js中的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[] = 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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.