我正在使用PHP动态创建自定义帖子,我需要作者不是登录用户。我找到了这个https://stackoverflow.com/questions/5759359/wordpress-manually-set-the-author-of-a-post-in-php 但我想知道在帖子插入后是否有办法做到这一点。我想我可以做一个db查询。。。
如何设置我刚刚用PHP创建的帖子的作者?
如果您知道作者的ID,可以使用wp\\u insert\\u 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()
.为了简单起见,以及此问题与上提出的另一个问题之间的相关性Stack Overflow (wordpress - manually set the author of a post in php -- 如WPSE上OP所链接)。
WordPress似乎为post_author
使用插入或更新帖子时wp_insert_post()
和wp_update_post()
.
The way around it is to use the filter hook 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 );
Example Usage of filter hook 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
.Note: 您需要确保禁用对的支持author
在您的自定义帖子类型中,可能需要谨慎使用此帖子类型范围内与作者相关的任何函数。
如果这是自定义帖子类型,并且您不希望将作者分配给帖子,则可以从中删除“author”supports( array )
在register\\u post\\u type中。http://codex.wordpress.org/Function_Reference/register_post_type
如果您的帖子类型仍然需要作者支持,那么在帖子中这样做会更有意义。php/发布新内容。php,通过过滤作者元数据库。
解决方案是使用wp\\u dropdown\\u users将none或null用户添加到下拉列表中\'show_option_none\'
WordPress将使用<option value="-1">
对于空用户,但它将在数据库中显示为0。
*注意:此示例还将author div移到publish按钮的正上方。
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\'
) );
}
我肯定你注意到了对$selected的所有额外条件检查。这可能有点过头了,但消除了编辑无法将作者从以前发布的帖子中更改为无作者的问题。