Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Last active April 5, 2020 08:24
Show Gist options
  • Save LeanSeverino1022/6ce1e00710a8510f49527a6b4367a9eb to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/6ce1e00710a8510f49527a6b4367a9eb to your computer and use it in GitHub Desktop.
[WP_Query Arguments] #wordpress

For just quick reference, check the snippets below. If want to learn check out these resources:

Customizing the WordPress Query – using pre_get_posts for the main query

/**
 * Exclude Category from Blog
 * 
 * @author Bill Erickson
 * @link https://www.billerickson.net/customize-the-wordpress-query/
 * @param object $query data
 *
 */
function be_exclude_category_from_blog( $query ) {
	
	if( $query->is_main_query() && ! is_admin() && $query->is_home() ) {
		$query->set( 'cat', '-4' );
	}
}
add_action( 'pre_get_posts', 'be_exclude_category_from_blog' );

NOTES: The correct way to use the set method (which is part of the WP_Query class) is to pass 2 arguments - a query parameter key and a query parameter value. EX $query->set( 'posts_per_page', '18' );

To know what arguments to pass...

real world example

//if post type archive is 'event'. show events with dates larger than today's date / show future events only

 function university_adjust_queries($query) {

        if (!is_admin() AND is_post_type_archive('event') AND $query->is_main_query()) {

            $today = date('Ymd');
            $query->set('meta_key', 'event_date');
            $query->set('orderby','meta_value_num');
            $query->set('order','ASC');
            $query->set('meta_query', array(
                array(
                    'key' => 'event_date',
                    'compare' => '>=',
                    'value' => $today,
                    'type' => 'numeric'
                )
            ));
        }
    }

    add_action('pre_get_posts', 'university_adjust_queries');

Custom WordPress Queries – For generating custom queries

When you code WP_Query in your themes or plugins, you need to include four main elements:

  • the arguments for the query, using parameters which will be covered in this tutorial
  • the query itself
  • the loop
  • finishing off: closing if and while tags and resetting post data

In practice this will look something like the following:

<?php
 
$args = array(
    // Arguments for your query.
);
 
// Custom query.
$query = new WP_Query( $args );
 
// Check that we have query results.
if ( $query->have_posts() ) {
 
    // Start looping over the query results.
    while ( $query->have_posts() ) {
 
        $query->the_post();
 
        // Contents of the queried post results go here.
 
    }
 
}
 
// Restore original post data.
wp_reset_postdata();
 
?>
$args = array(
    // Arguments for your query.
);

The arguments are what tells WordPress what data to fetch from the database. the arguments are contained in an array.

$the_query = new WP_Query( $args )

To know what arguments to pass in the array...

real word sample

<?php

$loop  = new WP_Query( array(
	'posts_per_page' => 20,
	'orderby'        => 'meta_value_num',
	'order'          => 'DESC',
	'meta_key'       => 'shared_counts_total',
) );
if ( $loop->have_posts() ) {
	$posts .= '<ol>';
	while ( $loop->have_posts() ) {
		$loop->the_post();
		$shares = get_post_meta( get_the_ID(), 'shared_counts_total', true );
		$posts .= sprintf( '<li><a href="%s">%s (%s %s)</a></li>',
			esc_url( get_permalink() ),
			get_the_title(),
			esc_html( $shares ),
			esc_html( _n( 'share', 'shares', $shares, 'shared-counts' ) )
		);
	}
	$posts .= '</ol>';
}
wp_reset_postdata();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment