-
-
Save wolffe/a3a4905ecc658e14694cc2c220615271 to your computer and use it in GitHub Desktop.
WordPress: Thoughts on Filtering by Time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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