首先是什么:Wordpress 中的 wp_head 或 the_content 挂钩?

What goes first: wp_head or the_content hooks in Wordpress?

我正在学习插件。我只是想在打开 post 后增加浏览量。如果我对这些行进行了评论:

//    if(is_single()){
//        $views++;
//    }

我没有看到任何增加。当他们没有评论时,打开 post 后我立即看到增加。

add_filter('the_content', 'get_views_count');
function get_views_count($content){

    if(is_page()){
        return $content;
    }

    global $post;

    $views = $post->my_count;

//    if(is_single()){
//        $views++;
//    }

    return $content . '<p>Views: ' . $views . '</p>';
}


add_action('wp_head', 'increase_counts');
function increase_counts(){

    if(!is_single()){
        return;
    }

    global $wpdb, $post;

    $views = $post->my_count + 1;

    $query = "UPDATE $wpdb->posts SET my_count=$views WHERE ID=$post->ID";
    $wpdb->query($query);
}

我认为 wp_head 挂钩应该比 the_content 先挂。逻辑对我来说更容易:wp_head 从 db 中获取计数,增加它并将其写入 db。然后the_content就输出结果。如何知道哪个钩子先挂?在此示例中,我如何更改他们的优先级?

Rachel Vasquez 拥有一篇关于 WordPress 钩子的最完整的文章,您可以在周围找到按触发顺序排序的钩子,因此无论何时您需要知道首先触发哪个钩子,您都应该完全检查一下:The WordPress Hooks Firing Sequence!

现在,为了回答您的问题,wp_head 首先触发。您的代码的问题在于:

global $wpdb, $post;

$views = $post->my_count + 1; // HERE!

您正在为 $views 分配当前值 $post->my_count + 1(例如 5 + 1 = 6),但 $post->my_count 仍保留其旧值(例如 5 ).

如果要显示更新的浏览量,需要先增加$post->my_count

global $wpdb, $post;

$post->my_count = $post->my_count + 1; // Increment the views count in the $post object first
$views = $post->my_count; // Assign the newly updated views count to the $views variable

这样,当您的 get_views_count() 函数被调用时,$post 对象已经更新为正确的观看次数。

旁白:

您似乎更改了 wp_posts table 以包含您的 my_count 列。请不要那样做。

尽可能避免更改核心内容(数据库 tables and/or WordPress 核心文件和文件夹),以确保您开发的任何插件或主题与未来 WordPress 版本的最大兼容性。您需要通过 update_post_meta() 函数将您的视图数据存储在 wp_postmeta table 中。