WordPress - 基于has_tag()的jquery选择器

I have a drop down selection for two choices (eg. books and records). By default is it books. The user will be redirected to another section on the site if they choose records. I want the dropdown to reflect how I have tagged the pages in WordPress using the has_tag condition. For example, if the page is tagged as "records", I want them to see records in the dropdown, and the opposite for books. Following is what I tried:

HTML:

 <select name="segment" id="segment">

  <option value="/book">Book</option>
  <option value="/record">Record</option>
</select>

<script type="text/javascript">
jQuery('#segment').change(function(){
window.location.href = jQuery(this).val();
});

jQuery(function(){
 jQuery("#segment > option").each(function() {
  if(this.value == window.location.pathname){
   this.selected = 'selected';
   }
 });
});

</script>

However, once they are on that page and click to any other page, it defaults to "book" again. I want to say that if the page has_tag('book'), then the option will be book, but if it the page has_tag('record'), then the option will be record. Any suggestions would be appreciated.

You can use the selected attribute of the <option> tag to do this. For example:

<select name="segment" id="segment">
    <option value="/book" <?php if ( has_tag('book') ) { echo 'selected'; } ?>>Book</option>
    <option value="/record" <?php if ( has_tag('record') ) { echo 'selected'; } ?>>Record</option>
</select>

I would get rid of the .each() function and just use PHP for this.