Support

Account

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

  • I fixed the rule_match function operator for != matches. It was set to

    elseif ($rule['operator'] != "!="){

    Instead of

    elseif ($rule['operator'] == "!="){

    This now works for me:

    /*
    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,
    		'public' => true
    	);
        $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
    	if($post) {
      	$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;
    
    }