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:
a:9:{i:2;a:0:{}i:3;a:3: {s:5:"title";s:0:"";s:4:"text";s:2:"mainItem";s:6:"filter";b:0;}i开发者_运维知识库:4;a:3: {s:5:"title";s:0:"";s:4:"text";s:9:"leftThree";s:6:"filter";b:0;}i:5;a:3: {s:5:"title";s:0:"";s:4:"text";s:10:"rightThree";s:6:"filter";b:0;}i:6;a:3: {s:5:"title";s:0:"";s:4:"text";s:8:"rightTwo";s:6:"filter";b:0;}i:7;a:3: {s:5:"title";s:0:"";s:4:"text";s:8:"rightOne";s:6:"filter";b:0;}i:8;a:3: {s:5:"title";s:0:"";s:4:"text";s:7:"leftOne";s:6:"filter";b:0;}i:9;a:3: {s:5:"title";s:0:"";s:4:"text";s:7:"leftTwo";s:6:"filter";b:0;} s:12:"_multiwidget";i:1;}
[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?
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'];
Try below code snippet. It return the array of all widgets stored data.
// 1. Initialize variables
$data = '';
$all_stored_widgets = array();
// 2. Get all widgets using - `$GLOBALS['wp_widget_factory']`
$all_widgets = $GLOBALS['wp_widget_factory'];
foreach ($all_widgets->widgets as $w => $value) {
$widget_data = get_option( 'widget_' . $value->id_base );
foreach ($widget_data as $k => $v) {
if( is_numeric( $k ) ) {
$data['id'] = "{$value->id_base}-{$k}";
$data['options'] = $v;
$all_widgets_css[$value->id_base][] = $data;
}
}
}
// 3. Output:
echo '<pre>';
print_r( $all_stored_widgets );
echo '</pre>';
Output:
精彩评论