我想显示的第一个字的帖子标题只在首页的我的网站。
My Problem:我有下面的编码,但它不适用于首页的帖子标题,但它会影响网站菜单标题和博客主标题,而我只想针对我的网站首页上的帖子标题。
add_filter( 'the_title', 'wpse_75691_trim_words' );
function wpse_75691_trim_words( $title )
{
// Limit the title to exactly one word only on the frontpage.
if (is_front_page()) {
return wp_trim_words( $title, 1, '' );
}
// Otherwise return the full title.
return $title;
}我想做什么
我在frontpage上的帖子标题在inspect元素中如下所示:

提示:--我认为,如果上面的代码只针对h3 title,那么它只会影响文章标题,而不会影响我的首页上的其他标题标记。所以,任何人都可以修改代码,只将函数应用到帖子标题中,而且它应该可以工作。
发布于 2021-05-01 22:40:32
如果只为“头版”中的"post“标题裁剪标题,那么您可以这样做:
add_filter( 'the_title', 'your_them_custom_title', 10, 2 );
function your_them_custom_title( $title, $post_id )
{
if( is_front_page() && 'post' === get_post_type( $post_id ) && !is_admin() ) {
return wp_trim_words( $title, 1, '' );
}
return $title;
}此外,如果您想保持导航菜单标题不变,那么您可以这样做:
add_filter( 'nav_menu_item_title', 'your_them_nav_title', 10, 4 );
function your_them_nav_title( $title, $item, $args, $depth )
{
# Removing your custom title for the nav menu
remove_filter( 'the_title', 'your_them_custom_title', 10, 2 );
$title = get_the_title( $item->object_id );
# Adding your custom title back
add_filter( 'the_title', 'your_them_custom_title', 10, 2 );
return $title;
}更新:
如果您不确定您所指的是哪个页面,那么您可以运行这个条件检查,以查看您需要检查哪个页面才能运行wp_trim_words。
“复制/过去”以下代码到functions.php以确定您所指的正确页面:
if ( is_front_page() && is_home() ) {
echo "default index page which is also the front page";
} elseif ( is_front_page()){
echo "custom front page";
} elseif ( is_home()){
echo "default index page";
} else {
echo "neither front nor blog index";
}https://stackoverflow.com/questions/67351019
复制相似问题