Products
GG网络技术分享 2025-03-18 16:12 12
So i have this function for my Wordpress site which basically just counts every click and shows the most popular ones in a loop.
My problem is that the meta fields doesn\'t reset or decrease after time. So it will show old posts instead of new ones. I don\'t have that much knowlege in PHP so if anyone can help me, that will be greatly appreciated!This is my current PHP function:
function shapeSpace_popular_posts($post_id) {$count_key = \'popular_posts\';
$count = get_post_meta($post_id, $count_key, true);
if ($count == \'\') {
$count = 0;
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, \'0\');
} else {
$count++;
update_post_meta($post_id, $count_key, $count);
}
}
add_action(\'wp_ajax_track_clicks\', \'track_clicks\');
add_action(\'wp_ajax_nopriv_track_clicks\', \'track_clicks\');
function track_clicks(){
$post_id = $_POST[\'post_id\'];
shapeSpace_popular_posts($post_id);
echo \'Success\';
wp_die();
}
图片转代码服务由CSDN问答提供
感谢您的意见,我们尽快改进~
功能建议所以我的Wordpress网站有这个功能,它基本上只计算每次点击并显示循环中最受欢迎的 。
我的问题是元字段不会在一段时间后重置或减少。 因此它将显示旧帖子而不是新帖子。 我在PHP中没有那么多知识,所以如果有人可以帮助我,那将非常感谢!</ p>
这是我目前的PHP函数:</ p>
< pre> function shapeSpace_popular_posts($ post_id){
$ count_key =\'popular_posts\';
$ count = get_post_meta($ post_id,$ count_key,true);
if($ count ==\'\'){\\ n $ count = 0;
delete_post_meta($ post_id,$ count_key);
add_post_meta($ post_id,$ count_key,\'0\');
} else {
$ count ++;
update_post_meta($ post_id,$ count_key,$ count);
}
}
add_action(\'wp_ajax_track_clicks\',\'track_clicks\');
add_action(\'wp_ajax_nopriv_track_clicks\',\'track_clicks\');
function track_clicks(){
$ post_id = $ _POST [\'post_id\'];
shapeSpace_popular_posts($ post_id);
echo\'Eccess\';
wp_die();
}
</ code> </ pre>
</ div>
Use wp_schedule_event() function to run a function that sets all post meta to 0:
https://codex.wordpress.org/Function_Reference/wp_schedule_event
And add a custom recurrence interval :
function add_cron_recurrence_interval( $schedules ) {$schedules[\'every_three_minutes\'] = array(
\'interval\' => 180,
\'display\' => __( \'Every 3 Minutes\', \'textdomain\' )
);
return $schedules;
}
add_filter( \'cron_schedules\', \'add_cron_recurrence_interval\' );
To delete all post meta, use
<?php delete_post_meta_by_key( \'popular_posts\' ); ?>
https://codex.wordpress.org/Function_Reference/delete_post_meta
Also, i recommend you sanitize
$_POST[\'post_id\']
with
intval($_POST[\'post_id\'])
https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data
Demand feedback