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

I am the Most Stupid Person asked

It is hard explain what I am trying to build. So I will try to explain it via example.

Custom Post Type : Mobile

Assume that there are 4 mobile posts..

  1. Nokia 6
  2. Samsung S 7
  3. Huawei P 10
  4. Apple iPhone 7

Custom Post Type : Compare

Following compare posts should be auto created..

  1. Nokia 6 vs Samsung S 7
  2. Nokia 6 vs Huawei P 10
  3. Nokia 6 vs Apple iPhone 7
  4. Samsung S 7 vs Huawei P 10
  5. Samsung S 7 vs Apple iPhone 7
  6. Huawei P 10 vs Apple iPhone 7

Every compare posts should be have two custom fields like mobile1 and mobile2 and it includes the post id of mobile post type.

Is it possible to build this type of site with WordPress?

I have some ideas build it using cron… I mean reading Mobile Posts and create compare posts…. But seems like it takes too much time… Is there any easy way?


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:

We want to add support for:

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).

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.

$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; ?>
Share This
Posted in: