Support

Account

Home Forums Feature Requests Add condition: page parent for custom post types Reply To: Add condition: page parent for custom post types

  • The code above was missing the $match rules so although you could see the correct pages in the location rules, the ACF rule wouldn’t get applied to anything. This should work:

    /*
    * ACF post parent
    */
    
    add_filter('acf/location/rule_types', 'acf_location_rules_types');
    function acf_location_rules_types( $choices )
    {
        $choices['Custom Post types']['cpt_parent'] = 'Custom post type parent';
     
        return $choices;
    }
    add_filter('acf/location/rule_values/cpt_parent', 'acf_location_rules_values_cpt_parent');
    function acf_location_rules_values_cpt_parent( $choices )
    {
    	$args = array(
    		'hierarchical' => true,
    		'_builtin' => false
    	);
        $posttypes = get_post_types( $args );
     
        if( $posttypes )
        {
            foreach( $posttypes as $posttype ):
            
    			if( $posttype != 'acf' ):
    				$args = array(
    				'post_type' => $posttype,
    				'posts_per_page' => -1,
    				'post_status' => 'publish'
    				);
    				$customposts = get_posts( $args );  
    				if ( $customposts  ) {
    					foreach( $customposts as $custompost ){
    						$choices[ $custompost->ID] = $custompost->post_title;
    					}
    				}
    			endif;
    		endforeach;
    	}
     
        return $choices;
    }
    
    //MATCH THE RULE
    add_filter('acf/location/rule_match/cpt_parent', 'acf_location_rules_match_cpt_parent', 10, 3);
    function acf_location_rules_match_cpt_parent( $match, $rule, $options )
    {
    	
    	global $post;
    	$selected_post = (int) $rule['value'];
    
    	// 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;
    }