4

I'm trying to change the text displayed for the anchor tags in the wp_nav_menu li's.

I actually managed to do this with jQuery, nothing fancy, because I am certainly no professional. You can see the basic code here:

jQuery(document).ready(function () {

    jQuery('.menu-item-30 > a').html('<i class="fas fa-home"></i>');

});

It works, this code will find the anchor tag in the desired nav menu li and change the icon to a tiny little house for the home page. The problem is that when I load the page, for the briefest second, before the house loads I can see the original text in that anchor tag which is "home" and it looks unprofessional. What I am trying to say, is that the page loads and then this code noticeably runs after.

Therefore, I figured this is maybe where filters and hooks come into play. However, from what I understand, you can't really wrap jQuery in PHP and set it as a filter, right? Maybe I just need to change "ready" in jQuery to something else.

Therefore, how can I change the text in between <a> and </a> from 'Home' to <i class="fas fa-home"></i> while at the same time, having it load while the page loads and not after?

1 Answer 1

8

One way to achieve such effect would be to use wp_nav_menu_objects hook.

function modify_home_in_nav_menu_objects( $items, $args ) {
    foreach ( $items as $k => $object ) {
        // you can also target given page using this if:
        // if ( 'page' == $object->object && 2 == $object->object_id ) {
        if ( 30 == $object->ID ) {
            $object->title = '<i class="fas fa-home"></i>';
        }
    }
    return $items;
}
add_filter( 'wp_nav_menu_objects', 'modify_home_in_nav_menu_objects', 10, 2 );

PS. Should it really be fas and not fa in there?

3
  • Thank you, that solved my issue and I will be sure to examine your code and figure out how it works the way it does. As for the font awesome code, that's just what I copied from the official site but I have heard it changes slightly from version to version.
    – Ruke
    Jun 5, 2018 at 2:30
  • @Ruke ahh, maybe you’re right :) Jun 5, 2018 at 5:24
  • yes and it's not the page's id, but an id of a menu item, you will find it by devtools inspector either on site or in the menus admin
    – Fanky
    Mar 10, 2021 at 11:12

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.