Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

How to filter custom posts by custom field in WordPress admin area

/** Create the filter dropdown */
add_action( 'restrict_manage_posts', 'wpse45436_admin_posts_filter_restrict_manage_posts' );
 
function wpse45436_admin_posts_filter_restrict_manage_posts(){
    $type = 'post';
    if (isset($_GET['post_type'])) {
        $type = $_GET['post_type'];
    }
 
    //add filter to the post type you want
    if ('NAME_OF_YOUR_POST' == $type){ //Replace NAME_OF_YOUR_POST with the name of custom post
        $values = array(
            'label1' => 'value1', //Replace label1 with name and value1 with the value of custom field
            'label2' => 'value2', //Replace label2 with name and value2 with another value of custom field
        );
        ?>
        <select name="ADMIN_FILTER_FIELD_VALUE">
<option value=""><?php _e('Filter By ', 'wose45436'); ?></option>
        <?php $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:''; foreach ($values as $label => $value) {
                printf
                    (
                        '<option value="%s"%s>%s</option>',
                        $value,
                        $value == $current_v? ' selected="selected"':'',
                        $label
                    );
                }
        ?>
        </select>
        <?php } } /** if submitted filter by post meta */ add_filter( 'parse_query', 'wpse45436_posts_filter' ); function wpse45436_posts_filter( $query ){ global $pagenow; $type = 'post'; if (isset($_GET['post_type'])) { $type = $_GET['post_type']; } //Replace NAME_OF_YOUR_POST with the name of custom post if ( 'NAME_OF_YOUR_POST' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '') { $query->query_vars['meta_key'] = 'META_KEY'; //Replace META_KEY to the actual meta key
        $query->query_vars['meta_value'] = $_GET['ADMIN_FILTER_FIELD_VALUE'];
    }
}
Source by www.iamabdus.com #
 
PREVIOUS NEXT
Tagged: #How #filter #custom #posts #custom #field #WordPress #admin #area
ADD COMMENT
Topic
Name
3+5 =