I am working on a custom widget which displays posts from a selected taxonomy (category or tag). This widget contains a textbox which the user enters an ID of a taxonomy (category or tag) to exclude from posts. This ID can vary from widget to widget as multiple instances of this widget will appear on the same page excluding different category or tags. I am looking for a way to pass the $exclude
variable from widget()
to the excludeTheID()
function which is located in functions.php
What I have tried: Setting the filter to a wrapper function that calls the excludeTheID() function and passes in $exclude, but NULL is returned.
For the sake of this example, here is a mock of what I am trying to accomplish:
class testWidget extends WP_Widget {
public function __construct() {
// .......
}
public function form( $instance ) {
// This widget contains a text field ($exclude) that the user is to enter a taxonomy ID into.
}
public function update( $new_instance, $old_instance ) {
// .......
}
public function widget( $args, $instance ) {
// this value represents what the user would enter in the textbox of the widget
$exclude = 15;
// .......
// This function does the work
add_filter( "posts_where", "excludeTheID" );
// Create a new query
$loop = new WP_Query();
// Remove the filter
remove_filter( "posts_where", "excludeTheID" );
}
}
// FROM Functions.php:
// External function responsible for generating the new WHERE clause using the value in $exclude.
function excludeTheID( $where, $exclude )
{
$clauses = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $exclude,
'operator' => 'NOT IN',
),
);
// Access the global WordPress DB variable
global $wpdb;
// Create the new WHERE Query string using the above arrays
$tax_sql = get_tax_sql( $clauses, $wpdb->posts, 'ID' );
$where .= $tax_sql['where'];
return $where;
}
I do not want to use globals to accomplish this as each widget will be passing a unique value for $exclude in every instance of that widget on a page.
Any guidance would be greatly appreciated :)
Thanks.