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

 

/**
 * 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" >;
}

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

Wordpress 文章添加副标题

 

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

Wordpress 文章添加副标题

 

最终效果如下图所示:

Wordpress 文章添加副标题

 

相关文章:

  • 2022-12-23
  • 2021-10-19
  • 2021-08-22
  • 2021-10-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-26
猜你喜欢
  • 2018-07-02
  • 2021-07-03
  • 2021-10-21
  • 2022-01-08
  • 2021-06-14
  • 2021-12-27
相关资源
相似解决方案