How to Display Content from Search URLs on Permanent URLs in WordPress?

If you have registered a custom post type and have added a custom template for it to your theme, then you could do something like this.

Add a helper function to functions.php that creates a custom query to find posts matching the topic slug. Using a helper keeps the template file a little cleaner.

// functions.php
function wpse_418573_search_posts_by_topic(string $topic, int $paged = 1) : WP_Query {
    return new WP_Query([
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => get_option( 'posts_per_page' ),
        's' => $topic,
        'paged' => $paged,
    ]);
}

In your custom template have the default Loop handle the rendering of the CPT’s content. Execute the search query by passing the CPT’s slug as a parameter and loop the found posts to display the search results.

// single-topic.php
<article class="topic">
    <section class="topic__description">
        <?php while ( have_posts() ): the_post(); ?>
            <h1 class="topic__title"><?php the_title(); ?></h1>
            <?php the_content(); ?>
        <?php endwhile; ?>
    </section>

    <?php
        global $post;
        $search = wpse_418573_search_posts_by_topic($post->post_name, get_query_var( 'paged', 1 ));

        if ($search->have_posts()): ?>
        <section class="topic__search">
            <?php while ( $search->have_posts() ): $search->the_post(); ?>
                <article class="topic__post entry">
                    <h2 class="entry__title"><?php the_title(); ?></h2>
                    <?php the_content(); ?>
                </article>
            <?php endwhile; ?>
        </section>
    <?php endif;?>
</article>

tech