Puo's 学习园地
http://puo.cn

WordPress 文章添加副标题 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 表中,如下图所示:

20250725124948792

 

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

20250725124948120

 

最终效果如下图所示:

20250725124948530

打赏
允许转载,请注明转载地址:Puo's 学习园地 » WordPress 文章添加副标题
分享到

评论 抢沙发

做一个好的个人学习园地

主要网建,域名、集装箱物流、生活方法论的学习及研究,整理等内容

网址导航222域名店

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册