WordPress自定义文章作者名称

许都 850 6

WordPress自定义文章作者名称

代码

PHP
  1. /*
  2. * WordPress自定义文章作者名称
  3. */
  4. add_action('post_submitbox_misc_actions', 'cus_author_createCustomField');
  5. add_action('save_post', 'cus_author_saveCustomField');
  6. add_filter('the_author','cus_author_the_author');
  7. /** 创建一个checkBox */
  8. function cus_author_createCustomField() {
  9. $post_id = get_the_ID();
  10. if (get_post_type($post_id) != 'post') {
  11. return;
  12. }
  13. /*
  14. * 提取现有的值
  15. * @var boolean
  16. */
  17. $value = get_post_meta($post_id, '_custom_author_name', true);
  18. /*
  19. * 添加 nonce 安全处理
  20. */
  21. wp_nonce_field('custom_author_nonce' , 'custom_author_nonce');
  22. ?>
  23. <div class="misc-pub-section misc-pub-section-last dashicons-before dashicons-admin-users">
  24. <label><b>作者:</b><input type="text" value="<?php echo $value ?>" name="_custom_author_name" /></label>
  25. </div>
  26. <?php
  27. }
  28. //保存配置信息 $post_id 文章的ID
  29. function cus_author_saveCustomField($post_id) {
  30. //自动保存不处理
  31. if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
  32. return;
  33. }
  34. //信息不正确不处理
  35. if (
  36. !isset($_POST['custom_author_nonce']) ||
  37. !wp_verify_nonce($_POST['custom_author_nonce'], 'custom_author_nonce')
  38. ) {
  39. return;
  40. }
  41. //用户无权编辑文章不处理
  42. if (!current_user_can('edit_post', $post_id)) {
  43. return;
  44. }
  45. //存在此项目就更新
  46. if (isset($_POST['_custom_author_name'])) {
  47. update_post_meta($post_id, '_custom_author_name', sanitize_text_field($_POST['_custom_author_name']));
  48. } else {
  49. //不存在就删除
  50. delete_post_meta($post_id, '_custom_author_name');
  51. }
  52. }
  53. function cus_author_the_author($author){
  54. $custom_author = get_post_meta(get_the_ID(), '_custom_author_name');
  55. if ($custom_author) {
  56. return $custom_author[0];
  57. } else {
  58. return $author;
  59. }
  60. }
复制 文本 高亮
  • 核心思路就是通过钩子 the_author 来修改了文章作者的显示名称。
  • 限定了文章类型为 post(文章),见6行。可自由发挥。

插件下载

官方下载

发表评论 取消回复
表情 图片 链接 代码

  1. leisu
    leisu Lv 3

    你怎么都发些小白教程啊,拉低了博主的技术水平。天啦噜!

  2. leisu
    leisu Lv 3

    楼下这个明显是发外链的。直接删了,嗯

    • 许都
      许都 站长

      @leisu链接都没了

  3. 明月登楼
    明月登楼 Lv 1

    这个 Begin 主题自定义栏目里不是可以添加吗?

    • 许都
      许都 站长

      @明月登楼这个比较实在,就是每次发布文章必须添加作者。代码有待完善。现在没用知更鸟了。

  4. 2018年稳妥赚钱项目
    2018年稳妥赚钱项目 Lv 1

    不错顶一个

分享