Skip to content

Instantly share code, notes, and snippets.

@wolffe
Forked from eteubert/anonymous.php
Created March 21, 2017 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolffe/a3a4905ecc658e14694cc2c220615271 to your computer and use it in GitHub Desktop.
Save wolffe/a3a4905ecc658e14694cc2c220615271 to your computer and use it in GitHub Desktop.
WordPress: Thoughts on Filtering by Time
<?php
$age_filter = function ( $where = '' ) use ( $options ) {
$where .= " AND post_date > '" . date( 'Y-m-d', strtotime( '-' . $options[ 'max_post_age' ] ) ) . "'";
return $where;
};
add_filter( 'posts_where', $age_filter );
$query = new WP_Query( $args );
remove_filter( 'posts_where', $age_filter );
<?php
function filter_where( $where = '' ) {
$where .= " AND post_date > '" . date( 'Y-m-d', strtotime( '-30 days' ) ) . "'";
return $where;
}
add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $args );
remove_filter( 'posts_where', 'filter_where' );
<?php
/**
* Wrap a block of code in a WordPress filter.
*
* That filter is added before the block is called and removed after it.
*
* @param string $filter_tag WordPress filter tag.
* @param function $filter_func The filter function.
* @param function $block The code to be wrapped in the filter.
* @return mixed Result of the called block.
*/
function with_filter( $filter_tag, $filter_func, $block ) {
add_filter( $filter_tag, $filter_func );
$result = call_user_func( $block );
remove_filter( $filter_tag, $filter_func );
return $result;
}
$query = with_filter(
'posts_where',
function ( $where = '' ) use ( $options ) {
$where .= " AND post_date > '" . date( 'Y-m-d', strtotime( '-' . $options[ 'max_post_age' ] ) ) . "'";
return $where;
}, function () use ( $args ) {
return new \WP_Query( $args );
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment