Skip to content

Instantly share code, notes, and snippets.

@theMikeD
Created August 20, 2018 12:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save theMikeD/7e448305fad19306787d2da6675a87f7 to your computer and use it in GitHub Desktop.
Save theMikeD/7e448305fad19306787d2da6675a87f7 to your computer and use it in GitHub Desktop.
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