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 表中,如下图所示:

 

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

 

最终效果如下图所示:

 

posted @ 2019-01-04 15:25  Ryan_zheng  阅读(1979)  评论(0编辑  收藏  举报