duannaozhao4626 2018-05-14 12:18
浏览 104
已采纳

wp_dropdown_categories - 提交后保留值

I am using wp_dropdown_categories within a form to perform a search that filters posts within a custom post type.

<form method="get" action="#anchor" id="findresult">

    <?php wp_dropdown_categories('name=location&child_of=2'); ?>

    <input id="submit" type="submit" value="SEARCH"/>

</form>

Once the form is submitted I would like the dropdown to retain the value that the user has selected.

Firstly I'm not sure from reading the documentation in the link below if this is even possible?

https://codex.wordpress.org/Function_Reference/wp_dropdown_categories

I know that upon submission I have the location id in the $GET array and I understand that I can get the name from this by using the below:

// Get id of category
<?php $locid = $_GET["location"]; ?>

//Get category name from id
<?php $locname = get_cat_name( $locid ) ?>

// Echo name to show it's working as expected
<h1><?php echo $locname; ?></h1>

What I don't know how to do is to set this as the 'value' of the dropdown after the form has been submitted.

All time and help is greatly appreciated.

  • 写回答

1条回答 默认 最新

  • dongyunque2511 2018-05-14 14:46
    关注

    According to the wp_dropdown_categories docs, you simply pass in selected as an argument.

    Example:

    <?php 
    // initialize these to prevent errors
    $locname = '';
    $locid = '';
    
    // check if form is posted, to prevent notices
    if ( ! empty( $_GET['location'] ) ) {
        // Get id of category
        $locid = $_GET["location"]; ?>
    
        //Get category name from id
        $locname = get_cat_name( $locid );
    }
    ?>
    
    // Echo name to show it's working as expected
    <h1><?php echo $locname; ?></h1>
    
    <form method="get" action="#anchor" id="findresult">
    
        <?php 
        // use array notation for arguments.  It's cleaner /neater
        $args = array(
            'name' => 'location',
            'child_of' => 2
        );
    
        // if the location id is set, assign it to the arguments
        if ( ! empty( $locid ) ) {
            $args['selected'] = $loc_id;
        }
    
        wp_dropdown_categories( $args ); ?>
    
        <input id="submit" type="submit" value="SEARCH"/>
    
    </form>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan