I’m a bit confused as to why this isn’t working – although it must be said I’m not that sure what apply_filters()
and add_filter
are doing, so any general tips would be great too!
I want a query that brings up the five earlier posts on a single post page. I am sending the current post’s date off, and want to apply a filter that filters out posts earlier than this.
function sw_filter_posts_before( $where = '', $date) {
$where .= " AND post_date < '" . $date . "'";
return $where;
}
How do I correctly apply this? Simply using add_filter or apply_filter before instantiating a new WP_Query object doesn’t seem to work correctly.
Thanks in advance!
Edit: To go into things further, I would like to understand how to pass a variable into the filter, as I can’t get $date to pass from another function.
Here is said other function (it is an ajax call within wordpress, hence I start by getting the post ID for the current page through a $_POST variable):
function create_more_videos_sidebar() {
$id = $_POST['theID'];
$args = array( 'post_type' => 'videos',
'posts_per_page' => 1,
'p' => $id
);
$wp_query = new WP_Query($args);
while ($wp_query->have_posts()) : $wp_query->the_post(); $do_not_duplicate = $post->ID;
$date = get_the_date('Y-m-d');
endwhile;
$args = array( 'post_type' => 'videos',
'posts_per_page' => 5
);
add_filter( 'posts_where', 'sw_filter_videos_before' ); //don't know how to pass $date
$wp_query = new WP_Query($args);
remove_filter( 'posts_where', 'sw_filter_videos_before' );
//do loop stuff
$response = json_encode( array( 'result' => $result ) );
header( "Content-Type: application/json" );
echo $response;
exit;
}
What are you attempting to filter? I’ll assume you’re trying to add a filter to a filter hook called
posts_before
. In which case, you need to add your filter to this hook, viaadd_filter()
:Note that I changed your function name.
filter_posts_before()
is far too generic of a function name, and very likely to cause a function-naming collision.EDIT
And just to clarify:
apply_filters()
is the filter hook location, is called by core code, and is used to apply any filters that are added to the queue by Themes/Plugins (and core).add_filter()
is called by Themes/Plugins (and core), and is used to add filters to the queue to be applied to the hook by core.EDIT 2
Based on your comment above, the hook is
posts_where
. So, let’s take a crack at re-building your callback function: