Wordpress如何添加页面计数器



我使用一个自定义数字字段(由Jet Engine插件生成(来跟踪页面加载的次数。

在我的functions.php文件中,我使用以下代码:

$count = get_post_meta("706", 'counter', true );
if(!is_admin() && !current_user_can('administrator')){
$count++;
update_post_meta("706", 'counter', $count );
}

"counter"是字段名。

我正在使用if(!is_admin),所以它不会计算我的后端测试。

我的主要问题是计数器不一致,尽管在大多数情况下它以1的步长计数,但有时它会跳过并在单个页面加载中计数234

这是我的测试页面的链接:

https://oferziv.com/ofer/test/test3/

我在这里错过了什么?

就像我说的,我总是使用wp_head动作挂钩,它可以无缝工作!

function my_counter_function()
{
if (is_admin() || current_user_can('activate_plugins')) return;
$counter = get_post_meta("706", 'counter', true);
if (empty($counter)) {
$counter = 1;
update_post_meta("706", 'counter', $counter);
} else {
$counter++;
update_post_meta("706", 'counter', $counter);
}
}
add_action('wp_head', 'my_counter_function'); // This is the action hook i was talking about!

通常,您需要将所有内容都包装在一个合适的钩子中,如下所示:

// Runs on every page request after we have a valid user.
add_action('init', function () {
// Return early if we're in the backend...
if (is_admin()) {
return;
}
// ...or the current user has admin capabilities 
if (current_user_can('activate_plugins')) {
return;
}
// Otherwise, update counter
$count = get_post_meta("706", 'counter', true );
$count++;

update_post_meta("706", 'counter', $count );
});

关于如何使用挂钩,请参阅:

  • https://developer.wordpress.org/plugins/hooks/
  • https://codex.wordpress.org/Plugin_API/Action_Reference

有关检查用户权限的信息,请参阅:

  • https://developer.wordpress.org/reference/functions/current_user_can/
  • https://wordpress.org/support/article/roles-and-capabilities/#capabilities
  • https://dev.to/lucagrandicelli/why-isadmin-is-totally-unsafe-for-your-wordpress-development-1le1

最新更新