我正在一个网站上工作,试图在其上获得热门帖子部分。我尝试过插件,但它们需要 wp_head() ,这会破坏我在网站上的 jCarousel 。我在functions.php中使用以下代码实现了getPostViews的代码:
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}
function setPostViews($postID) {
$count_key = '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);
}
}
但是,当我在循环中插入以下内容来显示它时,我的网站崩溃了,告诉我需要再次安装 WordPress。当我完成安装时,我得到了数据库错误列表。但是,如果我在当天晚些时候返回并删除代码,则该网站会再次运行。
<? query_posts('meta_key=post_views_count&orderby=meta_value_num&order=DESC'); ?>
如何使用此功能让热门帖子发挥作用?或者我应该寻找其他方法来让热门帖子发挥作用?感谢您的帮助。
最佳答案
将其放入functions.php中:
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}
function setPostViews($postID) {
$count_key = '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);
}
}
接下来,将其放置在您想要返回带 View 的帖子列表的位置:
<ul>
<?php
global $post;
$args = array( 'numberposts' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<li><?php setPostViews(get_the_ID()); echo getPostViews(get_the_ID());; ?></li>
<?php endforeach; ?>
</ul>
关于php - WordPress 不使用插件的热门帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9472602/