exclude custom post type by meta key in wp_query

If you don’t use any other meta data, just add the following to your $args: ‘meta_key’ => ‘sold’, ‘meta_value’ => true, // or whatever it is you’re using here ‘meta_compare’ => ‘!=’, Otherwise, use a WP_Meta_Query: ‘meta_query’ => array( array( ‘key’ => ‘sold’, ‘value’ => true, // or whatever it is you’re using here ‘compare’ … Read more

How to Display Post View Count

Add this to single.php, and make sure you paste in inside the loop. <?php setPostViews(get_the_ID()); ?> Lastly, to display the number of views a post has, just add this where you want it to be displayed: <?php echo getPostViews(get_the_ID()); ?> . <?php // function to display number of posts. function getPostViews($postID){ $count_key = ‘post_views_count’; $count … Read more

If No Search Results, Show Posts from Alternate Search Query

I’ve never seen it done before but the logic of the PHP IF/ELSE should mean you could simply plug a new query in after the ELSE: if ( have_posts() ) : while ( have_posts() ) : the_post(); get_template_part ( ‘templates/post’, ‘main’ ); endwhile; else: $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : … Read more

get_the_foo() in the loop – does it perform another query?

Query results for posts, terms, and metadata get placed in cache. If a function is called that accesses data from previously queried objects within the same request (or you’re using a persistent cache mechanism that maintains data across requests), it will not trigger another query and will instead fetch the data from cache.

Sort by meta key on archive page

Use pre_get_posts to alter the main query before it is run. The action runs on every query, use the Conditional Tags to target specific queries. function wpd_sort_by_meta( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $query->set( ‘meta_key’, ‘your_meta_key’ ); $query->set( ‘orderby’, ‘meta_value_num’ ); } } add_action( ‘pre_get_posts’, ‘wpd_sort_by_meta’ );