将 the_title 过滤器应用于帖子,但不适用于导航菜单 [英] Apply the_title filter to posts but not on nav menus

查看:19
本文介绍了将 the_title 过滤器应用于帖子,但不适用于导航菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对帖子类型的标题应用过滤器,但仅限于其单个页面.所以我做了这个功能:

I want to apply a filter to the title of a post type, but only on its single page. So I made this function:

function title_filter( $title, $post_id = null ) {
    if ( ! empty( wp_get_associated_nav_menu_items( $post_id ) ) && is_singular( 'review' ) ) {
        $title = sprintf( '%1$s %2$s', $title, __( 'Review', 'stackoverflow' ) );
    }

    return $title;
}
add_filter( 'the_title', 'title_filter', 10, 2 );

但问题是过滤器也应用于具有该类型帖子的导航菜单项.我尝试使用 wp_get_related_nav_menu_items() 但这似乎不起作用.还尝试使用 get_post_type() 检查帖子类型但由于菜单项在使用菜单编辑器上的帖子类型选项添加项目时会响应帖子类型,因此它们始终匹配并且无论如何都会应用过滤器.

But the problem is that the filter is also applied to the nav menu items that have a post of that type. I tried to exclude the filter from nav items using wp_get_associated_nav_menu_items() but that doesn't seem to work. Also tried checking the post type using get_post_type() but since the menu items respond to the post type when the item is added using the post type options on the menu editor, they always match and the filter is applied anyway.

这个问题 不适合我.

有什么想法吗?

推荐答案

您可以通过与 in_the_loop() 布尔函数:

You can check to make sure you're only filtering titles in the loop by comparing with the in_the_loop() boolean function:

function mithc_title_filter( $title, $post_id = null ) {
    if( in_the_loop() && is_singular( 'review' ) ){
        $title = sprintf( '%1$s %2$s', $title, __( 'Review', 'stackoverflow' ) );
    }
    return $title;
}
add_filter( 'the_title', 'mithc_title_filter', 10, 2 );

这篇关于将 the_title 过滤器应用于帖子,但不适用于导航菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆