广告
返回顶部
首页 > 资讯 > CMS >教你如何在WordPress发布文章时自定义文章作者名称
  • 603
分享到

教你如何在WordPress发布文章时自定义文章作者名称

2024-04-02 19:04:59 603人浏览 八月长安
摘要

有时候网站会收到一些投稿文章,或者也会转载别人的文章,新创建一个用户又有些麻烦,但在作者名称那里显示自己的名字,总不是那么和谐。今天倡萌推荐 @西秦公子 的一个小

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

直接在后台插件安装界面搜索“自定义作者名称”即可在线安装,或者到官方下载:https://litepress.cn/plugins/custom-author/

如果转载或投稿文章比较多,倡萌建议单独创建一个专门用于发布这类文章的用户,然后发布的文章的时候,自定义一下作者名称即可。

下面来看看这个小插件的代码:


<?PHP




add_action('post_submitbox_misc_actions', 'cus_author_createCustomField');
add_action('save_post', 'cus_author_saveCustomField');

function cus_author_createCustomField() {
	$post_id = get_the_ID();
	if (get_post_type($post_id) != 'post') {
		return;
	}
	
	$value = get_post_meta($post_id, '_custom_author_name', true);
	
	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   
}

function cus_author_saveCustomField($post_id) {
	
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
		return;
	}
	
	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技巧与插件请查看下面的相关链接

--结束END--

本文标题: 教你如何在WordPress发布文章时自定义文章作者名称

本文链接: https://www.lsjlt.com/news/136257.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作