jimboobrien
9/20/2017 - 11:15 PM

Practical example of how and why you might want to extend the WP_Query class.

Practical example of how and why you might want to extend the WP_Query class.

<?php

/**
 * Class Video_Query
 */
class Video_Query extends Attachment_Query {

	function __construct( $query = '' ) {
		add_filter( 'posts_where', array( $this, 'posts_where' ) );
		parent::__construct( wp_parse_args( $query ) );
		remove_filter( 'posts_where', array( $this, 'posts_where' ) );
	}

	function posts_where( $where ) {
		/**
		 * @var wpdb $wpdb
		 */
		global $wpdb;
		$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_mime_type LIKE %s", like_escape( 'video/' ) . '%' );
		return $where;
	}

}
<?php

/**
 * Class Image_Query
 */
class Image_Query extends Attachment_Query {

	function __construct( $query = '' ) {
		add_filter( 'posts_where', array( $this, 'posts_where' ) );
		parent::__construct( wp_parse_args( $query ) );
		remove_filter( 'posts_where', array( $this, 'posts_where' ) );
	}

	function posts_where( $where ) {
		/**
		 * @var wpdb $wpdb
		 */
		global $wpdb;
		$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_mime_type LIKE %s", like_escape( 'image/' ) . '%' );
		return $where;
	}

}
<?php

/**
 * Class Document_Query
 */
class Document_Query extends Attachment_Query {

	function __construct( $query = '' ) {
		add_filter( 'posts_where', array( $this, 'posts_where' ) );
		parent::__construct( wp_parse_args( $query ) );
		remove_filter( 'posts_where', array( $this, 'posts_where' ) );
	}

	function posts_where( $where ) {
		/**
		 * @var wpdb $wpdb
		 */
		global $wpdb;
		$where .= $wpdb->prepare( " AND ( {$wpdb->posts}.post_mime_type LIKE %s", like_escape( 'application/' ) . '%' );
		$where .= $wpdb->prepare( " OR {$wpdb->posts}.post_mime_type LIKE %s )", like_escape( 'text/' ) . '%' );
		return $where;
	}

}
<?php

/**
 * Class Audio_Query
 */
class Audio_Query extends Attachment_Query {

	function __construct( $query = '' ) {
		add_filter( 'posts_where', array( $this, 'posts_where' ) );
		parent::__construct( wp_parse_args( $query ) );
		remove_filter( 'posts_where', array( $this, 'posts_where' ) );
	}

	function posts_where( $where ) {
		/**
		 * @var wpdb $wpdb
		 */
		global $wpdb;
		$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_mime_type LIKE %s", like_escape( 'audio/' ) . '%' );
		return $where;
	}

}
<?php

/**
 * Class Attachment_Query
 */
class Attachment_Query extends WP_Query {

	function __construct( $query = '' ) {
		$defaults = array(
			'post_type'      => 'attachment',
			'post_status'    => 'inherit',
			'posts_per_page' => - 1,
			'orderby'        => 'menu_order',
			'order'          => 'ASC',
		);
		parent::__construct( wp_parse_args( $query, $defaults ) );
	}

}