我在表单中使用wp_dropdown_categories来执行搜索,以过滤自定义帖子类型中的帖子。
<form method="get" action="#anchor" id="findresult">
<?php wp_dropdown_categories('name=location&child_of=2'); ?>
<input id="submit" type="submit" value="SEARCH"/>
</form>
提交表单后,我希望下拉列表保留用户选择的值。
首先,我不确定是否可以阅读以下链接中的文档?
https://codex.wordpress.org/Function_Reference/wp_dropdown_categories
我知道提交后我在$ GET数组中有位置ID,我知道我可以通过以下方式从中获取名称:
// 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>
我不知道该怎么做才将其设置为&#39;值&#39;表格提交后的下拉列表。
非常感谢所有的时间和帮助。
答案 0 :(得分:0)
根据wp_dropdown_categories docs,您只需传递selected
作为参数。
示例:
<?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>