如何正确格式化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 andesc_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-2for the text) and replace$acf_link_text = get_field('field-name-1');with$acf_link_text = get_field('field-name-2');.
内容的提问来源于stack exchange,提问作者CharlyAnderson
相关产品推荐
相关产品推荐

