Support

Account

Home Forums ACF PRO Having current_menu_item when using a relationship field

Helping

Having current_menu_item when using a relationship field

  • I’m using relationship fields to build internal navigation like so:

    <?php 
    $nav_items = get_field('field_name');
    if( $nav_items ):
    ?>
      <ul>
        <?php foreach( $nav_items as $nav_item ):?>
        <li><a href="<?php echo get_permalink( $nav_item->ID ); ?>"><?php echo get_the_title( $nav_item->ID ); ?></a></li>
        <?php endforeach; ?>
      </ul>
    <?php endif; ?>

    Is it possible to add some functionality into this so a CSS class of current_page_item is added to the <li> when I’m on that particular page? Similar to how the stock WordPress navigation works?

    So it could like this:

    <ul>
      <li><a href="#">Menu item 1</a></li>
      <li class="current_page_item"><a href="#">Menu item 2</a></li>
    </ul>

    Is this even possible? Thanks in advance!

  • Hi @abbasinho

    One way to accomplish that is to use the WP function get_queried_object_id

    With that you can grab the Post/Page ID of the current page before you start iterating through your loop.

    Then, in your loop you can match $nav_item->ID with the returned value of get_queried_object_id then you can apply the class appropriately.

    In my testing, I set a variable containing the class name at the top of the loop if there was a match, then reset the variable at the end of the loop. There are a bunch of different ways, but using get_queried_object_id is key.

    I realize this is a late reply, but hopefully it’s helpful to you or someone else.

    Here’s my test code:

    <?php
    $current_page_id = get_queried_object_id();
    $class = '';
    $posts = get_field('relationship', 23);
    if( $posts ) {
      $content .= '<ul>';
      foreach( $posts as $p ) {
        if ( $current_page_id == $p->ID ) {
          $class = ' style="text-decoration:line-through"';
        }
        $content .= '<li>';
        $content .= '<a href="' . get_permalink( $p->ID ) .'"' . $class . '>' . get_the_title( $p->ID ) . '</a>';
        $content .= '</li>';
        $class = '';
      }
      $content .= '</ul>';
    }
    echo $content;
    ?>
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Having current_menu_item when using a relationship field’ is closed to new replies.