Search code examples
custom-fieldswordpresscustom-pages

How to Display Wordpress Posts by Custom Field


I am trying to create a page that displays all my wordpress posts that contain a certain custom field. I assumed that the best way to do this is to create a "custom page template" and use a new WP_query to list the posts in question. I created a new "page" and applied the new "page template" with my new WP_query, however no posts show up on the page. Can anyone tell me why this custom page template does not correctly list the posts in question? Any help is much appreciated!

<?php

/**

 * Template Name: Recommended Incentives


 *

 * @package WordPress

 * @subpackage Twenty_Fourteen

 * @since Twenty Fourteen 1.0

 */



get_header(); ?>



<div id="main-content" class="main-content">







    <div id="primary" class="content-area">

        <div id="content" class="site-content" role="main">


            <?php 

// args
$args = array(

    'meta_key' => 'Incentive ID',
    'meta_value' => '20'
);

// get results
$the_query = new WP_Query( $args );

// The Loop
?>
<?php if( $the_query->have_posts() ): ?>
    <ul>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
    <?php endwhile; ?>
    </ul>
<?php endif; ?>

<?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>


        </div><!-- #content -->

    </div><!-- #primary -->

</div><!-- #main-content -->



<?php

get_sidebar();

get_footer();

Solution

  • Thanks Andy, My code worked when I specified the post type in the $args variable. The code I used is

    'meta_key' => 'Incentive ID',
        'meta_value' => array(20,21),
        'orderby' => 'meta_value_num',
       'order' => 'ASC',
        'post_type' => 'incentives'