Programmatically edit the text of a widget

I guess you want to locate the widget by it’s title, so you can try this function:

/**
 * Update a widget text located by it's title
 * 
 * @see https://wordpress.stackexchange.com/a/155518/26350
 *
 * @param string $search_title
 * @param string $new_text
 * @param boolean
 */

function wpse_155046_update_widget_text_by_title( $search_title, $new_text )
{
    // Get all data from text widgets 
    $widgets = get_option( 'widget_text' );

    foreach( $widgets as $key => $widget )
    {       
        // Compare and ignore case:
        if( mb_strtolower( $search_title ) === mb_strtolower( $widget['title'] ) )
        {
            // Replace the widget text:
            $widgets[$key]['text'] = $new_text;

            // Update database and exit on first found match:
            return update_option( 'widget_text', $widgets );
        }
    }
    return false; 
}

where we only replace the text of the first widget instance that matches the given title.

Usage example:

You can apply the above function like demonstrated here:

if( wpse_155046_update_widget_text_by_title( 
        'My fruits', 
        'Five green apples and nine oranges.' 
     ) 
)
{
    echo 'success';
}
else
{
    echo 'no success';
}

where we replace the text of the widget with the title My fruits.

Before:

before

After:

after

You can also check out my answer here on where the widget data is located in the database.

Update:

A good question from @Tony in the comments below, how one could replace the widget text given the instance number. Here’s an untested idea:

/**
 * Update a widget text located by it's instance number
 * 
 * @see https://wordpress.stackexchange.com/a/155518/26350
 *
 * @param string $id
 * @param string $new_text
 * @param boolean
 */

function wpse_155046_update_widget_text_by_instance_number( $instance_number, $new_text )
{
    // Get all data from text widgets 
    $widgets = get_option( 'widget_text' );

    if( isset( $widgets[$instance_number]['text'] ) ) 
    {
        // Replace the widget text:
        $widgets[$instance_number]['text'] = $new_text;

        // Update database and exit on first found match:
        return update_option( 'widget_text', $widgets );
    }
    return false; 
}

Leave a Comment