WordPress Dashboard后台 非插件 纯代码 实现自定义字段过滤

前面我们介绍了 WordPress 主题/插件开发 自定义文章分类 筛选功能 图文教程

下面我们记录一下如何在后台实现过滤自定义字段,将以下代码放入 functions.php 文件中代码段如下:

add_filter( 'parse_query', 'jadmin_posts_filter' );
add_action( 'restrict_manage_posts', 'jadmin_posts_filter_restrict_manage_posts' );
 
function jadmin_posts_filter( $query )
{
    global $pagenow;
    if ( is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_NAME']) && '' != $_GET['ADMIN_FILTER_FIELD_NAME']) {
        $query->query_vars['meta_key'] = sanitize_text_field($_GET['ADMIN_FILTER_FIELD_NAME']);
    if (isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && '' != $_GET['ADMIN_FILTER_FIELD_VALUE'])
        $query->query_vars['meta_value'] = sanitize_text_field($_GET['ADMIN_FILTER_FIELD_VALUE']);
    }
}
 
function jadmin_posts_filter_restrict_manage_posts()
{
    global $wpdb;
    $sql = 'SELECT DISTINCT meta_key FROM '.$wpdb->postmeta.' ORDER BY 1';
    $fields = $wpdb->get_results($sql, ARRAY_N);
?>
<select name="ADMIN_FILTER_FIELD_NAME">
<option value=""><?php _e('Filter By Custom Fields', 'jiloc'); ?></option>
<?php
    $current = isset($_GET['ADMIN_FILTER_FIELD_NAME'])? $_GET['ADMIN_FILTER_FIELD_NAME']:'';
    $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
    foreach ($fields as $field) {
        if (substr($field[0],0,1) != "_"){
        printf
            (
                '<option value="%s"%s>%s</option>',
                $field[0],
                $field[0] == $current? ' selected="selected"':'',
                $field[0]
            );
        }
    }
?>
</select> <?php _e('Value:', 'jiloc'); ?><input type="TEXT" name="ADMIN_FILTER_FIELD_VALUE" value="<?php echo $current_v; ?>" />
<?php
}
WordPress Dashboard后台 非插件 纯代码 实现自定义字段过滤
链接到文章: https://vpsum.com/47629.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注