Archived topic
Show results archive page sorted by CPT
5 replies · Started by Jens on March 22, 2023
I have three CPT (cpt1, cpt2, cpt3) and one custom taxonomy (mytax). The archive page should show results sorted by CPT, e.g.
cpt1
List of results for terms of mytax
cpt2
List of results for terms of mytax
cpt3
List of results for terms of mytax
How does the query function have to be changed so that the "CurrentPostTerm" is evaluated? (The archive template will be created later with GenerateBlocks)
Hi there,
how are you going to display the posts ? Is it using the GB Query Loop block ?
Yes, I am using the GB Query Loop Block. For the display I want to use the TAB block, in which there is a query loop for each post type. The evaluation "Current post terms" does not work. (see the screenshot)
in the function.php I added the following code for the author archives (if that might be important for this problem)
/* Archiv Autor CPT */
add_action( 'pre_get_posts', 'add_cpt_author_archives' );
function add_cpt_author_archives( $query ) {
if ( ! $query->is_main_query() || is_admin() || ! is_author() ) {
return;
}
$query->set( 'post_type', array( 'post', 'anfrage', 'drucksache' ) );
}
Ok, so what you could try is:
1. Add this PHP Snippet:
add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {
$class = 'your-custom-class';
$taxonomy = 'your-taxonomy';
// apply filter if loop class has matching $class
if (
! empty( $attributes['className'] ) &&
strpos( $attributes['className'], $class ) !== false
) {
// get the current tax term
$current_term = get_queried_object();
// merge meta_key my-custom-field into query
return array_merge( $query_args, array(
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $current_term->slug
)
)
) );
}
return $query_args;
}, 10, 2 );
Set the $class to a CSS Class that you will add to the Query Loops grid block -> Advanced CSS Class(es) field.
This is how the filter will target that query loop.
Set $taxonomy to match your custom taxonomy.
2. Add your Query Loop blocks each with the matching CSS Class.
2.1 Set the Parameters to the show the specific post type. DO NOT use the Inherit Query from Template
If the code works it will merge the tax_query into those loops filtering the posts just for the current archive term.
David you are great. It works. Many thanks.
Woo hoo - awesome. Glad to be of help!!