Support

Account

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);