Skip to content

Instantly share code, notes, and snippets.

@jimboobrien
Forked from wpscholar/attachment-query.php
Created September 20, 2017 23:15
Show Gist options
  • Save jimboobrien/1fbdd8a36f79a680b98413ef053d6def to your computer and use it in GitHub Desktop.
Save jimboobrien/1fbdd8a36f79a680b98413ef053d6def to your computer and use it in GitHub Desktop.
Practical example of how and why you might want to extend the WP_Query class.
<?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 ) );
}
}
<?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 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 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 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment