function custom_filter() {
global $typenow;
global $wp_query;
if ( $typenow == \'invitation_code\' ) { // Your custom post type slug
$plugins = array( \'Searh-By-dealer-role\', \'Searh-By-distributer-role\',\'Used code\',\'availabel code\'); // Options for the filter select field
$current_plugin = \'\';
if( isset( $_GET[\'slug\'] ) ) {
$current_plugin = $_GET[\'slug\']; // Check if option has been selected
} ?>
<select name="slug" id="slug">
<option value="all" <?php selected( \'all\', $current_plugin ); ?>><?php _e( \'All\', \'wisdom-plugin\' ); ?></option>
<?php foreach( $plugins as $key=>$value ) { ?>
<option value="<?php echo esc_attr( $key ); ?>" <?php selected( $key, $current_plugin ); ?>><?php echo esc_attr( $value ); ?></option>
<?php } ?>
</select>
<?php }
}
function custom_filter_data_by_slug( $query ) {
global $pagenow;
global $wpdb;
// Get the post type
$post_type = isset( $_GET[\'post_type\'] ) ? $_GET[\'post_type\'] : \'\';
if ( is_admin() && $pagenow==\'edit.php\' && $post_type == \'invitation_code\' && isset( $_GET[\'slug\'] ) && $_GET[\'slug\'] !=\'all\' ) {
if($_GET[\'slug\'] == "0")//search by dealer
{
$query->query_vars[\'meta_key\'] = \'userrole\';
$query->query_vars[\'meta_value\'] = \'dealer\';
}
elseif($_GET[\'slug\']== "1")//search by distributer
{
$query->query_vars[\'meta_key\'] = \'userrole\';
$query->query_vars[\'meta_value\'] = \'distributors\';
}
elseif($_GET[\'slug\']== "2")//used code
{
$query->query_vars[\'meta_key\'] = \'userlimit\';
$query->query_vars[\'meta_value\'] = \'0\';
}
elseif($_GET[\'slug\']== "3")
{
//add_filter(\'posts_where\',\'data_where\',10,2);
//below code not working
$sql12 = "SELECT * FROM wp_posts WHERE ID IN(SELECT post_id FROM wp_postmeta WHERE meta_key=\'userlimit\' and meta_value > 0)";
$results = $wpdb->get_results($sql12);
return $results;
}
}
}
}
$this->loader->add_action( \'restrict_manage_posts\', $plugin_admin, \'custom_filter\' );
$this->loader->add_filter(\'parse_query\',$plugin_admin,\'custom_filter_data_by_slug\');
使用此挂钩
但是用slug==3编写的代码不起作用。。
SO网友:Krzysiek Dróżdż
为什么要这样做?
parse_query
是一种行为,而不是过滤器。此操作需要$query
(WP_Query
对象),并允许您修改它。
现在,如果slug等于3,请查看您的代码:
$sql12 = "SELECT * FROM wp_posts WHERE ID IN(SELECT post_id FROM wp_postmeta WHERE meta_key=\'userlimit\' and meta_value > 0)";
$results = $wpdb->get_results($sql12);
return $results;
您不需要修改
$query
对象,因此此代码不会影响查询的帖子。
如果我正确理解你的意图,你想得到所有的帖子,其中的meta值userlimit
大于0?在这种情况下,您必须修改$query
这样做:
elseif($_GET[\'slug\']== "3")
{
$query->set( \'meta_key\', \'userlimit\' );
$query->set( \'meta_value_num\', 0 );
$query->set( \'meta_compare\', \'>\' );
}
另外,您不应该修改
query_vars
直接用于其他情况。改用上面代码中的setter函数。