Home › Forums › Feature Requests › Add condition: page parent for custom post types › Reply To: Add condition: page parent for custom post types
This was a super helpful piece of code. I made one small addition which is to allow for an option for “No Parent” i.e. when the current custom post has no parent set. This was literally one line but I also made some tiny cleanups to the code so I’ve included it below.
Thanks again!
function acf_location_rules_types($choices) {
$choices['Custom Post Types']['cpt_parent'] = 'Custom Post Type Parent';
return $choices;
}
add_filter('acf/location/rule_types', 'acf_location_rules_types');
function acf_location_rules_values_cpt_parent($choices) {
$args = array(
'hierarchical' => true,
'_builtin' => false,
'public' => true
);
$hierarchical_posttypes = get_post_types($args);
foreach($hierarchical_posttypes as $hierarchical_posttype) {
if ('acf' !== $hierarchical_posttype) {
$choices[0] = __('No Parent');
$args = array(
'post_type' => $hierarchical_posttype,
'posts_per_page' => -1,
'post_status' => 'publish'
);
$customposts = get_posts($args);
foreach ($customposts as $custompost) {
$choices[$custompost->ID] = $custompost->post_title;
}
}
}
return $choices;
}
add_filter('acf/location/rule_values/cpt_parent', 'acf_location_rules_values_cpt_parent');
function acf_location_rules_match_cpt_parent($match, $rule, $options) {
global $post;
$selected_post = (int) $rule['value'];
if ($post) { // post parent
$post_parent = $post->post_parent;
if ($options['page_parent']) {
$post_parent = $options['page_parent'];
}
if ('==' == $rule['operator']) {
$match = ($post_parent == $selected_post);
} elseif ('!=' == $rule['operator']) {
$match = ($post_parent != $selected_post);
}
}
return $match;
}
add_filter('acf/location/rule_match/cpt_parent', 'acf_location_rules_match_cpt_parent', 10, 3);
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.