Wordpress 文章添加副标题

后台编辑区添加自定义副标题字段

 

/**
 * Add Subtitle in all post
 */
function article_subtitle( $post ) {
    if ( ! in_array( $post->post_type, [ 'post', 'page', 'knowledgebase' ], true ) ) {
        return; 
    }
    // The subtitle field.
    $_stitle = sanitize_text_field( get_post_meta( $post->ID, '_article_subtitle', true ) );
    echo '<label for="article_subtitle">' . __( 'Sub Title ' ) . '</label>';
    echo '<input type="text" name="article_subtitle" id="article_subtitle" value="' .  $_stitle . '" size="100" spellcheck="true" autocomplete="off" />';
}

function article_save_subtitle( $post_ID, $post, $update ) {
    if ( ! in_array( $post->post_type, [ 'post', 'page', 'knowledgebase' ], true ) ) {
        return;
    }
    // Prevent to execute twice.
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    // Get the subtitle value from $_POST.
    $_stitle = filter_input( INPUT_POST, 'article_subtitle', FILTER_SANITIZE_STRING );
    if ( $update ) {
        // Update the post meta.
        update_post_meta( $post_ID, '_article_subtitle', sanitize_text_field( $_stitle ) );
    } else if ( ! empty ( $_stitle ) ) {
        // Add unique post meta.
        add_post_meta( $post_ID, '_article_subtitle', sanitize_text_field( $_stitle ), true );
    }
}
add_action( 'edit_form_after_title', 'article_subtitle', 20 );
add_action( 'wp_insert_post', 'article_save_subtitle', 20, 3 );

 

保存或预览文章,会将副标题字段插入到数据库中的 wp_postmeta 表中,如下图所示:

 

需要在文章模板页面中添加副标题显示的样式等,代码如下:

 

最终效果如下图所示:

 

转载于:https://www.cnblogs.com/ryanzheng/p/10220078.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值