也想出现在这里?联系我们

WordPress 后台文章列表添加自定义字段过滤筛选

2024.03.07 wordpress教程
  • 文章介绍
  • 升级版本
  • 评价&建议

要在WordPress后台文章列表中添加自定义字段过滤筛选功能,您可以使用以下步骤:

  1. 编辑主题的functions.php文件:首先,您需要编辑当前使用的WordPress主题的functions.php文件。您可以通过登录到WordPress后台,然后在外观(Appearance)> 编辑主题(Theme Editor)中找到该文件。

  2. 添加自定义筛选表单:在functions.php文件中,您可以添加以下代码来创建一个自定义筛选表单,通常会放在主题的functions.php文件的底部:

// 添加文章列表页面的自定义筛选表单
function custom_filter_posts() {
    global $post_type;

    if ( 'post' == $post_type ) { // 只在文章列表中显示筛选表单
        $custom_field_value = isset($_GET['custom_field_value']) ? sanitize_text_field($_GET['custom_field_value']) : '';
        ?>
        <label for="custom_field_value">自定义字段筛选:</label>
        <input type="text" id="custom_field_value" name="custom_field_value" value="<?php echo esc_attr($custom_field_value); ?>" />
        <?php
    }
}

add_action('restrict_manage_posts', 'custom_filter_posts');
  1. 处理筛选结果:接下来,您需要在functions.php文件中添加代码来处理筛选结果并应用筛选。以下是一个示例:
// 应用自定义字段筛选
function custom_filter_posts_query($query) {
    global $pagenow;

    if ( is_admin() && 'edit.php' == $pagenow && isset($_GET['post_type']) && $_GET['post_type'] == 'post' && isset($_GET['custom_field_value']) && $_GET['custom_field_value'] != '' ) {
        $custom_field_value = sanitize_text_field($_GET['custom_field_value']);
        $query>query_vars['meta_query'] = array(
            array(
                'key'     => 'custom_field_name', // 将'custom_field_name'替换为您的自定义字段名称
                'value'   => $custom_field_value,
                'compare' => 'LIKE',
            ),
        );
    }
}

add_action('pre_get_posts', 'custom_filter_posts_query');

确保将上述代码中的'custom_field_name'替换为您实际要筛选的自定义字段名称。

  1. 保存文件:保存functions.php文件。

  2. 使用筛选器:现在,当您进入文章列表页面时,您应该会看到自定义筛选表单。您可以在其中输入自定义字段的值,并按“筛选”按钮来过滤文章列表。

请注意,这只是一个基本示例,您可以根据自己的需求进一步自定义筛选功能,以满足特定的要求。同时,确保备份您的主题文件和数据库,以防意外情况发生。

有用0
  • 2024.03.07初次和大家见面了!

等待您对该主题的建议

发表评论

还能输入240个字

Hi, 欢迎加入Wordpress技术交流群,带你装逼带你飞!

我要入群
也想出现在这里?联系我们
wordpress加速

我来推荐一个更牛逼的给你看看?

  • 猛戳我吧