dongpin1059 2018-05-12 13:04
浏览 90
已采纳

在Wordpress中重置post meta

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();
}
  • 写回答

1条回答 默认 最新

  • dqknycyt92288 2018-05-12 16:52
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题