Loop with Dynamic Categories

The code below enables categories for pages. An example page template is provided which loops through the categories assigned to the page and displays the posts for each category.

If you want to limit the user to selecting only one category, you can use a solution such as Taxonomy Single Term.

Associate the category taxonomy with the page post type:

function wpse_page_category() {
    register_taxonomy_for_object_type( 'category', 'page' );    
}
add_action( 'init', 'wpse_page_category', 999  );

Example bare bones page template (template-page-categories.php):

<?php
/**
 * Template Name: Page Categories
 *
 */

get_header(); ?>


<?php 
    // Standard loop for page content
    if ( have_posts() ) {
        while ( have_posts() ) {
            the_post();
            the_title( '<h1>', '</h1>' );
            the_content();
        }
    }


    // Get the category assigned to this page and list the posts in this category.
    // This code works when multiple categories have been assigned to the page.
    $page_categories = get_the_terms( get_the_ID(), 'category' );
    if ( $page_categories && ! is_wp_error( $page_categories ) ) {

        foreach ( $page_categories as $page_category ) {

            $posts_query = new WP_Query( [
                'post_type' => 'post',
                'cat' => $page_category->term_id,
            ] );


            if ( $posts_query->have_posts() ) {
                echo '<h2> Posts from the <em>' . esc_html( $page_category->name ) . '</em> category:</h2>';
                while ( $posts_query->have_posts() ) {
                    $posts_query->the_post();
                    the_title( '<h3>', '</h3>' );
                    //the_content();
                }
                echo '<hr>';
            }
        }
    }

?>

Leave a Comment