Link from page to category posts

Instead of hard-coding the pages, categories and sidebars in your template file(s) you could consider registering a custom metabox to store the category relation (i.e. the category term ID) in the page post meta. This way you could make the sidebar handling dynamic.

The first step would be to register, render and handle the saving of a custom metabox. There are decent user-submitted examples on the add_meta_box() documentation page, which you can check. There are also plenty of tutorials in the web and answers here in WPSE regarding metaboxes.

Instead of using the generic add_meta_boxes and save_post hooks I usually use the post type specific ones, add_meta_boxes_{$post_type} and save_post_{$post->post_type}, for a cleaner result.

For rendering a category select within the metabox you can use for example wp_dropdown_categories().

As a sidenote, add_meta_box() could be considered the “traditional” way of doing things. If you’re feeling adventurous, another options is to use a combination of PHP and JS to do the meta data handling with the block editor.

Once you got the data saving covered the second step is to retrieve the saved category ID and render the sidebar content. In essence it is a combination of get_post_meta() and get_term_by().

Here’s a simple example.

// Helpers in functions.php
function my_page_category_term_id(int $post_id): int {
    $term_id = get_post_meta($post_id, 'my_metakey_for_category_term_id', true);

    return $term_id && is_numeric($term_id) ? (int) $term_id : 0;
}

function my_page_category_term(int $post_id): ?WP_Term {
    $term_id = my_page_category_term_id($post_id);

    return $term_id ? get_term_by('term_id', $term_id, 'category') : null;
}

function my_page_category_link(int $post_id): string {
    $term = my_page_category_term($post_id);
    if (! $term) {
        return '';
    }

    return sprintf(
        '<a href="%s">View %s posts</a>',
        esc_url(get_term_link($term)),
        esc_html($term->name)
    );
}

// E.g. in page.php template
$category_link = my_page_category_link(get_the_ID());
if ($category_link) {
    printf(
        '<aside class="sidebar-float">
            <h3>%s</h3>
        </aside>',
        $category_link
    );
}

techhipbettruvabetnorabahisbahis forumutaraftarium24edueduedueduedusedusedueduseduedus