我正在尝试在wordpress帖子标题中使用以下简码。简码如下所示:
//Use [year] in your posts.
function year_shortcode() {
$year = date('Y');
return $year;
}
add_shortcode('year', 'year_shortcode');
有什么建议如何在帖子标题中执行这个简码吗?
感谢您的回复!
您绝对可以在标题中使用短代码。你只需要在调用标题时使用WordPress钩子系统来运行短代码。因此,如果您想拥有一个吐出当前年份的短代码[year]
,您将创建短代码:
add_shortcode( 'year', 'sc_year' );
function sc_year(){
return date( 'Y' );
}
然后,挂入过滤器,the_title()
运行您的短代码:
add_filter( 'the_title', 'my_shortcode_title' );
function my_shortcode_title( $title ){
return do_shortcode( $title );
}
这负责帖子/页面标题,但您还需要为single_post_title
钩子运行它,该钩子用于您网站上的标题标签上的wp_head
。这样,浏览器也会显示正确的标题:
add_filter( 'single_post_title', 'my_shortcode_title' );
注意:这里不需要单独的函数,因为它运行的是完全相同的代码。因此,您的总代码将如下所示:
add_shortcode( 'year', 'sc_year' );
function sc_year(){
return date( 'Y' );
}
add_filter( 'single_post_title', 'my_shortcode_title' );
add_filter( 'the_title', 'my_shortcode_title' );
function my_shortcode_title( $title ){
return do_shortcode( $title );
}
我认为您不能在带有短代码的帖子标题中应用(保存在管理员帖子编辑屏幕中(简码。post_title是消毒以避免标签或短代码,帖子标题被许多短代码可以破坏的功能使用。
要对post_title进行修改,可以使用过滤器the_title
add_filter('the _title', 'yourfunction');
function yourfunction($title){
global $post;
// if you set a custom field on the post where you want to display the year
if(get_post_meta($post->ID, 'display_year', true) == 1){
$title = $title. ' '. date('Y');
}
return $title;
}
希望对你有帮助
请在"function.php"中添加此代码。试试这个。
<?php
function TitleFunction($title)
{
global $post;
$title = $title. ' ' .get_the_date('Y');
return $title;
}
add_filter( 'the_title', 'TitleFunction', 10, 2 );
?>