wp_nav_menu exclude pages from menu

2019-08-19 05:38发布

问题:

I am trying to exclude pages from wp_nav_menu

Here is the function to exclude pages from menu Works well when

  <?php $page = get_page_by_title('my title' );
   wp_nav_menu( array( 'theme_location' => 'menu-2', 'exclude' => $page->ID  ) ); ?>

Works properly

BUt when using

   <?php $page = get_page_by_title('my title' );
         $pag1 = get_page_by_title('my title 1' );
         $pag2 = get_page_by_title('my title2' );
   wp_nav_menu( array( 'theme_location' => 'menu-2', 'exclude' => $page->ID,$pag1->ID,$pag2->ID  ) ); ?>

Doesn't work properly.

回答1:

try this

wp_nav_menu( array( 'theme_location' => 'menu-2', 'exclude' => '".$page->ID.",".$pag1->ID.",".$pag2->ID."'  ) ); 

checkout this tutorial



回答2:

Here is the correct solution

I hope it helps some other people

<?php 
$page = get_page_by_title('my title' );
$pag1 = get_page_by_title('my title 1' );
$pag2 = get_page_by_title('my title2' );

$ids = "{$page->ID},{$pag1->ID},{$pag2->ID}";
wp_nav_menu( array( 'theme_location' => 'menu-2', 'exclude' => $ids ) ); 
?>    


回答3:

It should work if you put the pages that you want to exclude into an array.

Check out this: http://ehsanis.me/2010/11/30/wordpress-wp_nav_menu-to-exclude-pages/



回答4:

Managed it using the exclude method, but exclude by page id:

wp_nav_menu( 
  array( 
   'theme_location' => 'menu-2', 
   'exclude' => '599, 601'  
  ) 
); 

(599 & 601 are page id's)

which is written here:

http://bacsoftwareconsulting.com/blog/index.php/wordpress-cat/wordpress-tip-how-to-exclude-pages-from-wp_nav_menu-function/

and finding the page id manually is written here:

http://bacsoftwareconsulting.com/blog/index.php/wordpress-cat/how-to-find-tag-page-post-link-category-id-in-wordpress/



回答5:

You can use a Custom Walker Function to just skip the rendering of the menu item.

wp_nav_menu( array(
    'theme_location' => 'menu-2',
    'walker'         => new custom_navigation
) );

class custom_navigation extends Walker_Nav_Menu {

    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

        parent::start_el($item_html, $item, $depth, $args);

        $exclude = array();
        $exclude[] = get_page_by_title( 'my title' );
        $exclude[] = get_page_by_title( 'my title 1' );
        $exclude[] = get_page_by_title( 'my title2' );

        if ( ! in_array( $item->object_id, $exclude ) ) {

            // add your menu item html to the $output variable

        }

    }

}


标签: php wordpress