在WordPress类别下拉列表中传递选定的值

时间:2017-06-11 21:29:46

标签: php jquery wordpress post custom-wordpress-pages

我有自定义分类法,并且我已在归档页面中添加了类别下拉列表,以允许用户在类别之间快速切换。我有以下代码,用于将用户重定向到他们选择的新类别。但是,下拉列表始终默认为<select>中的第一个选项。如何通过选定的<option>并将其设置为用户切换类别时的默认值?

<?php
$args = array(
  'taxonomy'     => 'custom_taxonomy',
  'orderby'      => 'name',
  'show_count'   => 1,
  'hierarchical' => 1,
  'title_li'     => 'title'
);

<form id="categoriesform" action="<?php bloginfo('url'); ?>" method="post">
    <div>
        <?php $cats = get_categories($args); ?>
        <select id="categories" name="custom_taxonomy">
            <option value="allCategories">All Categories</option>
            <?php foreach ($cats as $cat) : ?>
                <option value="<?php echo get_term_link($cat, $cat->taxonomy) ?>">
                <?php echo $cat->name ?></option>
            <?php endforeach; ?>
        </select>
    </div>
</form>
<script>
jQuery(document).ready(function() {
    jQuery('#categories').change(function() {
        if (jQuery(this).val() == 'allCategories') {
            window.location = 'http://example.com/all-categories';
        } else {
            window.location = jQuery(this).val();
        }
    });
});
</script>

1 个答案:

答案 0 :(得分:1)

首先,您需要通过get_queried_object()->term_id;获取当前类别ID,然后检查并添加所选的选项。

<?php
 $current=get_queried_object()->term_id;
$args = array(
 'taxonomy'     => 'custom_taxonomy',
 'orderby'      => 'name',
 'show_count'   => 1,
 'hierarchical' => 1,
 'title_li'     => 'title'
);

<form id="categoriesform" action="<?php bloginfo('url'); ?>" method="post">
<div>
    <?php $cats = get_categories($args); ?>
    <select id="categories" name="custom_taxonomy">
        <option value="allCategories">All Categories</option>
        <?php foreach ($cats as $cat) : ?>
            <option <?php echo ($current == $cat->term_id ? 'selected' : ''); ?> value="<?php echo get_term_link($cat, $cat->taxonomy) ?>">
            <?php echo $cat->name ?></option>
        <?php endforeach; ?>
    </select>
</div>
</form>
<script>
jQuery(document).ready(function() {
   jQuery('#categories').change(function() {
    if (jQuery(this).val() == 'allCategories') {
        window.location = 'http://example.com/all-categories';
    } else {
        window.location = jQuery(this).val();
    }
});
});
</script>