2

I've a custom post type with some custom meta box. I want to filter my custom post type posts using custom meta value. I've written the code below. But it return no post found. Can anyone tell me where I did wrong? Here is the codes.

<?php

add_action('restrict_manage_posts','restrict_listings_by_metavalue');
function restrict_listings_by_metavalue() {
    global $typenow;
    global $wp_query;
    if ($typenow=='jspp_std') {
        echo '<input type="text" name="adate" id="adate" placeholder="Enter Admission date" />';
    }
}
add_filter('parse_query','jspp_custom_meta_query');
function jspp_custom_meta_query($query) {
    global $typenow;
    global $pagenow;

    if( $pagenow == 'edit.php' && $typenow == 'jspp_std' && isset($_GET['adate']) )
    {

        $query->query_vars['meta_key'] = '_jspp_sp_sid';
        $query->query_vars['meta_value'] = $_GET['adate'];
        $query->query_vars['meta_compare'] = '=';

    }
}

?>

Screenshot of result it return.Thanks in advance.

enter image description here

2 Answers 2

1

I ave faced the same issue when I was trying to filter custom-post-type with custom-field
but I have resolved this issue in the following steps.
Converted custom-field name from writer to _writer
and then I have updated following code inside callback function of parse_query hook that I can add custom-field meta_query like

$query->set( 'meta_query', array(
    array(
          'key'     => '_writer',
           'compare' => '=',
           'value'   => $_GET['_writer'],
           'type'    => 'numeric',
      )
) );         

This Above Solution Worked for me.
Documentation https://developer.wordpress.org/reference/hooks/pre_get_posts/
Helpful Links https://developer.wordpress.org/reference/hooks/pre_get_posts/#comment-2571
https://stackoverflow.com/questions/47869905/how-can-i-filter-records-in-custom-post-type-list-in-admin-based-on-user-id-that

0

UPDATE: I figured it out! My fix was I could only filter by Columns which were specified to be sortable. Hopefully this helps someone else!

So for my custom post type, I had only a single column set as sortable. I added the column I was trying to Filter by and boom! The filtering worked!

// Make Custom Post Type Custom Columns Sortable
function cpt_custom_columns_sortable( $columns ) {

    // Add our columns to $columns array
    $columns['item_number'] = 'item_number';
    $columns['coat_school'] = 'coat_school'; 

    return $columns;
} add_filter( 'manage_edit-your-custom-post-type-slug_sortable_columns', 'cpt_custom_columns_sortable' );

Thus, including the above, my entire code solution looks like this:

/**
 * Add School as a Filter Drop Menu
 * Create the dropdown
 * Change POST_TYPE to the name of your custom post type
 */
function ssp_school_custom_column_filter() {

    // Only show the filter drop menu to Admins/SSP Users
    $user = wp_get_current_user();
    $role = ( array ) $user->roles;
    if ( in_array("administrator", $role ) ||  in_array("ssp_user", $role ) ) {
        // do nothing - this is backwards... shouldn't need to do it this way.
    } else { return; }

    $type = 'post'; // Set default to be overridden

    // Check for the Post Type
    if (isset($_GET['post_type'])) {
        $type = $_GET['post_type'];
    }

    $types = array( 'member' );
    $types_uniforms = ssp_get_uniform_items_names_by_size('all');   
    $types = array_merge( $types , $types_uniforms );

    // Only add filter to certain post types
    if ( in_array( $type , $types) ) {

        // Get all Schools
        $schools_args = array(
            'post_type' => 'schools',
            'post_status'   => 'publish',
            'posts_per_page'=> '-1',
            'orderby'   => 'title',
            'order'     => 'ASC',
            'fields'    => 'ids',
        );
        $schools = new WP_Query( $schools_args );

        // Populate the List of Schools
        if ( $schools->have_posts() ) {
            $values = array();
            while ( $schools->have_posts() ) {
                $schools->the_post();
                $values += [ get_the_title() => get_the_ID() ];
            }
        } else {
            $values = array(
                'Error: No Schools Available' => 'error',
            );
        }
        ?>
        <select name="ssp_school_custom_column_filter">
        <option value="">Filter by School</option>
        <?php
            $current_school = isset($_GET['ssp_school_custom_column_filter']) ? $_GET['ssp_school_custom_column_filter'] : '';
            foreach ($values as $label => $value) {
                printf (
                    '<option value="%s" %s>%s</option>',
                    $value,
                    $value == $current_school ? 'selected="selected"' : '',
                    $label
                );
            }
        ?>
        </select>
        <?php
    }
} add_action( 'restrict_manage_posts', 'ssp_school_custom_column_filter' );

/**
 * Handle Submitted School Filter
 *
 * Change META_KEY to the actual meta key
 * and POST_TYPE to the name of your custom post type
 *
 * @param  (wp_query object) $query
 *
 * @return Void
 */
function ssp_school_custom_column_posts_filter( $query ){

    global $pagenow;

    $type = 'post';
    if (isset($_GET['post_type'])) {
        $type = $_GET['post_type'];
    }

    // Manually add members b/c they aren't Uniform Items
    $types = array( 'member' );
    // Get all the Uniform Items and add them to Types
    $types_uniforms = ssp_get_uniform_items_names_by_size('all');   
    // Combine Members and Uniform Items
    $types = array_merge( $types , $types_uniforms );

    if ( in_array( $type , $types) &&
         is_admin() &&
         $pagenow == 'edit.php' &&
         isset($_GET['ssp_school_custom_column_filter']) &&
         $_GET['ssp_school_custom_column_filter'] != '' &&
         $query->is_main_query()
        )
    {
        // Get the post type object
        $type_obj = get_post_type_object( $type );

        // The meta_key is dependent on the post type
        $query->query_vars['meta_key'] = 'assigned_school';
        $query->query_vars['meta_value'] = intval($_GET['ssp_school_custom_column_filter']);
        $query->query_vars['meta_compare'] = '=';
    }

} add_filter( 'parse_query', 'ssp_school_custom_column_posts_filter' );

I'm having the exact same issue.

All the code examples I've found look like the following, and it seems both of our code (your and mine) look just like these examples, but neither seem to be working

Filter by custom field in custom post type on admin page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.