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

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.