Home > Software engineering >  wordpress plugin - button to open in new tab or on page based on user input
wordpress plugin - button to open in new tab or on page based on user input

Time:10-29

i have a select field

     <select name="URL_tab">
        <option name="yes" id="yes">yes</option>
        <option name="no" id="no">no</option>
     </select>

that allows a user to select yes or no. the value is then uploaded to the wp_postmeta table

    function Modal_save_meta_box( $post_id ) {
  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
  if ( $parent_id = wp_is_post_revision( $post_id ) ) {
      $post_id = $parent_id;
  }

  $fields = [
      'headline',
      'sub_headline',
      'button_text',
      'date_live',
      'date_close',
      'destination_url',
      'URL_tab',
      'yes',
      'no'
  ];

  foreach ( $fields as $field ) {
      if ( array_key_exists( $field, $_POST ) ) {
          update_post_meta( $post_id, $field, sanitize_text_field( $_POST[$field] ) );
      }
   }
}
add_action( 'save_post', 'Modal_save_meta_box' );

the button then needs to open ina new tab if the user selected yes

$selected_yes = get_post_meta(1408, 'yes', true);

if($selected_yes == 'yes'){
  $url_target= 'target_"blank" ';
}else{
  $url_target= 'target_"self" ';
}

which is then added to the button

<a href="<?php echo $destination_url ?>" <?php echo $url_target ?>class="button-link"><?php echo $button_text;?></a>

the problem i am finding is that the result of $selected_yes == 'yes' doesnt return a value even if yes is selected. any ideas would be greatly appreciated.

CodePudding user response:

I would use simple jquery to check what is selected

Abit of changes in your output

<select id="myselect" name="URL_tab">
    <option>Select Option</option>
    <option name="yes" id="yes">yes</option>
    <option name="no" id="no">no</option>
 </select>
 <a href="#" id="myselect-button" class="button-link">Link</a>

Your jquery code

jQuery(function($){
    $('#myselect').change(function(){
        if($(this).val() == 'yes'){
          $('#myselect-button').attr('target','_blank');
        }else {
          $('#myselect-button').attr('target','_self');
        }
    });
});

CodePudding user response:

It seems the html is wrong. Please use below code to set target:

if($selected_yes == 'yes'){
  $url_target= 'target="blank" ';
}else{
  $url_target= 'target="self" ';
}

You write "_" instead if "=".

  • Related