Support

Account

Home Forums Backend Issues (wp-admin) Filtering relationship field depending on selected Post Type

Solved

Filtering relationship field depending on selected Post Type

  • Hi all,

    Is it possible to filter only one of the post types available in a relationship?

    For example, I have a field that lists both events and posts, but I only want to filter the events using a meta_query.

    Something along the lines of

    add_filter('acf/fields/relationship/query/name=main_feature', function($options, $field, $post_id) {
        $options['post_status'] = array('publish');
        if($field['post_type'] === 'event') {
            $options['meta_query'] = array(
                array(
                    'key' => 'end',
                    'compare' => '>=',
                    'value' =>  date('Y-m-d H:i:s'),
                    'type' => 'DATETIME'
                )
            );
        }
        return $options;
    }, 10, 3);
  • Assuming that your posts do not have the field end

    
    add_filter('acf/fields/relationship/query/name=main_feature', function($options, $field, $post_id) {
        $options['post_status'] = array('publish');
            $options['meta_query'] = array(
                'relation' => 'OR',
                array(
                    'key' => 'end',
                    'compare' => '>=',
                    'value' =>  date('Y-m-d H:i:s'),
                    'type' => 'DATETIME'
                ),
                array(
                    'key' => 'end',
                    'compare' => 'NOT EXISTS'
                )
            );
        return $options;
    }, 10, 3);
    
  • Like a charm! Thanks John

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Filtering relationship field depending on selected Post Type’ is closed to new replies.