Set post title font size automatically according to number of words in post title

When creating a post, i would like for it to check if the post title i set is longer than let’s say 15 characters, if it is then i want to change the font size to a smaller size. I am using the Enfold Theme.

Does anybody know a function to check this?

Thanks in advance!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You need to target the the_title filter.

In that filter we can manipulate the output string as we need.

add_filter('the_title', 'bt_the_title');
function bt_the_title ($title) {
    if (current_user_can('administrator')) {
        if (strlen($title) > 15) {
            $title = '<span class="font18px">' . $title . '</span>';
            $title = '<span style="font-size: 18px">' . $title . '</span>';
        }
    }

    return $title;
}

add the code in your functions.php file of the child theme.

A few notes.

current_user_can(‘administrator’) is only used to development, i don’t know if the site you are working on is live, so for this changed to not affect users i warped the code in this function check. You can remove it once you are happy with the result.

there are two $title, you only need one.

The first $title adds a span with a custom class, you can add css for that class in the main css file of your theme.

The second $title adds a span with inline style, this option lets you add the style without the need to edit the main css file.

Choose the option that works for you.

You can also change the span tag with what ever you need, I used span because it a tag that used mainly for styling and will not affect the title semantic.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x