自定义字段的问题是它们之间没有关系,因此无法将郊区与城市关联起来。
更好的方法是创建层次结构Custom Taxonomy 因此,您可以具有父子关系(如类别和子类别)。因此:
add_action( \'init\', \'create_locations_taxonomies\', 0 );
//create two taxonomies, genres and writers for the post type "book"
function create_locations_taxonomies()
{
// Add new taxonomy, make it hierarchical (like categories)
$labels = array(
\'name\' => _x( \'Locations\', \'taxonomy general name\' ),
\'singular_name\' => _x( \'Location\', \'taxonomy singular name\' ),
\'search_items\' => __( \'Search Locations\' ),
\'all_items\' => __( \'All Locations\' ),
\'parent_item\' => __( \'Parent Location\' ),
\'parent_item_colon\' => __( \'Parent Location:\' ),
\'edit_item\' => __( \'Edit Location\' ),
\'update_item\' => __( \'Update Location\' ),
\'add_new_item\' => __( \'Add New Locations\' ),
\'new_item_name\' => __( \'New Location\' ),
\'menu_name\' => __( \'Locations\' ),
);
register_taxonomy(\'location\',array(\'post\',\'page\',\'custom type\'), array(
\'hierarchical\' => true,
\'labels\' => $labels,
\'show_ui\' => true,
\'query_var\' => true,
\'rewrite\' => array( \'slug\' => \'location\' ),
));
}
这将在新建/编辑帖子屏幕中添加一个元框,就像类别一样,但用于位置,因此您可以添加城市和郊区作为其子位置。
完成后,您可以创建一个下拉列表,其中仅包含父位置(城市)wp_dropdown_categories() 类似这样:
$args = array(
\'show_option_none\' => \'select your location\',
\'hide_empty\' => 1,
\'echo\' => 1,
\'selected\' => 0,
\'hierarchical\' => 1,
\'name\' => \'p-location\',
\'class\' => \'postform\',
\'depth\' => 1,
\'tab_index\' => 0,
\'taxonomy\' => \'location\',
\'hide_if_empty\' => true );
wp_dropdown_categories( $args );
然后,您可以使用Jquery/ajax捕获此下拉列表的更改事件,获取所选ID的子项(郊区),并填充第二个下拉列表。
它还不完整,但应该让你开始。