I am trying to use ajax to filter by category, through my custom posts, but it doesn't seem to work for custom posts.
I have created a custom taxonomy called 'image_category'.
I think I'm on the right lines:
$category = $_POST['category'];
$args = array(
'post_type' => 'image',
'posts_per_page' => -1,
'tax_query' => array(
array( 'taxonomy' => 'image_category',
'field' => 'term_id',
),
);
if(isset($category)) {
$args[2][1] = array($category);
}
$query = new WP_Query($args);
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
echo '<div class="col-md-3">hi</div>';
endwhile;
endif;
Here's how im adding my image_category custom post type:
function image_category() {
$labels = array(
'name' => _x( 'Image Categories', 'Taxonomy General Name', 'text_domain' ),
'singular_name' => _x( 'Image Category', 'Taxonomy Singular Name', 'text_domain' ),
'menu_name' => __( 'Image Category', 'text_domain' ),
'all_items' => __( 'All categories', 'text_domain' ),
'parent_item' => __( 'Parent Categories', 'text_domain' ),
'parent_item_colon' => __( 'Parent Category:', 'text_domain' ),
'new_item_name' => __( 'New Category Name', 'text_domain' ),
'add_new_item' => __( 'Add New Category', 'text_domain' ),
'edit_item' => __( 'Edit Category', 'text_domain' ),
'update_item' => __( 'Update Category', 'text_domain' ),
'view_item' => __( 'View Category', 'text_domain' ),
'separate_items_with_commas' => __( 'Separate categories with commas', 'text_domain' ),
'add_or_remove_items' => __( 'Add or remove categories', 'text_domain' ),
'choose_from_most_used' => __( 'Choose from the most used', 'text_domain' ),
'popular_items' => __( 'Popular Categories', 'text_domain' ),
'search_items' => __( 'Search Categories', 'text_domain' ),
'not_found' => __( 'Not Found', 'text_domain' ),
'no_terms' => __( 'No categories', 'text_domain' ),
'items_list' => __( 'Categories list', 'text_domain' ),
'items_list_navigation' => __( 'Categories list navigation', 'text_domain' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'image_category', array( 'image' ), $args );
}
add_action( 'init', 'image_category', 0 );
$args = array(
'post_type' => 'image',
'posts_per_page' => -1,
'tax_query' => array(
array( 'taxonomy' => 'image_category',
'field' => 'term_id',
),
),
);
if(isset($category)) {
$args['tax_query'][0]['terms'] = array($category);
}