1

I will query all posts of a custom post type if the visitor is in the assigned custom taxonomy. I can use an array of all my custom post types in the argument list, but I want to do it dynamicly with the informations of the category the visitior is in. Is there a way to get the custom post type name from the current taxonomy?

$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
if ( ! $paged ) {
    $paged = ( get_query_var( 'page' ) ) ? get_query_var( 'page' ) : 1;
}

$posts_per_page = get_option( 'posts_per_page' );

// Get the queried object and sanitize it
$current_page = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() );
// Get the slug
$slug_taxonomy  = @$current_page->taxonomy;

// Check if I'm in a category
if ( isset( $slug_taxonomy ) && ! is_null( $slug_taxonomy ) && ! empty( $slug_taxonomy ) ) {
    $query = new WP_Query( array(
            'posts_per_page' => $posts_per_page,
            'post_type'      => 'i_dont_know',   // How can I get the custom post type?
            'paged'          => $paged,
            'post_status'    => 'publish',
            'orderby'        => 'title',
            'order'          => 'ASC',
            'tax_query'      => array(
                array(
                    'taxonomy' => $current_page->taxonomy,
                    'field'    => 'term_id',
                    'terms'    => $current_page->term_id,
                )
            )
        )
    );
}
0

You can use 'post_type' => 'any' if you are not sure of the post types resulting from other query arguments.

According to documentation that is what happens by default when you use tax_query:

post_type (string / array) - use post types. Retrieves posts by Post Types, default value is 'post'. If 'tax_query' is set for a query, the default value becomes 'any'

WP_Query / Type parameters

Outside of WP_Query context you would probably need to get such information from global $wp_taxonomies array, which track taxonomies and post types they apply to.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.