wordpress中的小工具我希望在选定的下拉列表中更新内容


Widget in wordpress i want the content to update on selected dropdown

我不知道如何更改自定义小部件的内容
我正在Form函数中创建一个下拉列表,该下拉列表项是从表中生成的。当我选择其中一个下拉项并点击保存按钮时,我想从我的DB中加载一个内容并设置小部件的内容。

如果我在下拉列表中选择项目1,我想用项目1查询我的数据库,并更新小部件内容的内容。

我该怎么做?我知道有一个ajax调用从DB中获取数据,但我如何将数据设置为小部件内容?

function form($instance){
$select = esc_attr($instance['select']);
?>
    <select>
<?php
    require_once('../wp-load.php');
    global $wpdb;
    $query = $wpdb->get_results("SELECT titel FROM wp_layout");
    foreach($query as $result){
    echo '<option value="' .$result->titel. '">' .$result->titel.           '</option>';
    }
    ?>
    </select>
   function update($new_instance, $old_instance) {
    $instance = $old_instance;
    $instance['select'] = strip_tags($new_instance['select']);
    return $instance;
   }

我需要

函数小部件()

要制作一个自定义的wordpress小部件,首先必须制作您的自定义小部件类,该类将扩展wordpress核心的WP_widget类。

    // Creating the widget 
class My_Custom_Widget extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'my_custom_widget', 
// Widget name will appear in UI
__('My Custom Widget', 'my_custom_widget_domain'), 
// Widget description
array( 'description' => __( 'Sample widget', 'my_custom_widget_domain' ), ) 
);
}
// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
// This is where you run the code and display the output
echo __( 'Hello, World!', 'my_custom_widget_domain' );
echo $args['after_widget'];
}
// Widget Backend 
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'my_custom_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> 
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php 
}
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // Class ends here

并注册您的小工具:

// Register and load the widget
function custom_load_widget() {
    register_widget( 'my_custom_widget' );
}
add_action( 'widgets_init', 'custom_load_widget' );

现在,如果你想进行ajax调用,那么只需通过钩子注册你的ajax调用即可。Wordpress ajax