You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确格式化WordPress导航菜单函数以插入指定PHP代码?

Got it, let's get this sorted for you. The main issue here is that the_field() outputs the value directly right when you call it—great for template files, but not when you're building a string to return in a filter function. Instead, we'll use get_field() to grab the field value first, then build your link safely.

Here's the updated function that will output your desired ACF-powered link in the main menu:

add_filter('wp_nav_menu_items', 'add_acf_link_to_menu', 10, 2);
function add_acf_link_to_menu($items, $args){
    // Only target the main-menu location
    if( $args->theme_location == 'main-menu' ){
        // Get the ACF field value (use get_field instead of the_field)
        $acf_link_url = get_field('field-name-1');
        $acf_link_text = get_field('field-name-1'); // If you want different text, use a separate field
        
        // Only add the link if the field isn't empty
        if( !empty($acf_link_url) ){
            $items .= '<li><a href="'. esc_url($acf_link_url) .'">' . esc_html($acf_link_text) . '</a></li>';
        }
    }
    return $items;
}

Quick notes:

  • I renamed the function to something more descriptive (add_acf_link_to_menu) so it's clearer what it does.
  • We use esc_url() on the link URL and esc_html() on the link text to keep your site secure (always sanitize dynamic content in WordPress!).
  • Added a check for empty field values—this way you won't get an empty <li> element if the ACF field isn't filled out.
  • If you want the link text to be different from the URL (which makes sense!), just create a second ACF field (like field-name-2 for the text) and replace $acf_link_text = get_field('field-name-1'); with $acf_link_text = get_field('field-name-2');.

内容的提问来源于stack exchange,提问作者CharlyAnderson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:33:45