Tackle specific Array Key

I am not a PHP expert or even intermediate by any means.

I am trying to assign a couple of HTML spans to a post title in a WordPress page.php

Read More

One span will be added to the first word of the title and the other span should apply to the rest of the rest of the title.
I started with this code, which got me half way there:

<?php
    $words = explode(' ', the_title('', '',  false));
    $words[0] = '<span class="bold-caption">'.$words[0].'</span>';
    $title = implode(' ', $words);
    echo $title;
?>

As you can see the first Key of the array has the first spam assigned.

I can’t manage to assign the other to the rest of the title.

How can I accomplish this? Thank you in advance.

Related posts

1 comment

  1. You’re close…I’d unset() the first item after adding a span around it, implode() the rest, and concatenate:

    <?php
        // Split the title into an array of words
        $words = explode(' ', get_the_title());
        // Create a new title, with the first word bolded
        $newtitle = '<span class="bold-caption">' . $words[0] . '</span>';
        // Remove the first word from the array of title words
        unset($words[0]);
        // Concatenate the remaining words (in a new span) to the first word
        $newtitle .= '<span>' . implode(' ', $words) . '</span>';
    
        echo $newtitle;
    ?>
    

Comments are closed.