php 查询用户,计算他们在帖子上出现的次数,并使用该计数更新他们的配置文件

6jygbczu  于 2023-02-07  发布在  PHP
关注(0)|答案(1)|浏览(116)

我已经把下面的代码段放在一起来计算指定角色的搜索用户在我的几篇文章的ACF用户字段中出现的次数,如果我实际上指定某人的user_id(例如:$用户标识符= 32;),但当我想为该角色中的所有用户运行它时($user_id= $user-〉ID;),它不会更新每个用户字段的计数。任何想法将不胜感激。

add_action( 'run_snippet_hourly', function () {
$user_query = array(
    'role'    => 'um_pds-project-manager',
    'orderby' => 'display_name',
    'order'   => 'ASC'
);
$users = get_users( $user_query );
if ( !empty( $users ) ) { 
foreach ( $users as $user ) 
$user_id= $user->ID;
$args = array(
  'posts_per_page' => -1,
  'post_type' => 'project',
  'meta_query' => array(
            'relation' => 'AND',
    array(
        'key'   => 'status',
        'value' => '1'
    ),
          array(
        'key' => 'pds_project_manager',
        'value' => $user_id,
        'compare' => 'LIKE'
    )
  )
);

$posts_pm = get_posts($args);
$pds_project_manager_count = count($posts_pm);
// Update user profile field user_project_count with the count 
update_user_meta( $user_id, 'user_project_count', $pds_project_manager_count);
}
    } );//end Cron
x33g5p2x

x33g5p2x1#

我可以让这个工作,这是我修改的片段,我修改它,试图澄清什么人需要改变为他们工作.如果你在你的帖子中使用ACF用户字段,这可以得到一个角色的用户,然后计数有多少次,每个用户出现在用户字段中的所有职位,然后更新一个字段,他们的个人资料与计数.

add_action( 'run_snippet_hourly', function () {// I am triggering this with a cron job

// Get the user ID's for all users in a specific role.
$user_ids = get_users( array('role' => 'YOUR ROLE HERE', 'fields' => 'ID' ) );

// Loop through each user and get the count of posts that have the user in the ACF user field.
foreach ( $user_ids as $user_id ) {

    // Get the ACF user field for all posts.
    $args = array(
        'post_type'   => 'YOUR POST TYPE HERE',
        'posts_per_page' => -1,
        'meta_query'  => array(
            'relation' => 'AND',
            array(
                'key'     => 'YOUR FIELD KEY HERE',
                'value'   => '"' . $user_id . '"',
                'compare' => 'LIKE'
            )
        )
    );

    $query = new WP_Query( $args );
    $count = $query->post_count;

    // Update the user meta field user_post_count with the count for each user. Use ACF to add a text field to all users profiles.
    update_user_meta( $user_id, 'user_post_count', $count );

}
    
} );//end Cron

相关问题