Dynamically Create Custom Post Type According to Relationship Another Custom Post Type

I would have the goal of appending the other device onto any existing permalink so you can compare one to the other, and vice versa. That’s fully dynamic/automatic; i.e., requires no manual entry and no CRON job, etc.

So let’s pretend you have:
https://example.com/mobile-device-a/

We want to add support for:
https://example.com/mobile-device-a/compare/mobile-device-b/
https://example.com/mobile-device-b/compare/mobile-device-a/


See: add_rewrite_endpoint()

Create a new endpoint so you can visit any mobile post type that already exists and simply add .../compare/mobile-device-b/ onto the end of it, which can be used to transform the display of that particular post on-the-fly; i.e., you will look for the /compare/mobile-device-b/ endpoint in your template(s).

<?php
add_action( 'init', function() {
    add_rewrite_endpoint( 'compare', EP_PERMALINK );
} ); // This syntax requires PHP 5.4+.

See also: WordPress Endpoint Introduction


Next, add some custom code in your template’s single.php file, which will be responsible for detecting the use of the /compare/mobile-device-b/ endpoint, and adjust the output accordingly.

I’ll provide a quick example, showing how to run a sub-query and pull the content for the other device by slug. However, you’ll no doubt need to customize this further and blend it into your theme and overall design goals.

<?php
$compare = get_query_var( 'compare' );
$compare = sanitize_key( $compare );

if ( is_singular( 'mobile' ) && $compare ) :
    $sub_query = new WP_Query( array(
        'post_type'      => 'mobile',
        'name'           => $compare,
        'posts_per_page' => 1,
    ) );
?>
    <?php the_content(); // Of mobile-device-a. ?>

    <?php if ( $sub_query->have_posts() ) : ?>
        <?php while ( $sub_query->have_posts() ) : $sub_query->the_post(); ?>

            <?php the_content(); // Of mobile-device-b. ?>

        <?php endwhile; ?>
    <?php endif; ?>

    <?php wp_reset_postdata(); ?>

<?php endif; ?>