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

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?

Leave a Reply

Your email address will not be published. Required fields are marked *