我真的希望有人能帮忙。当点击“加载新消息”按钮时,我想在主页上随机加载帖子。
我们在Wordpress中加载了200条短消息作为帖子。在主页上,我们希望人们能够单击按钮重新加载新消息,但页面不会刷新。
请问有人能帮忙做这件事吗?
感谢您抽出时间。AB公司
我真的希望有人能帮忙。当点击“加载新消息”按钮时,我想在主页上随机加载帖子。
我们在Wordpress中加载了200条短消息作为帖子。在主页上,我们希望人们能够单击按钮重新加载新消息,但页面不会刷新。
请问有人能帮忙做这件事吗?
感谢您抽出时间。AB公司
过去几天我一直在使用ajax—我喜欢走钩子路线,所以首先让我们设置ajax调用:
$(\'#buttonID\').click(function(){
$.ajax({
url: \'/wp-admin/admin-ajax.php\',
type: \'GET\',
data: {
\'action\' : \'implement_ajax\'
},
dataType: \'html\'
})
.success(function(results){
$(\'#ContentWrapper\').html(results);
})
.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
});
该操作就是您想要称为ajax函数的操作-您可以将其放在函数文件中:function implement_ajax() {
$ajaxQuery = new WP_Query(array(\'post_type\' => \'post\', \'posts_per_page\' =>9, \'orderby\' => \'rand\'));
ob_start();
if($ajaxQuery->have_posts()) :
while($ajaxQuery->have_posts()) : $ajaxQuery->the_post();
?>
<h1>Title: <?php the_title(); ?></h1>
<?php /** Normal Loop Stuff **/ ?>
<?php
endwhile;
endif;
$htmlContent = ob_get_clean();
echo $htmlContent;
exit;
}
add_action(\'wp_ajax_nopriv_implement_ajax\', \'implement_ajax\');
add_action(\'wp_ajax_implement_ajax\', \'implement_ajax\');
我们打电话ob_start
记录我们回显的每一次内容,所有html和变量,这样就不会过早地返回到ajax调用。然后我们通过ob_get_clean()
并将html内容返回到我们的ajax调用中,然后我们可以将其粘贴到任何地方。一旦带回来,你可以在它或任何你需要的东西上添加一些奇特的smancy淡入动画,使它看起来很酷:D!
这只是一个类似的例子,可以做一些你有疑问的事情。每次用户点击一个按钮,它都会随机加载帖子。
HTML:
<input type="button" id="load" value="Load random posts" />
<div id="posts"></div>
JQuery: <script type="text/javascript">
$(document).ready(function(e) {
$("#load").on(\'click\', function(){
$.post(\'any_page.php\',
function(data){
$(\'#posts\').html(data);
});
});
});
</script>
现在您的any_page.php
这将加载立柱。任何\\u页。php:
<?php
$args = array(
\'post_type\' => \'post\',
\'posts_per_page\' =>9,
\'orderby\' => \'rand\'
);
$the_query = new WP_Query($args);
?><?php if ( $the_query->have_posts() ) { ?>
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<?php the_title() . "<br>"; ?>
<?php endwhile; ?>
<?php
} else { ?>
<h2>Oh No!!</h2>
<p><?php _e(\'Sorry, no posts matched your criteria.\'); ?></p>
<?php }
wp_reset_postdata(); /* Restore original Post Data */
?>
这只会得到帖子的标题。如果您需要包含缩略图和内容的帖子,则需要使用the_content
方法有关内容的更多信息可在此处找到我希望这有帮助我对jQuery和插件有问题,控制台错误显示jQuery没有定义。我不明白的是,只有当我将其加载到生产服务器时,它才会失败,在我的本地dev安装上,它工作得很好。ReferenceError:未定义jQuery。插件代码:add_filter( \'wp_footer\', \'enqueue_footer_scripts\', 9); add_filter( \'wp\', \'enqueue_styles\', 11); function enqueue_footer_scr