0

I am working on my header navigation and I want to underline the menu item for certain conditions.

I would like to add a CSS class if

  • the post has the ID 21638, or
  • the post has the meta value 'bloom'

The meta value is an ACF relationship field.

<nav class="header-navigation">
<ul class="header-navigation__list">
    <li <?php if (is_single(21638)) or (metadata_exists('bloom') echo 'class="current-menu-item"' ?>><a href="<?php echo site_url('/labels/bloom') ?>">Bloom</a></li>
</ul>

I managed to solve the post ID part, but how do I add condition regarding meta value?

2
  • 2
    Did you try changing or to ||? and you have a parenthesis in the wrong place. it should be if ( is_single(21638) || (metadata_exists('bloom') )
    – rudtek
    Dec 23, 2022 at 5:54
  • I've replaced the code with <?php if ( is_single(21638) or (metadata_exists('bloom') ) ) echo 'class="current-menu-item"' ?>. VSCode accepts it but I receive an Parse error: syntax error, unexpected 'echo' (T_ECHO) Dec 25, 2022 at 20:19

1 Answer 1

0

The good thing about ACF is it comes with lots of functions to check fields. Here is the manual. Are you creating a meta value in addition to the field and it's value? I'm guessing that you are looking for the value of the bloom field. If that's so then get_field('bloom',post->ID) should be what you're looking for. Also as rutec pointed out you closed your if parentheses before the second eval. I'm surprised that doesn't throw an error.

4
  • Hi Alex. I am building my website which displays a couple of record labels and dozens of albums. When you are on a label page, you can see all albums, that have been released under this label. To achieve that, I have setup two CPT's. The first is "labels" where each label is represented by a post. The second CPT is "albums". Every album has an ACF, relationship field where the related label has to be selected. Dec 25, 2022 at 20:31
  • In my header navigation, I have a link to the label "Bloom". When you are on it, ( is_single(21638), the CSS class is being echoed. I also want the class to be echoed on all "albums" posts that are related to "Bloom", i.e. that have the meta vale "Bloom". I had a look at the manual... Do I somehow have to create an object to achieve that? Dec 25, 2022 at 20:36
  • The advanced custom field "record label" has a value of "Bloom"? What do you mean by "meta vale "Bloom""?
    – Alex T.
    Dec 25, 2022 at 22:31
  • $value = get_field( "record_label" ); if ($value == "Bloom")...
    – Alex T.
    Dec 25, 2022 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.