我从零开始就用_S初学者主题开发了自定义主题。我有问题通过ajax请求获取Wordpress下一篇文章,点击read按钮。我已经尝试过很多文章,特别是下面的文章,但是没有运气。
参考链接:
我试过使用上面的自定义循环,并使用jquery脚本添加自定义函数,但不知何故,它不起作用。
下面是循环代码示例:
循环在index.php中的应用
<?php query_posts('showposts=5'); if (have_posts()) : while (have_posts()) : the_post(); ?>
<article class="post-item">
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
</article>
<?php endwhile; ?>
<?php else : ?>
<h2>Sorry no posts are created yet.</h2>
<p>Please create some posts to see it in action.</p>
<?php endif; wp_reset_query(); ?>
<button class="load-more-btn">Load More</button>我处理这个问题超过4-5天,所以任何人都可以帮助我解决这个问题的工作解决方案将是非常感谢的。
提前谢谢。
发布于 2015-11-30 15:40:03
我也许能给你一个解决办法。
首先,确保在主题中有一个脚本队列。
wp_enqueue_script('your_js_hanlde', get_template_directory_uri() . '/js/your_js_hanlde.js', array('jquery'), '1.0.0', true );然后本地化添加一个函数,在您的dom中添加js var。
wp_localize_script('your_js_hanlde', 'ajaxurl', admin_url( 'admin-ajax.php' ) );在js中,在“加载更多”按钮的“单击”上添加一个事件。
传递操作名称和在您的位置上的文章计数,响应在按钮“load more”之前添加内容。
$("#load_more").click(function()
{
$.post(ajaxurl,
{
'action': 'your_load_more',
'count': $("article.post-item").length
},
function(response)
{
var posts = JSON.parse(response);
for( var i = 0; i < posts.length; i++ )
{
if( posts[i] == "0" )
$("#load_more").fadeOut();
else
$("#load_more").before(posts[i]);
}
});
});在functions.php中创建一个函数
function your_load_more()
{
$count = $_POST["count"];
$cpt = 1;
$args = array(
'posts_per_page' => -1,
'post_type' => 'post', // change the post type if you use a custom post type
'post_status' => 'publish',
);
$articles = new WP_Query( $args );
$ar_posts = array();
if( $articles->have_posts() )
{
while( $articles->have_posts() )
{
$articles->the_post();
$one_post = "";
if( $cpt > $count && $cpt < $count+6 )
{
$one_post .= "<article id='" . get_the_id() . "' class='post-item'>";
$one_post .= "<h3>" . get_the_title() . "</h3>";
$one_post .= "</article>";
$ar_posts[] = $one_post;
if( $cpt == $articles->found_posts )
$ar_posts[] = "0";
}
$cpt++;
}
}
echo json_encode($ar_posts);
die();
}
add_action( 'wp_ajax_your_load_more', 'your_load_more' );
add_action( 'wp_ajax_nopriv_your_load_more', 'your_load_more' );对我来说很管用。我希望这对你有帮助。
https://stackoverflow.com/questions/33999193
复制相似问题