WordPress修改标题前的"私密"和"密码保护"
如果你将文章的公开度设置为"私密"和"密码保护",这些文章就会在标题的前面自动添加"私密:"和"密码保护:"或"Protected: "。
去掉标题前的"私密:"和"密码保护:"
将如下代码添加到主题的 functions.php 中
add_filter( 'private_title_format', 'diy_private_title_format' ); //私密 add_filter( 'protected_title_format', 'diy_private_title_format' ); //密码保护 function diy_private_title_format( $format ) { return '%s'; //这个不能省略 }
注:return '%s' 表示直接返回标题,也可以根据自己的需要,分别为 私密 和 密码保护 撰写不同的函数,定义返回的标题格式即可。
替换标题前的“私密:”和“密码保护:”
将如下代码添加到主题的 functions.php 中
//私密 add_filter( 'private_title_format', 'diy_private_title_format' ); function diy_private_title_format( $format ) { return '[私密] %s'; } //密码保护 add_filter( 'protected_title_format', 'diy_protected_title_format' ); function diy_protected_title_format( $format ) { return '[密码保护] %s'; }
拓展一下
我们针对不同的分类,做不同的提示文字,这里需要处理两个参数,上述代码就要稍作调整,以"密码保护"文章为例
add_filter( 'protected_title_format', 'diy_protected_title_format', 10, 2 ); function diy_protected_title_format( $format, $post ) { $post = get_post( $post ); $title = isset( $post->post_title ) ? $post->post_title : ''; //读取文章标题 $id = isset( $post->ID ) ? $post->ID : 0; //读取文章ID $category = get_the_category( $id ); $category_id = $category[0]->cat_ID; //分类ID $category_name = $category[0]->cat_name; //分类名称 $txt1 = '[私密]'; $txt2 = ''; if( $category_id==3 || $category_id==1943 ){ $txt1 = '[付费文档]'; } return $txt1 .' %s'. $txt2; }
这里的 $post 有如下数据可操作:
Object ( [__PHP_Incomplete_Class_Name] => WP_Post [ID] => 1557 [post_author] => 1 [post_date] => 2014-10-10 16:21:13 [post_date_gmt] => 2014-10-10 08:21:13 [post_content] => 文章内容 [post_title] => 文章标题 [post_excerpt] => 文章摘要 [post_status] => private [comment_status] => open [ping_status] => closed [post_password] => [post_name] => 1557 [to_ping] => [pinged] => [post_modified] => 2020-04-10 14:40:18 [post_modified_gmt] => 2020-04-10 06:40:18 [post_content_filtered] => [post_parent] => 0 [guid] => https://yangjunwei.com/?p=1557 [menu_order] => 0 [post_type] => post [post_mime_type] => [comment_count] => 0 [filter] => raw [platform] => 0 )
这里的 $category 有如下数据可操作:
Array ( [0] => __PHP_Incomplete_Class Object ( [__PHP_Incomplete_Class_Name] => WP_Term [term_id] => 3 [name] => 微信开发 [slug] => weixin [term_group] => 0 [term_taxonomy_id] => 3 [taxonomy] => category [description] => [parent] => 0 [count] => 302 [filter] => raw [cat_ID] => 3 [category_count] => 302 [category_description] => [cat_name] => 微信开发 [category_nicename] => weixin [category_parent] => 0 ) )