同时调用the_title与document_title导致菜单项异常的问题
解决动态页面标题替换时菜单项被修改的问题
问题分析
你需要在带?filter=most-viewed的动态页面替换document_title和the_title,但当前实现会把菜单项标题也改成自定义内容。is_nav_menu()函数无效是因为它仅用于判断当前页面是否是后台的导航菜单编辑页,而非前端菜单项的渲染上下文。另外document_title钩子不在循环内,不能把替换逻辑全放进in_the_loop()判断里。
解决方案
通过给the_title过滤器传递额外参数,利用其第三个参数$context判断是否为导航菜单项,同时区分循环内标题和页面标题的处理逻辑,用同一个函数完成需求:
- 调整过滤器注册,给
the_title添加参数支持:
add_filter( 'document_title', 'custom_title', 10 ); add_filter('the_title', 'custom_title', 10, 3); // 第三个参数3表示接受3个参数
- 修改自定义标题函数:
function custom_title( $title, $post_id = null, $context = null ) { // 安全获取filter参数 $filter = isset( $_REQUEST['filter'] ) ? sanitize_text_field( $_REQUEST['filter'] ) : ''; // 导航菜单项直接返回原标题 if ( $context === 'nav_menu' ) { return $title; } // 循环内的文章标题返回原标题 if ( in_the_loop() && $post_id ) { $post = get_post( $post_id ); return $post ? $post->post_title : $title; } // 仅在filter为most-viewed时替换标题 if ( $filter === 'most-viewed' ) { return 'Most Viewed'; } // 默认返回原标题 return $title; }
逻辑说明
the_title过滤器的第三个参数$context在渲染导航菜单时会被设为nav_menu,通过这个判断直接跳过替换逻辑。- 循环内的文章标题通过
in_the_loop()和$post_id获取原文章标题返回。 document_title钩子调用时不会传递$post_id和$context,会直接执行filter替换逻辑,保证页面标题正常修改。
内容的提问来源于stack exchange,提问作者Mario Rossi
相关产品推荐
相关产品推荐

