Uma*_*zaq 1 php ajax wordpress jquery twitter-bootstrap-3
我已经使用 _S 入门主题从头开发了自定义主题。我在通过点击阅读更多按钮的 ajax 请求获取 Wordpress 下一篇文章时遇到问题。我已经尝试了很多文章,特别是以下文章,但没有运气。
参考链接:
我试过使用上面的自定义循环并使用 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>
Run Code Online (Sandbox Code Playgroud)
我在这个问题上搞砸了超过 4-5 天,所以任何人都可以通过工作解决方案帮助我解决这个问题,这将是非常可观的。
提前致谢。
我也许有你的解决方案。
首先确保在你的主题中有一个脚本入队
wp_enqueue_script('your_js_hanlde', get_template_directory_uri() . '/js/your_js_hanlde.js', array('jquery'), '1.0.0', true );
Run Code Online (Sandbox Code Playgroud)
然后本地化添加一个函数在你的dom中添加一个js var
wp_localize_script('your_js_hanlde', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
Run Code Online (Sandbox Code Playgroud)
在您的 js 中,在“加载更多”按钮上的“单击”上添加一个事件
传递一个动作名称和你在你的 dom 中的文章数量,响应在你的按钮“加载更多”之前添加内容
$("#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]);
}
});
});
Run Code Online (Sandbox Code Playgroud)
在你的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' );
Run Code Online (Sandbox Code Playgroud)
它对我有用。我希望对你有帮助。
| 归档时间: |
|
| 查看次数: |
7787 次 |
| 最近记录: |