Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adds a language selector to the Location rules for ACF, allowing you to restrict a field group to appear only on admin pages of the selected language.
<?php
/**
* ACF Rule: adds Post Language type
*
* @author @theMikeD
*
* @param array $choices, all of the available rule types
* @return array
*/
function cnmd_acf_rule_type_language( $choices ) {
$choices['Post']['post_language'] = 'Post Language';
return $choices;
}
add_filter( 'acf/location/rule_types', 'cnmd_acf_rule_type_language' );
/**
* ACF Rule: populate language option based on active languages.
*
* @param array $choices, available rule values for this type
* @return array
*/
function cnmd_acf_rule_values_language( $choices ) {
$active_languages = apply_filters( 'wpml_active_languages', NULL, 'orderby=id&order=desc' );
foreach ( $active_languages as $code=>$properties ) {
$choices[$code] = $properties['translated_name'];
}
return $choices;
}
add_filter( 'acf/location/rule_values/post_language', 'cnmd_acf_rule_values_language' );
/**
* ACF Rule: Performs the test to determine if the ACF field group should appear for the language test.
*
* @param boolean $match, whether the rule matches (true/false)
* @param array $rule, the current rule you're matching. Includes 'param', 'operator' and 'value' parameters
* @param array $options, data about the current edit screen (post_id, page_template...)
* @return boolean $match
*/
function cnmd_acf_rule_match_language( $match, $rule, $options ) {
if ( ! $options['post_id'] ) {
return false;
}
$post_type = get_post_type( $options['post_id']);
if ( 'page' !== $post_type && 'post' !== $post_type && 'resource-item' !== $post_type) {
return false;
}
if ( ! defined( 'ICL_LANGUAGE_CODE' ) ) {
return false;
}
$rule_match = false;
if ( ICL_LANGUAGE_CODE === $rule['value'] ) {
$rule_match = true;
}
if ( '==' == $rule['operator'] && $rule_match) {
$match = true;
} elseif ( '!=' == $rule['operator'] && ! $rule_match ) {
$match = false;
}
return $match;
}
add_filter( 'acf/location/rule_match/post_language', 'cnmd_acf_rule_match_language', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.