diff --git a/gp-populate-anything/gppa-wpml-current-language-choices.php b/gp-populate-anything/gppa-wpml-current-language-choices.php new file mode 100644 index 000000000..73f437911 --- /dev/null +++ b/gp-populate-anything/gppa-wpml-current-language-choices.php @@ -0,0 +1,84 @@ +cssClass ) ? $field->cssClass : ''; + if ( strpos( $css_class, 'wpml-limit-to-current-language' ) === false ) { + return $choices; + } + + // Get current WPML language (e.g. 'nl', 'en'). + $current_lang = apply_filters( 'wpml_current_language', null ); + if ( ! $current_lang ) { + return $choices; + } + + $filtered_choices = array(); + + foreach ( $choices as $index => $choice ) { + $post_id = 0; + $post_type = null; + + // Preferred: WP_Post object from $objects array. + if ( isset( $objects[ $index ] ) && $objects[ $index ] instanceof WP_Post ) { + $post_id = $objects[ $index ]->ID; + $post_type = $objects[ $index ]->post_type; + } + + // Fallback: use the choice value as post ID. + if ( ! $post_id && isset( $choice['value'] ) ) { + $post_id = absint( $choice['value'] ); + + if ( $post_id && ! $post_type ) { + $post_obj = get_post( $post_id ); + $post_type = $post_obj ? $post_obj->post_type : null; + } + } + + // If we can resolve a post and post type, apply WPML language check. + if ( $post_id && $post_type ) { + // Convert the post type to a WPML element type, e.g. 'post_post'. + $element_type = apply_filters( 'wpml_element_type', $post_type ); + + // Get the language code for this specific element. + $choice_lang = apply_filters( + 'wpml_element_language_code', + null, + array( + 'element_id' => $post_id, + 'element_type' => $element_type, + ) + ); + + // If WPML knows the language and it does not match the current language, skip this choice. + if ( $choice_lang && $choice_lang !== $current_lang ) { + continue; + } + } + + // Keep the choice. + $filtered_choices[] = $choice; + } + + return $filtered_choices; +}