2016-08-11 34 views
0

我是相對較新的WordPress。所以這可能不是最好的方法,甚至是可能的。有了這個說法,我願意提供更好的解決方案。WordPress的加載更多發佈通過按鈕點擊

我有一個主頁,將顯示最新的12個職位。 我想打一個按鈕,點擊會加載下一個4

當我有什麼目前是這樣的:

<?php query_posts('showposts=4&offset=12'); ?> 
<?php while (have_posts()): the_post(); ?> 
    //some html tags 
<?php endwhile; ?> 

這將加載後我13-16的細節。

我正在尋找一種方法,我可以把它放在一個函數中,然後通過jquery click()事件調用它,我可以使用某種類型的計數器來計算偏移量。像

var offSetCounter = 12; 

$(".btnLoadMore").click(function(){ 
    //php function call 
    loadmore(offSetCounter); 
    offSetCounter += 4; 
}); 

所以下次我點擊按鈕offSetCounter將是16等等。

在此先感謝。

+0

是什麼loadmore(offSetCounter)呢? – stweb

+0

希望這將是一個自定義php函數,將調用第一個塊中的代碼 – Radizzt

+0

在您的js/JQuery代碼中,您只能啓動對php的ajax請求,但不能php本身。 – stweb

回答

0

要在WordPress的運行試試這個:

PHP:

add_action('wp_ajax_nopriv_show_next_posts', 'show_next_posts'); 
function show_next_posts() { 
    $offset = $_POST['offset']; 
    $the_query = new new WP_Query(array('posts_per_page' => 4, 'offset' => $offset)); 



    while ($the_query->have_posts()) { 
     $the_query->the_post(); 
     echo '<div class="post_container">' . get_the_title() . '</div>'; 
    } 
    wp_reset_postdata(); 
    wp_die(); 
    return; 
} 

add_action('wp_head','add_ajaxurl'); 
function add_ajaxurl() { 
    $ajaxurl = admin_url('admin-ajax.php'); 
    echo '<script type="text/javascript"> 
     var ajaxurl ='.$ajaxurl.'; 
    </script>'; 

} 

JS:

jQuery('.btnLoadMore').click(function(){ 
    var offset = jQuery('.post_container').length(); 
    var data = { 
     'action': 'show_next_posts', 
     'offset': offset 
    }; 

    jQuery.post(ajaxurl, data, function(response) { 
     console.log(response); 
    }); 
});