简体   繁体   中英

Custom filter function not working with Custom post type

I have custom post type "soto_property". I have made a custom filter to filter post listing according to used meta data named "operations". Here is my code-

<?php
add_filter( 'parse_query', 'soto_posts_filter' );
add_action( 'restrict_manage_posts', 'soto_posts_filter_restrict_manage_posts' );

function soto_posts_filter( $query )
{
    global $pagenow;
    if( is_admin() AND $query->query['post_type'] == 'soto_property' ) {
        $qv = &$query->query_vars;
        $qv['meta_query'] = array();

        if( !empty( $_GET['operations'] ) ) {
          $qv['meta_query'][] = array(
            'field' => 'operations',
            'value' => $_GET['operations'],
            'compare' => 'LIKE',
          );
        }

    }
}

function soto_posts_filter_restrict_manage_posts()
{
    global $wpdb;
    if($_GET['post_type']=='soto_property')
    {
        $sql = 'SELECT DISTINCT meta_key FROM '.$wpdb->postmeta.' where meta_key="operations" ORDER BY 1';
        $fields = $wpdb->get_results($sql, ARRAY_N);

 ?>
<select name="operations" id="filter-operations" class="custom-filter" style="display:none; width: 15%;" >
        <option value=""></option>
        <option value="2" <?php echo $_GET['operations']==2?"selected='selected'":'' ?>>Rent</option>
        <option value="1" <?php echo $_GET['operations']==1?"selected='selected'":'' ?>>Sale</option>
      </select>
<?php
    }
}

But my post are not filtering according to meta data "operations". This meta data is stored in wp_postmeta table in DB with meta_key=operation and meta_value=1 or meta_value=2 .

Can anyone help me.

Multiple things are wrong with your code:

  1. You should never use values you get from a user ( $_GET , $_POST or $_REQUEST ) without sanitizing them. You should read this: Validating Sanitizing and Escaping User Data .
  2. Your Select statement in the function soto_posts_filter_restrict_manage_posts is useless as you do not do anything with it. Also, your <select> code suggests that only one value can be used so why use DISTINCT ? Also, Shouldn't that statement link to the post ID ?

This is surely why you don't get the results you are expecting. I would suggest you add some var_dump here and there and validate each steps in your process to make sure you have the expected outcome all the way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM