0

I am having a heck of a time solving this problem. Please help me find the right way to do this. I am creating a widget that has a dropdown populated with data from custom table; This is the form code:

public function form($instance) {
       global $event;
       global $events;       
       $events = new WP_Query( "SELECT id, event FROM mo_Event");
     ?>     
    <select class="dropdown" id="mydropdown" name="mydropdown" title="My Dropdown">
    <?php
    foreach ($events as $event) { ?> 
      <option value="' . <?php $event . '">' . $event . '?> </option>';
    }?>
  </select>
  } 

This line: <option value="' . <?php $event . '">' . $event . '?> </option>'; is getting "PHP Notice: Array to string conversion" And "PHP Catchable fatal error: Object of class WP_Tax_Query could not be converted to string " Any help is appreciated.

1 Answer 1

0

You have to use get_results() instead of WP_Query.

I have made changes in your code and tested at my end and it is working for me. I have also save that value using update() function of widget. You can take reference from below code.

  public function form( $instance ) {

    if ( isset( $instance[ 'mydropdown' ] ) )
    $selectedvalue = $instance[ 'mydropdown' ];
    else
    $selectedvalue = __( '', 'text-domain' );

    global $event;
    global $events;       
    global $wpdb;  

     $events = $wpdb->get_results("SELECT id, event FROM mo_Event",ARRAY_A);
       ?>     
      <select class="dropdown" id="<?php echo $this->get_field_name( 'mydropdown' ); ?>" name="<?php echo $this->get_field_name( 'mydropdown' ); ?>" title="My Dropdown">
      <?php
      foreach ($events as $event) {
      $selected = ($event->id == $selectedvalue) ? 'selected' : '';  
        echo '<option value="'.$event->id.'" '.$selected.'>'.$event->event.'</option>';
      }
      ?>
      </select>
      <?php
  }

  public function update( $new_instance, $old_instance ) {
    $instance = array();
    $instance['mydropdown'] = ( ! empty( $new_instance['mydropdown'] ) ) ? strip_tags( $new_instance['mydropdown'] ) : '';
    return $instance;
  }
1
  • I need to make a long response with code snippets. How can I do that? Commented May 7, 2020 at 13:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.