Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Adding span to WordPress widget title

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #236278
    TWG
    Participant

    I found some code to break apart a word and add a span around the first word. Ideally I would like to add the span to everything but the first word but I can write my CSS code to work the other way.

    The only other part that I’m lost on is how can I interact with the widget title.

    function widget_titles($word)
    {
        $temp = explode(' ', $word);
        $temp[0] = '<span>' . $temp[0] . '</span>';
        $title = implode(' ', $temp);
        return $title;
    }
    

    Thanks for any help.

    #236432
    jmstopper
    Participant

    Hi TWG

    This should do the job. It uses the wordpress widget title filter which provides the widget title as a parameter. From there you can modify the title and return it once your happy.

    Documentation can be found at https://codex.wordpress.org/Plugin_API/Filter_Reference/widget_title

    function custom_widget_title($title) {
    $temp = explode(' ', $title);
    $temp[0] = '<span>' . $temp[0] . '</span>';
    $title = implode(' ', $temp);
    return $title;
    }
    add_filter('widget_title', 'custom_widget_title');

    #236433
    Ilan Firsov
    Participant

    Ideally I would like to add the span to everything but the first word but I can write my CSS code to work the other way.

    You can do something like this:

    <?php
    $string = "this is a test !";
    $string = explode(" ", $string);
    echo array_shift($string) . ' <span>' . implode(" ", $string) . '</span>';
    // returns:
    // this <span>is a test !</span>
    

    array_shift removes the first element from the array and returns it. Here I used it to isolate the first word from the rest of the ‘exploded’ string.
    This is easily adapted to wrap the first word with the spans by just moving where in the output string you concatenate the span:

    echo '<span>' . array_shift($string) . '</span> ' . implode(" ", $string);
    
Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘Back End’ is closed to new topics and replies.