0

Hello i wonder if you can help me. How do you make to post titles capitalize the first letter of every word?

Is there a way to do it in wordpress?

1
  • 1
    Then there's CSS: .entry-title { text-transform: capitalize; }
    – birgire
    Commented Dec 16, 2018 at 10:45

3 Answers 3

2

The code below was assembled of different pieces I've found around and it was not tested. Consider it as an idea only.

<?php
add_filter( 'the_title', 'my_capitalize_title', 10, 2 );

function my_capitalize_title( $title, $id ) {

    // get separate words
    $words = preg_split( '/[^\w]*([\s]+[^\w]*|$)/', $title, NULL, PREG_SPLIT_NO_EMPTY );

    $stop_words = array(
        'the', //
        'a',
        'and',
        'of',
    );

    $title_case = '';

    foreach( $words as $word ) {
        // concatenate stop word intact
        if ( in_array( $word, $stop_words ) ) {
            $title_case .= $word;
        }
        // or concatenate capitalized word
        $title_case .=  ucfirst( $word );
    }

    return $title_case;
}

You have to polish the idea: you don't want "The Simpsons" to become "the Simpsons".

0

WordPress is based on PHP. So, a better question might be, "Is there a PHP function that will do this?" The answer given above ucwords; is correct. However, there may be words you don't want capitalized, such as "a", "an" or "the". If that is the case, there needs to be a filter that prevents these words from being capitalized. However, that is beyond the scope of this question.

0

Is this for <title></title> or output title?

If output title, call your title as echo ucwords( get_the_title() ); on your page.

If <title></title>, you can do the same as above by applying a filter to wpseo_title in your functions file.

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.