Home Forums General Issues WP archive with custom field filter by taxonomy field


WP archive with custom field filter by taxonomy field

  • Hi, community!

    I’m using Theme v.7 & ACF 4.3.9.
    I have custom post type “Events” and added some custom fields using ACF.

    I have 2 custom fields specified for cpt Events:

      event_city — field type Post Object

    • event_category — field type Taxonomy

    Аnd now, I’m creating custom post type archive with filter by custom fields using this manual — Creating a WP archive with custom field filter

    I’m successfully created filtering by event_city. All works great.
    But when I try to create filter by event_category — query result is always empty( fires if !have_posts(): ).

    my pre_get_posts function looks like:

    add_action('pre_get_posts', 'my_pre_get_posts');
    function my_pre_get_posts( $query ){
    	if( is_admin() ){
    	if( !$query->is_main_query() ){
    	$meta_query = $query->get('meta_query');
            if( !empty($_GET['event_category']) )
    	    $event_category = explode(',', $_GET['event_category']);
    	    $meta_query[] = array(
                    'key'		=> 'event_category',
                    'value'		=> $event_category,
                    'compare'	=> 'IN',
    	// update the meta query args
    	$query->set('meta_query', $meta_query);

    I’m tried to modify tax_query instead of meta_query in pre_get_posts. But it’s almost breaks archive template and I went back to the meta_query.

    When debugging this issue i’m using this links:
    http://wp.local/events/?event_city=12 — work’s great
    http://wp.local/events/?event_category=5 — don’t work’s

    Also, I’m tried to modify query args just in archive template file. And all works fine — posts filtered by event_category. My events archive template file then looked:

    <?php if (!have_posts()) : ?>
      <div class="alert alert-warning">
        <?php _e('Sorry, no results were found.', 'roots'); ?>
      <?php get_search_form(); ?>
    <?php endif; ?>
    	$args = array(
    		'post_type' => 'events',
    		'meta_query' => array(
    		            'key' => 'event_category',
    		            'value' => array(8),
    		            'compare' => 'IN'
    <?php query_posts($args); ?>
    <?php while (have_posts()) : the_post(); ?>
      <?php get_template_part('templates/content', get_post_format()); ?>
    <?php endwhile; ?>

    Need help with that issue. I understand — that taxonomy terms have their archive templates. But i need to do it on main custom post type archive page with filtering.

Viewing 1 post (of 1 total)

The topic ‘WP archive with custom field filter by taxonomy field’ is closed to new replies.