【问题标题】:Change posts status to pending based on user role根据用户角色将帖子状态更改为待处理
【发布时间】:2016-11-14 14:53:30
【问题描述】:

我有会员网站,用户必须付费订阅。当用户订阅时,他的角色成为“成员”,现在可以发布到名为“user-profile”的自定义帖子类型

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

我试过了,但似乎没有任何效果

 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');

【问题讨论】:

  • 您还需要在查询中选择post_status 列。
  • wordpress 会员插件
  • 我正在使用重力表单并手动管理订阅,如果我手动更改角色以获得结果,我想要
  • SELECT ID, post_status FROM $wpdb->posts
  • @Fred-ii- 所以它应该看起来像这样:$post_ids = $wpdb->get_results( "SELECT ID, post_status FROM $wpdb->posts" );

标签: php wordpress


【解决方案1】:

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

您的函数应该修改如下,以提高效率(您不需要循环访问帖子)并确保您只更新相关帖子,并确保它不会发出通知。

修改后的代码:

// 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')。这个钩子可能不会被调用,这取决于你如何改变用户的角色。如果您通过仪表板转到用户的个人资料、更改角色并单击“保存用户”,则此挂钩会被调用如果不起作用,请务必准确说明您是如何改变角色的。
  2. 如果您使用的角色不是“成员”,这将不起作用。如有必要,更改上面的代码(我使用“成员”)以匹配您实际使用的任何角色。 如果不起作用,请务必准确说明您使用的角色名称。
  3. “过期”不是我熟悉的帖子状态。我相信这会抑制帖子的显示,但可能不会。 如果不起作用,请务必查看数据库以查看帖子状态是否正在更改
  4. 如果您没有在(多个)适当位置之一安装此函数/挂钩,则它可能不会被调用。

【讨论】:

  • 谢谢你的详细解释,不过我想用这个把post状态改成pending,expired是一个用户角色,所以如果用户角色改成expired应该会生效,我有许多其他不同的角色,成员,premuim 成员...等,所以需要在代码中定义“过期”角色
  • 我最终将它包裹在 if ( 'expired' == $new_role ) { } 中并完全删除了它 if ( ! in_array( 'member', $old_roles ) ) { } 谢谢你
猜你喜欢
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
  • 2016-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
相关资源
最近更新 更多