2013-03-14 146 views
6

我花了數小時閱讀和試用教程。我似乎找不到解決方案,我知道它應該很容易,但我與AJAX鬥爭。 :(如何使用Ajax加載Wordpress帖子onclick

我要發佈的內容從一個div鏈路負載。 下面是我。有人可以幫我與JavaScript的一面呢?謝謝!

<ul> 
    <?php query_posts('post_type=artwork&posts_per_page=-1'); ?> 
    <?php if(have_posts()) : while(have_posts()) : the_post(); ?> 
    <li class="mytab"> 
     <span> 
     <h3><?php the_title(); ?></h3> 
     <a href="#"><?php the_post_thumbnail('Project'); ?></a> 
     </span> 
    </li> 
    <?php endwhile; endif; wp_reset_query(); ?> 
</ul> 

<div id="loadAjaxHere"></div> 

我希望加載這個在格碼#loadAjaxHere

<div class="myArtwork"> 
    <h2><?php the_title(); ?></h2> 
    <div class="text"><?php the_content(); ?></div> 
</div> 

謝謝你的幫助!

+0

你用什麼來定義你想要檢索哪個帖子?什麼是附加了點擊功能的元素?你熟悉functions.php文件嗎? – Ohgodwhy 2013-03-14 06:10:57

+0

您必須在JavaScript端包含wp-blog-header.php。 – 2013-03-14 07:40:26

+0

Try: $ folder = substr(substr($ _ SERVER [「REQUEST_URI」],1),0,strpos(substr($ _ SERVER [「REQUEST_URI」],1),「/」)); $ ajax_url = realpath($ _ SERVER [「DOCUMENT_ROOT」])。'/'。$ folder。'/ wp-blog-header.php'; require($ ajax_url); 位於您的外部ajax請求頁面的頂部。 – 2013-03-14 07:46:07

回答

10

好吧, 我覺得我已經審判的一個漫長的過程後,解決了這個和錯誤。

這似乎是工作,但請讓我知道這是不是做的這個

JavaScript中的正確方法:

jQuery.noConflict(); 
jQuery(document).ready(function($){ 
    $.ajaxSetup({cache:false}); 
    $("a.ajax").click(function(){ 
     var post_url = $(this).attr("href"); 
     var post_id = $(this).attr("rel"); 
     $("#tabs").html('<div class="loading">loading...</div>'); 
    $("#tabs").load(post_url); 
    return false; 
    }); 
}); 

的頁面,在這裏我想顯示帖子內容(我使用自定義文章類型稱爲「藝術品」。

<ul class="container"> 
    <?php query_posts('post_type=artwork&posts_per_page=-1'); ?> 
    <?php if(have_posts()) : while(have_posts()) : the_post(); ?> 
    <li class="mytab"> 
    <h3><?php the_title(); ?></h3> 
    <a href="<?php the_permalink(); ?>" rel="<?php the_ID(); ?>" class="ajax"><?php the_post_thumbnail('Project'); ?></a> 
    </li> 
    <?php endwhile; endif; wp_reset_query(); ?> 
</ul> 

<!-- LOAD SINGLE POST CONTENT IN #TABS --> 
<div id="tabs"></div> 

和單後「單artwork.php」注意:不要使用get_header或get_footer等:

<?php if(have_posts()) : while(have_posts()) : the_post(); ?> 
    <div class="tabcontent" id="tab-<?php the_ID(); ?>"> 
    <?php the_content(); ?> 
    </div> 
<?php endwhile; endif; ?> 

謝謝!

3

我想補充,如果你只是想在一個職位的一部分來加載,你可以ammend

$("#tabs").load(post_url); 

$("#tabs").load(post_url + ".tabcontent"); 

這將在一切只加載在div.tabcontent

+0

在逗號和點之間使用空格... $(「#tabs」)。load(post_url +'.tabcontent'); – 2017-01-23 18:02:00

3

Barry的答案對於能夠通過在URL末尾添加css選擇器表達式來加載部分頁面是正確的。然而,將需要的URL和選擇之間的空間,像這樣:

$("#tabs").load(post_url + " .tabcontent"); 

否則傳遞給​​字符串是http://example.com.tabscontent。但它應該是http://example.com .tabscontent

此外,使用此方法的智慧詞將阻止jQuery加載並執行<script>標記中的任何代碼。但是,僅使用.load(post_url);而沒有選擇器將成功加載並執行代碼<script>標記。

閱讀更多關於here