首页 > 解决方案 > wordpress 插件 - 根据用户输入在新选项卡或页面上打开的按钮

问题描述

我有一个选择字段

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

允许用户选择是或否。然后将该值上传到 wp_postmeta 表

    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' );

如果用户选择是,则该按钮需要在新选项卡中打开

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

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

然后将其添加到按钮

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

我发现的问题是 $selected_yes == 'yes' 的结果即使选择了 yes 也不会返回值。任何想法将不胜感激。

标签: phphtmlwordpressplugins

解决方案


我会使用简单的 jquery 来检查选择了什么

输出的变化

<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>

你的jQuery代码

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

推荐阅读