如何在我的小部件中检索数据

时间:2014-10-21 作者:csharpdude77

我有一个正在创建的小部件,但我的问题是如何访问通过插件创建的自定义表。我试图填写名为tfp的表格中的下拉列表,该表格包含我希望将值放入下拉列表中的列“升”

class my_plugin extends WP_Widget {

// constructor
function my_plugin() {
        parent::WP_Widget(false, $name = __(\'Thomsons Fuels Widget\', \'wp_widget_plugin\') );

}

// widget form creation
function form($instance) {

//Check values
if( $instance) {
 $title = esc_attr($instance[\'title\']);
 $dropdown= esc_attr($instance[\'dropdown\']);
 $textarea = $instance[\'textarea\'];
 } else {
 $title = \'\';
 $textarea = \'\';
}
?>


<p>
<label for="<?php echo $this->get_field_id(\'dropdown\'); ?>">
<?php _e(\'Liters\',   \'wp_widget_plugin\'); ?></label>
<select>
<option value="volvo">Volvo</option>
</select>

</p>
如何在插件中创建表

global $wpdb;
global $custom_table_example_db_version;

$table_name = $wpdb->prefix . \'tfp\'; // do not forget about tables prefix

// sql to create your table
// NOTICE that:
// 1. each field MUST be in separate line
// 2. There must be two spaces between PRIMARY KEY and its name
//    Like this: PRIMARY KEY[space][space](id)
// otherwise dbDelta will not work
$sql = "CREATE TABLE " . $table_name . " (
  id int(11) NOT NULL AUTO_INCREMENT,
  liters VARCHAR(100) NOT NULL,
  price VARCHAR(100) NOT NULL,   
  postcodearea varchar(20) NULL,      
  dft varchar(20) NULL,
  PRIMARY KEY  (id)
);";

// we do not execute sql directly
// we are calling dbDelta which cant migrate database
require_once(ABSPATH . \'wp-admin/includes/upgrade.php\');
dbDelta($sql);

// save current database version for later use (on upgrade)
add_option(\'custom_table_example_db_version\', $custom_table_example_db_version);

1 个回复
SO网友:shanebp

Read: SELECT_a_Column

$sql = "SELECT \'liters\' FROM " . $wpdb->prefix . "tfp";

$liters = $wpdb->get_col( $sql );
if( $liters ) { 
  foreach( $liters as $liter ) { 
        echo \'<option value="\' . $liter . \'">\' . $liter . \'</option>\';
  }
}
结束