我正在使用PHP动态创建自定义帖子,我需要作者成为登录用户以外的其他人。我找到了这个 https://stackoverflow.com/questions/5759359/wordpress-manaly-set-set-the-author-of-a-post-in-php 但是我想知道是否有办法在插入帖子之后。我想我可以做一个DB查询...

有帮助吗?

解决方案

如果您知道作者的ID,则可以使用wp_insert_post指定ID和作者ID。

$id = $post->ID; // change this to whathever
$user_id = '4'; // change this too

$the_post = array();
$the_post['ID'] = $id;
$the_post['post_author'] = $user_id;

wp_insert_post( $the_post );

诀窍是指定ID以更新帖子。看 wp_insert_post().

其他提示

为了简单性和相关性,这个问题与提出的另一个问题 堆栈溢出 (WordPress-手动设置PHP中帖子的作者 - 由OP在WPSE上的OP链接。)。

WordPress似乎迫使 post_author 在使用或更新帖子的同时 wp_insert_post()wp_update_post().

它的解决方法是使用过滤器钩 wp_insert_post_data.

/**
 * Filter slashed post data just before it is inserted into the database.
 *
 * @since 2.7.0
 *
 * @param array $data    An array of slashed post data.
 * @param array $postarr An array of sanitized, but otherwise unmodified post data.
 */
$data = apply_filters( 'wp_insert_post_data', $data, $postarr );

示例使用过滤器钩 wp_insert_post_data:

function remove_author_id( $data, $postarr ) {

    if ( $data['post_type'] != 'YOUR-POST-TYPE-HERE' ) {
        return $data;
    }

    $data['post_author'] = 0;

    return $data;

}

add_filter( 'wp_insert_post_data', 'remove_author_id', '99', 2 );

这对于使用 PHP.

笔记: 您将要确保禁用支持 author 在您的自定义帖子类型中,可能会使用此帖子类型范围内的任何作者相关功能谨慎。

如果这是自定义帖子类型,并且您不希望分配给帖子的作者,则可以从中删除“作者” supports( array ) 在register_post_type中。 http://codex.wordpress.org/function_reference/register_post_type

如果您仍然需要作者支持您的帖子类型,那么通过过滤作者metabox来在post.php / post-new.php中进行此操作将变得更有意义。

解决方案是使用wp_dropdown_users添加无或null用户到下拉 'show_option_none' WordPress将使用 <option value="-1"> 对于您的空用户,但它将显示为DB中的0。

*注意:此示例还将作者div移动到发布按钮上方。

add_action( 'post_submitbox_misc_actions', 'move_author_meta' );

function move_author_meta() {
    global $post_ID;
    $post = get_post( $post_ID );
    echo '<div id="author" class="misc-pub-section" style="border-top-style:solid; border-top-width:1px; border-top-color:#EEEEEE; border-bottom-width:0px;">Author: ';
    better_author_meta_box( $post );  //This function is being called in replace author_meta_box()

    echo '</div>';

}

function better_author_meta_box($post) { ?>

   <label class="screen-reader-text" for="post_author_override"><?php _e('Author'); ?></label>
  <?php

    if ( 'auto-draft' == $post->post_status ) : $selected = false; elseif (  $post->post_author == 0 || ( ! $post->post_author) ) : $selected = -1; else : $selected = $post->post_author; endif;
    wp_dropdown_users( array(
            'who' => 'authors',
            'name' => 'post_author_override',
            'selected' => $selected ? $selected : (int) -1,
            'include_selected' => true,
            'show_option_none' => 'NONE',
            'orderby'          => 'display_name',
            'show'             => 'display_name',
            'order'            => 'ASC'
      ) );
  }

我确定您会注意到所选$的所有额外条件检查。它可能过于杀伤,但消除了编辑无法将作者更改为以前发表的帖子的任何问题。

许可以下: CC-BY-SA归因
scroll top