Show a Category X’s custom post type on Category X archive page?

I created a custom post type “landing_page” to hold content I want to display on the top of category archive pages.

So for each category, I have one landing_page entry tagged with that category. What do I have to add to the category archive.php template to get it to show that category’s (or custom taxonomy term’s) landing_page content?

query_posts(
    array( 'posts_per_page' => 1,
    'post_type' => landing_page,
    'category' => [[???]] ));

     while (have_posts()) : the_post();
    the_content();
endwhile;
?>

Related posts

Leave a Reply

2 comments

  1. I’d suggest adding something like this to the top of the theme file or wherever you want this content to appear in the archive, category or whatever..

    // Check if it's a category or taxonomy archive
    if( is_category() || is_tax() ) {
        // Grab the queried data, slug, tax, etc..
        $queried = $wp_query->get_queried_object();
        // Check taxonomy and slug are set
        if( isset( $queried->taxonomy ) && isset( $queried->slug ) ) {
            // Look for a landing page post type with a slug that matches the current queried slug
            $landing_page = get_posts( 'name=' . $queried->slug . '&post_type=landing_page&posts_per_page=1&nopaging=1' );
            // If the result wasn't empty
            if( !empty( $landing_page ) ) {
                // Output the title and content using the same filters WP uses in the loop
                echo apply_filters( 'the_title', get_the_title( $landing_page->ID ) );
                echo apply_filters( 'the_content', get_the_content( $landing_page->ID ) );
            }
        }
    }
    

    This will should do what you want without interupting the main category query for the archive.

    Hope that helps.

  2. You can get the current category with

    and since you are using archive.php and not category.php check if its a category first so something like this:

    if (is_category()){
    query_posts(
        array( 'posts_per_page' => 1,
        'post_type' => 'landing_page',
        'category' =>  get_query_var('cat'));
    
         while (have_posts()) : the_post();
            the_content();
         endwhile;
    
    }