Query custom post type only if it contains another custom post type

I currently have a custom post type named “blog”. On registration, every user gets automatically a post “blog” linked with their user ID.

This custom post type queries another post type named “articles”. Those articles are written by the user and then showed in their “blog” custom post type.

Now, I would like to show a list of X most recent “blog” custom post type but only if they have at least one “article” in it but I can not find any way to do it…

Thank you in advance for your help and have a good day.

Solutions Collecting From Web of "Query custom post type only if it contains another custom post type"

I finally found a workaround for this, here it goes :

I used “get_user” with a “has_custom_post_type” function to query every user with at least one article written and then added the link to their blog CPT by adding “/blog/display_name” in the href.

Here goes the code

<?php
$blog_url = get_bloginfo('home');
$users_number = 0;
$blogusers = get_users('orderby=registered&order=DESC');
    foreach ($blogusers as $user) {
     $cpt_count = has_custom_post_type( $user->ID, 'article' );
  if (!empty($cpt_count) ) {
    $users_number ++;
    if ($users_number <= 5) {
      echo '<li><a href="' . $blog_url . '/blog/' . $user->user_nicename . '">Le blog de ' . $user->display_name . '</a></li>';
    }
  }
}
?>

Thanks to everyone for your help.

I haven’t tested this, but in my head it works perfectly! What we do is put add a pre_get_posts filter in our functions file then get the current user. IF user isn’t registered, drop out. IF the number of user posts isn’t greater than 0, drop out. IF we’re not on the post type archive, drop out. IF all 3 conditions are true, we’ll replace our default blog articles with the users.

function user_posts_filter($query){
    $userID = get_current_user_id();

    if($userID != 0 && count_user_posts($userID) > 0 && is_post_type_archive('blog')){
        $query->set('post_type', 'articles');
        $query->set('author', $userID);
    }
}
add_action('pre_get_posts', 'user_posts_filter');

Hopefully it works for you!