1

I'm trying to covert all menu items to title case; this is the function I'm using to change output to title case:

function titleCase($title) {

    $smallwordsarray = array( 'of','a','the','and','an','or','nor','but','is','if','then','else','when', 'at','from','by','on','off','for','in','to','into','with' );

    // Split the string into separate words
    $words = explode(' ', $title);

    foreach ($words as $key => $word) {

    // If this word is the first, or it's not one of our small words, capitalise it
    // with ucwords().
    if ($key == 0 or !in_array($word, $smallwordsarray))
        $words[$key] = ucwords($word);
    }

    // Join the words back into a string
    $newtitle = implode(' ', $words);

    return $newtitle;

}

}

So if for example I want to change the title output I can do this:

echo titleCase(get_the_title());

The issue is I don't know how to apply the above function to the wp_nav_menu() output:

<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id' => 'primary-menu' ) ); ?>

Any help greatly appreciated.

0

See if the following might work for you, I posted about it yesterday in response to another question so played around with it today. Also see the point in the codex of inheriting from Walker_Nav_Menu instead. You can subsequently modify the output of the menu and use your function.

Example from the codex:

<?php
class Walker_Quickstart_Menu extends Walker {

    // Tell Walker where to inherit it's parent and id values
    var $db_fields = array(
        'parent' => 'menu_item_parent', 
        'id'     => 'db_id' 
    );

    /**
     * At the start of each element, output a <li> and <a> tag structure.
     * 
     * Note: Menu objects include url and title properties, so we will use those.
     */
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        $output .= sprintf( "\n<li><a href='%s'%s>%s</a></li>\n",
            $item->url,
            ( $item->object_id === get_the_ID() ) ? ' class="current"' : '',
            $item->title
        );
    }

}

and

<ul>
    <?php
    wp_nav_menu(array(
        'menu'    => 2, //menu id
        'walker'  => new Walker_Quickstart_Menu() //use our custom walker
    ));
    ?>
</ul>

Reference: https://codex.wordpress.org/Class_Reference/Walker

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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