php - WordPress 不使用插件的热门帖子

标签 php wordpress

我正在一个网站上工作,试图在其上获得热门帖子部分。我尝试过插件,但它们需要 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/

相关文章:

php - 如何内爆多个值?

php - SQL 更新查询问题

javascript - jquery 标签不是由 $.post 生成的

wordpress - 需要有关 WordPress 移动重定向代码的帮助

mysql - WampServer - mysqld.exe 无法启动,因为缺少 MSVCR120.dll

css - (Wordpress CSS) 如何在 404 页面上隐藏面包屑和多余空间?

php - WooCommerce:在结帐页面中默认设置国家/地区

php - wordpress 数据库中的事务

php - 调用服务器中存储的Python文件

php - 有效电子邮件地址的 Swift_RfcComplianceException,适用于 Windows 而不是 Ubuntu