我正在开发一个自定义小部件,它显示来自所选分类法(类别或标记)的帖子。此小部件包含一个文本框,用户输入分类法(类别或标记)的ID以从帖子中排除。此ID可能因小部件而异,因为此小部件的多个实例将出现在同一页面上,不包括不同的类别或标记。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: 将筛选器设置为调用excludeTheID()函数并传入$exclude的包装函数,但返回NULL。
在这个例子中,下面是我试图完成的一个模拟:
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;
}
我不想使用globals来实现这一点,因为每个小部件将在页面上该小部件的每个实例中传递一个唯一的$exclude值。任何指导都将不胜感激:)
谢谢