how to get posts by custom post type then display Custom fields?

This might be a good read for you. I’m not sure exactly what you’re looking to do so I’ll lay this out in a simple format.

This query will pull all Posts under the Post Type recipes where the custom field side-dishes exists. You can then loop through and display them how you would like.

$recipes = new WP_Query(
    array(
        'post_type' => 'recipes',
        'posts_per_page' => 8,
        'orderby' => 'rand',
        'post_status' => 'publish',
        'meta_query' => array(
            array(
                'key' => 'side-dishes'
                'compare' => 'EXISTS'
            )
        )
    )
);

This 2nd query will pull all posts under the taxonomy my_taxonomy_name_here which you will need to replace with your taxonomy. It looks for categories with the slug my_category_slug_here which you will need to replace with the category slug. You can replace ‘slug’ with ID and pull it based off that if you’d like.

$recipes = new WP_Query(
    array(
        'post_type' => 'recipes',
        'posts_per_page' => 8,
        'orderby' => 'rand',
        'post_status' => 'publish',
        'tax_query' => array(
            array(
                'taxonomy' => 'my_taxonomy_name_here',
                'field' => 'slug',
                'terms' => 'my_category_slug_here'
            )
        )
    )
);

You can then loop through each post like a normal loop:

<?php if($recipes->have_posts()) : ?>
    <?php while($recipes->have_posts()) : $recipes->the_post(); ?>
        <h1><?php the_title(); ?></h1>
        <?php the_content(); ?>
    <?php endwhile; ?>
<?php endif; wp_reset_query(); ?>

Documentation on WP_Query

Documentation on Meta_Query

Documentation on Tax_Query

Leave a Comment