Get related custom post by specifics custom post ID

The question:

I created two custom posts, one is formations and the other is Technologie.
The relation between both is one formation have one or many technologies.

After that, i have created a form where i select one to three technologies.
I know that to display the list of custom post type is like this :


$args = array(
        //'post__in' => array(8136),
        'post_type' => 'categories',
        'posts_per_page' => 20
    );

    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
        print '<strong>' . the_title().'</strong> <br>';
        //the_excerpt();
    endwhile;

    wp_reset_postdata();

So my question is how to display this list only for the custom post id ‘1234’ ?
PS : the custom post ‘1234’ have multiple technologie and not all !

Thanks!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

I do it with that but i don’t think this is so optimized!

function list_formation(){
$args = array(,

    'post_type' => 'categories',
    'posts_per_page' => 20,
);

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
    
    $formations = get_posts(array(
        'post_type' => 'formations',
        'post__in' => array(16061),
        'meta_query' => array(
            array(
                'key' => 'categories', // name of custom field
                'value' => '"' . get_the_ID() . '"', 
                'compare' => 'LIKE'
            )
        )
    ));
   
    if($formations){

        foreach ($formations as $categorie){
           // $list = get_field('formations', $formation->ID);
           // list of categorie  with ID  formation
            echo   the_title()  . '</br>';

        }

    }
endwhile;

wp_reset_postdata();

}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment