php - 根据用户角色将帖子状态更改为待处理

标签 php wordpress

我有成员(member)网站,用户必须付费才能订阅。当用户订阅时,他的角色变为“成员”,现在可以发布到名为“用户配置文件”的自定义帖子类型

我想做的是将此帖子类型中所有已发布帖子的状态更改为待处理,例如,如果用户角色更改为“已过期”

这个我试过了,好像没有什么效果

 function auto_expire_posts(){
    global $wpdb, $wp_roles;
      //get all post ids of published posts.
      $post_ids = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_status = 'publish' ");

foreach($post_ids as $id){
$postid =  $id->ID;
if ($_GET['role'] == "expired" ) 
    {
        $profile_post = array();
        $profile_post['ID'] = $postid;
        $profile_post['post_status'] = 'pending';
        // Update the post into the database
         wp_update_post( $profile_post );

       }
}
}
add_action('set_user_role', 'auto_expire_posts');

最佳答案

从根本上说,您的函数应该使所有帖子过期。从功能上讲,它是有效的,所以当你说“没有效果”时,这是令人惊讶的。

您的函数应该按照下面的内容进行修改,以提高效率(您不需要遍历帖子)并确保您只更新相关帖子,并确保它不会发出通知。

修改后的代码:

// This action passes 3 parameters, so let's accept them - $user_id, $new_role, $old_roles
function auto_expire_posts( $user_id, $new_role, $old_roles ) {
    // If the user didn't USED to be a member, then no need to do anything
    if ( ! in_array( 'member', $old_roles ) ) {
        return;
    }

    global $wpdb;

    // Set the array of values to update
    $update = array(
        'post_status' => 'expired'
    );

    // Set the array that defines the "WHERE" clause
    // WHERE is ONLY published posts that are authored by the specified user
    $where = array(
        'post_status' => 'publish',
        'post_author' => $user_id
    );

    // $updated will contain the number of posts changed
    $updated = $wpdb->update( $wpdb->posts, $update, $where );
}

// Ensure the add_action passes the 3 parameters through (10 is the priority, 3 is the number of parameters)
add_action( 'set_user_role', 'auto_expire_posts', 10, 3 );

这已经过测试,我已经证明它可以工作。 但是您可能会发现它没有按照您的意愿进行操作的原因有很多:

  1. 这是利用核心 WordPress 的 do_action('set_user_role')。此 Hook 可能不会被调用,具体取决于您更改用户角色的方式。如果您通过仪表板转到用户的个人资料、更改角色并单击“保存用户”,则此 Hook 确实会被调用如果它不起作用,请务必准确解释您是如何改变角色的。
  2. 如果您使用的角色不是“成员”,这将不起作用。如有必要,请更改上面的代码(我使用“成员”的地方)以匹配您实际使用的任何角色。 如果不起作用,请务必准确解释您正在使用的角色名称。
  3. “过期”不是我熟悉的帖子状态。我相信这会禁止显示帖子,但它可能不会。 如果它不起作用,请务必查看数据库以查看帖子状态是否发生了变化
  4. 如果您没有在(多个)适当位置安装此函数/ Hook ,则它可能不会被调用。

关于php - 根据用户角色将帖子状态更改为待处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40591580/

相关文章:

php - 如果未为发布设置缩略图,则 SQL 查询不会显示结果

mysql - 合并 2 个 SQL 查询。

html - 尝试在 Wordpress Widget 中使用 HTML 以特定方式对齐两列

php - 如何在 PHP 正则表达式中获得全部匹配的 3 个条件?

php - 更改域名导致我的图像无法在 WordPress 中加载

PHP 邮件链接

html - 在 WordPress Astra 主题上添加指向 HTML 按钮的链接

php - 无法在 php 中使用 unserialize() 函数并且无法显示数据

php - 从同一个表中选择不同的结果

html - 如何获取 html/css 表单以发布到 Gravity Forms?