[英]Create a widget in wordpress to display both most recent and most popular posts
我正在构建一个功能以在WordPress中显示我的最新帖子,并且我想知道如何返回其中的一些帖子:
到目前为止,这是我的代码:
function wpb_set_post_views($postID) {
$count_key = 'wpb_post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
我根据关于如何显示没有插件的最新帖子的想法复制了一条建议。 到目前为止,一切都很好,只不过我需要返回一些东西来创建一个小部件以在最新和最受欢迎之间切换。 最受欢迎的小部件稍微容易一些,例如:
function get_recent_posts($count){
$args = [
'numberposts' => $count,
'offset' => 0,
'category' => 0,
'orderby' => 'post_date',
'order' => 'DESC',
'include' => '',
'exclude' => '',
'meta_key' => '',
'meta_value' =>'',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true
];
return wp_get_recent_posts( $args );
}
这就是我可以在它们之间切换的部分:
function get_blog_posts($count , $type='recent'){
if($type=='recent'){
$posts = get_recent_posts($count);
} else {
$posts = wpb_set_post_views(get_the_ID());
}
var_dump($posts);
die();
return $posts;
}
正如我所说,我正在尝试构建它,此刻,我正在转储数组以查看它们是否像我方面那样工作。 如果我切换到流行,我将获得一个NULL值,但是如果我尝试返回带有
return function wpb_set_post_views($postID);
我忘了提到我将以这种方式在模板中调用函数:
<?php if($blog_posts = get_blog_posts( wp_kses_post($instance['posts_type']) )):
foreach ($blog_posts as $blog_post) :
?>
<a class="blog-archive-sidebar-feed" href="<?=get_permalink($blog_post['ID'])?>">
<span class="blog-archive-title"><?=$blog_post['post_title']?></span>
<p class="blog-archive-date"><?=date('F d, Y' , strtotime($blog_post['post_date']))?></p>
</a>
<?php endforeach; endif; ?>
无论如何,什么都不会发生。
有什么建议吗?
好,
首先, wpb_set_post_views()
函数不返回任何内容,因为其中没有return
语句,因此return wpb_set_post_views($postID);
是完全正常的return wpb_set_post_views($postID);
不返回任何东西。
其次,wpb_set_post_views()用于更新存储指定帖子视图nb的帖子元变量,而不是返回查看次数最多的帖子的列表。
您需要创建一个这样的函数(假设get_most_viewed_posts($count);
用于为例),然后调用它的内部get_blog_posts()
的函数INSEAD wpb_set_post_views()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.