2017-04-11 6 views
0

私はワードプレスウィジェットをコーディングしようとしていましたが、ウィジェット機能の$instance変数は空ですが、理由はわかりません。

<?php the_widget('mi_widget'); ?> 

と私は私のfunctions.phpファイル内でこのようなウィジェットを登録しています:私は私のサイドバーの外でウィジェットを使用しています

class mi_widget extends WP_Widget {  
    public function __construct() { 
     // instrucciones para esta función 
     parent::__construct(
      'mi_widget', // $id_base 
      'Soy un widget formidable', // $name 
      array('description' => __('Widget formidable que hace maravillas', 'mi-widget'),) // $widget_options 
     ); 
    } 
    public function widget ($args, $instance) { 
     // instrucciones para esta función 
     extract($args); 
     echo $before_widget.$before_title; 
     echo print_r($instance['mi_campo']); 
     echo $after_title.$after_widget; 
    } 
    public function update ($new_instance, $old_instance) { 
     // instrucciones para esta función 
     $instance = array(); 
     $instance['mi_campo'] = strip_tags($new_instance['mi_campo']); 
     return $instance; 
    } 
    public function form($instance) { 
     // instrucciones para esta función 
     if (isset($instance[ 'mi_campo' ])) { 
      $mi_campo = $instance[ 'mi_campo' ]; 
     } 
     else { 
      $mi_campo = __('Valor por defecto', 'mi-widget'); 
     } 
     ?> 
     <p> 
      <label for="<?php echo $this->get_field_id('mi_campo'); ?>"><?php _e('T&iacute;tulo:', 'mi-widget'); ?></label> 
      <input class="widefat" id="<?php echo $this->get_field_id('mi_campo'); ?>" name="<?php echo $this->get_field_name ('mi_campo'); ?>" type="text" value="<?php echo esc_attr ($mi_campo); ?>" /> 
     </p> 
     <?php 
    } 
    function get_field_name($field_name) { 
     return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']'; 
    } 
    function get_field_id($field_name) { 
     return 'widget-' . $this->id_base . '-' . $this->number . '-' . $field_name; 
    } 

} // Cierra la clase 

、私はこのコードでfront-page.phpでそれを使用しています

function wpb_load_widget() { 
    register_widget('mi_widget'); 
    register_sidebar(
     array(
      'name'=>'Home Widgets', 
      'id'=>'sidebar-1', 
      'class'=>'custome', 
      'description'=>'Here you can set the widgets that you want to display in home page.' 
     ) 
    ); 
} 
add_action('widgets_init', 'wpb_load_widget'); 

答えて

0

ウィジェットをサイドバーに配置してフォームを埋めれば、$ instanceが埋められます。 the_widget関数を使用して直接ウィジェットを呼び出す場合は、$インスタンスを第2パラメータとして渡す必要があります。たとえば、次のコード:

the_widget('mi_widget', array('mi_campo'=>'blahblah'))

がページについては、このリンクを参照してください:https://codex.wordpress.org/Function_Reference/the_widget

私はそれが役に立てば幸い。

関連する問題