konzepz konzepz - 1 year ago 59
MySQL Question

Retrieving widget data with MySQL query in WordPress

I've built up multiple dynamic sidebars for front page item manipulation. Each sidebar contains a Text widget, and I want to retrieve each widget's content (according to widget ID) from wp_options.

Basically, the structure is

dbName -> wp_options -> option_id #92
contains the following:


[Actually all on one line.]

I want to retrieve the following strings:

  • mainItem

  • leftOne/leftTwo/leftThree

  • rightOne/rightTwo/rightThree

What's the syntax for such a query? And how can I add it to the PHP template?

Answer Source

You can pull all of the information about a type of widget from the database like so:

$text_widgets = get_option( 'widget_text' );

There's no need to use mySQL to get this. This will return an array of all the stored widgets of the type 'text'. Then you can loop through this array and do stuff with the internal properties of each like so:

foreach ( $text_widgets as $widget ) {
    extract( $widget );
    // now you have variables: $mainItem, $leftOne, $leftTwo, etc.
    // do something with variables	

Or, if you already know the ID's of the widgets you want to interact with, you can access the properties like this:

$mainItem = $text_widgets[17]['mainItem'];