0

Trying to save some plugin data to the wpdb using the update_option method. This code works fine for my single value ad_url, but fails for my array exclude_posts. The POST data in Chrome dev panel shows exclude_posts[] getting a value of 5, but nothing is going into the wpdb.

options.php

<form method="post" action="options.php">
<?php
    settings_fields('insert-video-ad-settings');
    do_settings_sections('insert-video-ad-settings');
?>
    <input id=adurl type="textarea" name="ad_url" autocomplete="off" value="<?php
    echo get_option('ad_url');
    ?>"/>

<?php
if(isset($_POST['exclude_posts'])) {
     $exclude_posts = $_POST['exclude_posts'];
}

if( isset( $exclude_posts ) )
{
   update_option( 'exclude_posts', $exclude_posts );
}
else
{
   delete_option( 'exclude_posts' );
}
?>

<select id="exclude_posts" name="exclude_posts[]" multiple="multiple">
       <?php
       $postslist = get_posts(array(
          'order' => 'ASC',
          'orderby' => 'date'
       ));
       $exclude = get_option('exclude_posts');
       If(!$exclude){
          $exclude=array();
       }
  if ($postslist) {
    global $post;
    foreach ($postslist as $post)
          {
          ?>
             <option value="<?php echo $post->ID; ?>" <?php echo ( in_array( $post->ID, $exclude ) ? 'selected' : '' ); ?> >
                <?php echo $post->post_title; ?>
             </option>
          <?php
          }
        }
       ?>
</select>

myplugin.php

add_action('admin_init', 'update_ad_url');

if (!function_exists("update_ad_url")) {
    function update_ad_url()
    {
        register_setting('insert-video-ad-settings', 'ad_url');
    }
}

add_action('admin_init', 'update_exclude_posts');

if (!function_exists("update_exclude_posts")) {
    function update_exclude_posts()
    {
        register_setting('insert-video-ad-settings', 'exclude_posts');
    }
}
0

If $_POST['exclude_posts'] is an array but you need to store it as a string, you can always use a function like serialize() and unserialize() to turn it into a string and vice versa.

http://php.net/manual/en/function.serialize.php

  • I'm not sure this is the issue. Maybe I'm not really following this adapted code well. print_r($_POST); always returns null, even while saving my ad_url data. – user255406 Sep 16 '18 at 19:57
  • 1
    If POST is empty even after a form submit, it usually means that the page has been redirected. – Michael Sep 16 '18 at 20:01
  • This helped me figure it out. Removing this code fixed it. <?php if(isset($_POST['exclude_posts'])) { $exclude_posts = $_POST['exclude_posts']; } if( isset( $exclude_posts ) ) { update_option( 'exclude_posts', $exclude_posts ); } else { delete_option( 'exclude_posts' ); } ?> – user255406 Sep 16 '18 at 22:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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