簡體   English   中英

Wordpress:使用AJAX將帖子內容傳遞到div中

[英]Wordpress: Passing post content into div using AJAX

我嘗試在Wordpress的引導模式窗口中打開帖子。 目標是通過將模式窗口放在頁腳中,通過Ajax加載帖子內容。

這是我到目前為止所擁有的:

我的模板部分已加載到頁腳(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>

那么解決這個問題的最干凈的方法是什么?

感謝您的任何建議! 卡拉

您可以將REST API用於worpdress(位於http://v2.wp-api.org/ ),這樣您可以使用ajax加載帖子內容,並根據需要將其附加到div

例:

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

我希望這有幫助

首先,您必須在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。 該文件將包含查詢,為您的模態提供令人難忘的內容。 例如:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM