Select dependent with multi-select | WordPress.org

[ad_1]

Hello, i have implemented this codesnippet to create a dependent select and it works; however i would like to implement multi-select. Any idea yo solve it? I tried but it disable the filter!

// Filter to initialize the second select (lessons) as empty
add_filter('fluentform/rendering_field_data_select', function ($data, $form) {
if ($form->id != 91) {
return $data;
}

// If it's the second select (lessons), we initialize it empty
if (\FluentForm\Framework\Helpers\ArrayHelper::get($data, 'attributes.name') == 'lesson_select') {
$data['settings']['advanced_options'] = []; // Initially empty the options
}

return $data;
}, 10, 2);

// AJAX handler to load lessons based on the selected course
add_action('wp_ajax_update_lesson_select', 'update_lesson_select');
add_action('wp_ajax_nopriv_update_lesson_select', 'update_lesson_select');

function update_lesson_select() {
// Verify and get the course ID
$selected_course_id = intval($_POST['selected_course_id']);
if (!$selected_course_id) {
wp_send_json_error('Invalid course ID');
}

// Get the lessons that belong to the selected course
$lessons = get_posts([
'post_type' => 'sfwd-lessons',
'meta_query' => [
[
'key' => 'course_id', // Make sure this meta field exists and links lessons to courses
'value' => $selected_course_id,
'compare' => '='
]
],
'numberposts' => -1
]);

// Check if lessons were found
if (empty($lessons)) {
wp_send_json_error('No lessons found for the selected course');
}

$options = [];
foreach ($lessons as $lesson) {
$options[] = [
'label' => $lesson->post_title,
'value' => $lesson->ID
];
}

// Send options as the AJAX response
wp_send_json_success($options);
}

// Add JavaScript to the footer to handle the change in the course select
add_action('wp_footer', function() {
?>
<script>
jQuery(document).ready(function($) {
// Change in the course select
$('select[name="course_select"]').on('change', function() {
var selectedCourseId = $(this).val();

// AJAX request to update the lesson select
$.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
method: 'POST',
data: {
action: 'update_lesson_select',
selected_course_id: selectedCourseId
},
success: function(response) {
var $lessonSelect = $('select[name="lesson_select"]');
$lessonSelect.empty();

if(response.success) {
// Add options to the lesson select
$.each(response.data, function(index, option) {
$lessonSelect.append(new Option(option.label, option.value));
});
} else {
alert('Error: ' + response.data);
}
}
});
});
});
</script>
<?php
});

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer