
有时候网站会收到一些投稿文章,或者也会转载别人的文章,新创建一个用户又有些麻烦,但在作者名称那里显示自己的名字,总不是那么和谐。今天倡萌推荐 @西秦公子 的一个小插件,支持在后台自定义当前文章的作者名称,效果如下图所示:

不过网站玩的久了,插件装的太多,还是喜欢 直接用代码和协在网站内部,话不多说,直接上代码,
把下面代码复制在 functions.php 即可。
//自定义作者名称
add_action('post_submitbox_misc_actions', 'cus_author_createCustomField');
add_action('save_post', 'cus_author_saveCustomField');
/** 创建一个checkBox */
function cus_author_createCustomField() {
$post_id = get_the_ID();
if (get_post_type($post_id) != 'post') {
return;
}
/**
* 提取现有的值
* @var boolean
*/
$value = get_post_meta($post_id, '_custom_author_name', true);
/**
* 添加 nonce 安全处理
*/
wp_nonce_field('custom_author_nonce' , 'custom_author_nonce');
?>
<div class="misc-pub-section misc-pub-section-last dashicons-before dashicons-admin-users">
<label><b>作者:</b><input type="text" value="<?php echo $value ?>" name="_custom_author_name" /></label>
</div>
<?php
}
/**
* 保存配置信息
* @param int $post_id 文章的ID
*/
function cus_author_saveCustomField($post_id) {
/**
* 自动保存不处理
*/
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
/**
* nonce 信息不正确不处理
*/
if (
!isset($_POST['custom_author_nonce']) ||
!wp_verify_nonce($_POST['custom_author_nonce'], 'custom_author_nonce')
) {
return;
}
/**
* 用户无权编辑文章不处理
*/
if (!current_user_can('edit_post', $post_id)) {
return;
}
/**
* 存在此项目就更新
*/
if (isset($_POST['_custom_author_name'])) {
update_post_meta($post_id, '_custom_author_name', sanitize_text_field($_POST['_custom_author_name']));
} else {
/**
* 不存在就删除
*/
delete_post_meta($post_id, '_custom_author_name');
}
}
add_filter('the_author','cus_author_the_author');
function cus_author_the_author($author){
$custom_author = get_post_meta(get_the_ID(), '_custom_author_name');
if ($custom_author) {
return $custom_author[0];
} else {
return $author;
}
}
核心思路就是通过钩子 the_author 来修改了文章作者的显示名称。限定了文章类型为 post(文章),见32行。
至此关于在WordPress发布文章时自定义文章作者名称就结束了,更多关于WordPress技巧与插件请查看下面的相关链接













