我有两个下拉列表。第一个包含自定义帖子类型的父分类列表。第二个一次包含所有子分类。但我试图只显示selected 父分类法(不是来自其他父分类法的所有子分类法)。例如,如果我从第一个下拉列表中选择父分类,那么第二个下拉列表应该只显示它的子分类。我没找到php
实现这一目标的逻辑。我在“编辑个人资料”页面上显示这两个下拉列表。这是我的密码functions.php
<?php
function slcustom_user_profile_fields($user) { ?>
<h1 id="temppp">Select a parent taxonomy</h1>
<select name="parent_category" id="parent_category">
<?php
global $wpdb;
$parentCat = $wpdb->get_results( "SELECT name FROM wp_terms WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE taxonomy = \'project_category\' AND parent = 0)" );
foreach ( $parentCat as $cat ) { ?>
<option value="<?php echo esc_attr( $cat->name ) ?>"<?php echo selected( $user->parent_category, $cat->name ); ?>><?php echo $cat->name; ?></option>
<?php }
?>
</select>
<p>Select a child taxonomy</p>
<select name="child_category" id="child_category">
<?php
//trying to bring this $termName value from JS
if(isset($_POST[\'selectedParentName\'])) {
$termName = isset($_POST[\'selectedParentName\']);
}
$termId = get_term_by(\'name\', $termName, \'project_category\');
$selectedTermId = $termId->term_id;
$id = $selectedTermId;
$childCats = $wpdb->get_results( "SELECT name FROM wp_terms WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE taxonomy = \'project_category\' AND parent = ".$id." )" );
foreach ($childCats as $childCat) { ?>
<option value="<?php echo esc_attr( $childCat->name ) ?>"<?php echo selected( $user->child_category, $childCat->name ); ?>><?php echo $childCat->name; ?></option>
<?php }
?>
</select>
<?php
}
add_action(\'show_user_profile\', \'slcustom_user_profile_fields\');
add_action(\'edit_user_profile\', \'slcustom_user_profile_fields\');
function save_custom_user_profile_fields($user_id) {
if( current_user_can(\'edit_user\', $user_id) ) {
update_user_meta($user_id, \'parent_category\', $_POST[\'parent_category\']);
update_user_meta($user_id, \'child_category\', $_POST[\'child_category\']);
}
}
add_action(\'personal_options_update\', \'save_custom_user_profile_fields\');
add_action(\'edit_user_profile_update\', \'save_custom_user_profile_fields\');
script.js
$(\'select#parent_category\').on(\'change\', function() {
var selectedParentName = this.value; //it tracks changes dropdown value
$.ajax({
type: \'POST\',
url: \'http://localhost:3000/wp-content/themes/mytheme/functions.php\',
data: { selectedParentName : selectedParentName }, //trying to send this \'selectedParentName\' to functions.php
success: function(data) {
var sendThisDataToPHP = selectedParentName;
}
});
});
2019年2月19日更新:脚本。添加了js,函数上的行数很少。php接收JS变量。