使用wp_insert_post为每个用户自动创建帖子

问题描述:

我正在为每个至少拥有作者凭证的用户自动创建自定义帖子类型的帖子(jt_cpt_team)。使用wp_insert_post为每个用户自动创建帖子

首先,它需要为管理员创建的每个新用户执行此操作。如果有一种简单的方法为每个现有作者(〜30)生成一篇文章,那么这很好,但如果需要的话,我不介意手动做这些文章。

我猜这或多或少是我需要的—努力让它工作,虽然…

class team_functions { 

    public function __construct() { 

    add_action('user_register', array($this, 'create_authors_page')); 

    } 

    public function create_authors_page($user_id) { 

    $the_user  = get_userdata($user_id); 
    $new_user_name = $the_user->user_login; 
    $my_post  = array(); 
    $my_post['post_title'] = $new_user_name; 
    $my_post['post_type'] = 'jt_cpt_team'; 
    $my_post['post_content'] = ''; 
    $my_post['post_status'] = 'publish'; 
    $my_post['post_theme'] = 'user-profile'; 

    wp_insert_post($my_post); 

    } 

} 

而且,如果有一种方法来添加作者的电子邮件作为custom_field这将是真棒。

预先感谢您的帮助:)

像这样的东西应该工作:

public function create_authors_page($user_id) { 

    $the_user  = get_userdata($user_id); 
    $new_user_name = $the_user->user_login; 
    $PostSlug  = $user_id; 
    $PostGuid  = home_url() . "/" . $PostSlug; 

    $my_post = array('post_title' => $new_user_name, 
         'post_type' => 'jt_cpt_team', 
         'post_content' => '', 
         'post_status' => 'publish', 
         'post_theme' => 'user-profile', 
         'guid'   => $PostGuid); 

    $NewPostID = wp_insert_post($my_post); // Second parameter defaults to FALSE to return 0 instead of wp_error. 

    // To answer your comment, adding these lines of code before the return should do it (Have not tested it though): 
    $Key = $new_user_name; // Name of the user is the custom field KEY 
    $Value = $user_id; // User ID is the custom field VALUE 
    update_post_meta($NewPostID, $Key, $Value); 

    return $NewPostID; 
    } 
+0

辉煌 - 就像一个魅力! :) 谢谢。 – richerimage

+0

另一件事 - 我想用作者ID填充一个'custom_field' - 这可能在这个函数中吗?谢谢。 – richerimage

+0

@richerimage更新了答案。 –