WooCommerce 管理后台产品页面增加一个根据产品标题的自定义字符数量进行筛选

要在 WooCommerce 管理后台产品页面增加一个根据产品标题的自定义字符数量进行筛选的功能,以下是完整的代码,您可以将其添加到主题的 functions.php 文件中:

// 添加筛选输入框
function filter_products_by_title_length() {
    global $typenow;
    if ( $typenow == 'product' ) {
        $title_length = isset($_GET['title_length']) ? intval($_GET['title_length']) : '';
        echo '<input type="number" name="title_length" value="' . esc_attr($title_length) . '" placeholder="筛选标题长度"/>';
    }
}
add_action('restrict_manage_posts', 'filter_products_by_title_length');

// 根据输入的字符数值筛选产品
function filter_products_query_by_title_length( $query ) {
    global $pagenow, $wpdb;
    if ( $pagenow == 'edit.php' && isset($_GET['title_length']) && !empty($_GET['title_length']) ) {
        $title_length = intval($_GET['title_length']);
        $query->set('suppress_filters', false);

        // 添加一个 where 子句来过滤产品标题的长度
        add_filter('posts_where', function($where) use ($title_length, $wpdb) {
            global $wpdb;
            $where .= " AND CHAR_LENGTH({$wpdb->posts}.post_title) = {$title_length}";
            return $where;
        });
    }
}
add_filter('pre_get_posts', 'filter_products_query_by_title_length');

// 重置 posts_where 过滤器
function reset_posts_where_filter($query) {
    if ( !is_admin() || !$query->is_main_query() ) {
        return;
    }
    
    remove_filter('posts_where', 'filter_products_query_by_title_length');
}
add_action('pre_get_posts', 'reset_posts_where_filter', 20);