2017-01-12 39 views
0

我嘗試在Wordpress中的引導模式窗口中打開帖子。目標是通過Ajax加載發佈的內容,因爲模式窗口放置在頁腳中。WordPress的:使用AJAX將帖子內容傳遞到div

這是我到現在爲止:

我的模板部分是在頁腳加載(modal.php)

<div class="modal fade" id="myModal-<?php the_ID(); ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> 
<div class="modal-dialog" role="document"> 
    <div class="modal-content"> 
     <div class="modal-header"> 
      <h5 class="modal-title" id="exampleModalLabel"><?php the_title();?></h5> 
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button> 
     </div> 
     <div class="modal-body"> 
      <?php the_content();?> 
     </div> 
     <div class="modal-footer"> 
      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> 
      <button type="button" class="btn btn-primary">Save changes</button> 
     </div> 
    </div> 
</div> 

正如你所看到的,我會需要將一些內容從查詢傳遞到頁腳中的div。

我的鏈接,即打開模態窗口:

<a href="#" class="modal-link" data-toggle="modal" data-target="#myModal-<?php the_ID(); ?>" >View more</a> 

那麼這將是解決這個最乾淨的方式是什麼?

感謝您的任何建議! 卡拉

回答

1

您可以使用worpdress的REST API(在http://v2.wp-api.org/)這種方式,您可以加載文章內容與阿賈克斯並將它添加到您的DIV,你認爲合適

例子:

$.get('http://demo.wp-api.org/wp-json/wp/v2/posts/470',function(data){ 
    data = JSON.parse(data); 
    $('div.selector').html(data.content); 
}) 

我希望這有助於

0

首先,您必須聲明中的header.php或頁面AJAX網址,其中包括Ajax調用:

<script type="text/javascript" language="javascript"> 
    var ajax_url = "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php"; 
</script> 

然後,在你的當前主題開放function.php並宣佈一個Ajax調用:

function implement_ajax() { 
    include(TEMPLATEPATH . '/ajax_return.php'); 
} 

add_action('wp_ajax_my_special_action', 'implement_ajax'); 
add_action('wp_ajax_nopriv_my_special_action', 'implement_ajax'); 

現在,你必須設置你想要的工作頁面內AJAX調用。

<script type="text/javascript"> 
jQuery(function(){ 
    jQuery('.modal-link').click(function(){ 
     var mypostid = ''; Will be contained element that allows you to manage dinamical content (such as post_id). 
     jQuery.post(ajax_url, {action : 'my_special_action', post_id : mypostid}, return_function, 'JSON'); 
    }); 
}); 
</script> 

因此,在您當前的主題中創建ajax_return.php。該文件將包含查詢,爲您的模態提供dinamical內容。例如:

query_posts('page_id=' . $_POST['id']); 
if(have_posts()) while(have_post()) : the_post(); 
    $dinamic_post_content = get_the_content(); 
endwhile; 

return json_encode(array('return' => $dinamic_post_content)); 
exit; 

jQuery.post後,你必須調用 「return_function」,讓您管理響應和正確設置模態:

function return_function(data) 
{ 
    jQuery('.modal-body').html(data.return); 
} 
相關問題