WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] is it possible to make a 'primary' category for wp_nav_menu() to highlight? (3 posts)

  1. kn00tcn
    Member
    Posted 11 months ago #

    if a post is in multiple categories, is there a way to have the admin select which category is the primary one so that wp_nav_menu() highlights only the primary category instead of all the categories the post is in?

    one possible hack is to use a custom field that gets read by javascript to highlight the menu item on page load, but is there a better way?

  2. esmi
    Forum Moderator
    Posted 11 months ago #

    Not as far as I am aware. WordPress tends to view post categories in ID order (ie date created).

  3. kn00tcn
    Member
    Posted 11 months ago #

    ok that went better than expected, i have it working fine using the 'advanced custom fields' plugin to create a dropdown in the post edit screen

    if nothing is selected, it highlights the categories as it does with wp_nav_menu, whether it's one category or several

    if a primary category is selected, it highlights only that one

    if disable highlight is selected, no menu items are highlighted

    <ul id="testmenu">
    	<?php function sportmenu($sport) {echo '<li><a href="'.get_term_link($sport,'sports').'" id="msport-'.$sport.'">'.$sport.'</a></li>';}
    	sportmenu('Basketball');
    	sportmenu('Football');
    	sportmenu('Hockey');
    	sportmenu('And So On...');?>
    
    	<?php global $wp_query;
    		$psport = get_field('primary_sport');
    		$osport = get_the_terms($wp_query->post->ID,'sports');
    
    		if ($psport) {
    			if ($psport != 'none' && $psport != 'disable') : ?>
    				<script type="text/javascript">
    					$('#testmenu #msport-<?php echo $psport; ?>').addClass('active');
    				</script>
    			<?php endif; if ($psport == 'none') : ?>
    				<script type="text/javascript">
    					<?php foreach($osport as $term){echo "$('#testmenu #msport-".$term->name."').addClass('active');";} ?>
    				</script>
    			<?php endif;
    		}
    	?>
    </ul>

    yes you can see that i'm actually using custom taxonomies instead of built in categories, I AM INVINCIBLE

Reply

You must log in to post.

About this Topic