admin管理员组

文章数量:1129454

I have a dropdown menu of all authors or usernames on the page of post table or post list. I would like to make that dropdown menu searchable. Here are my codes:

    <?php

    // Get an array of WP usernames:
    $users = get_users();
    $user_names = wp_list_pluck( $users, 'user_login' );

    ?>

    <script src=".1.1.min.js" type="text/javascript"></script>
    <link href=".0.1/css/select2.min.css" rel="stylesheet" />
    <script src=".0.1/js/select2.min.js"></script>

    <script type="text/javascript">
      jQuery(document).ready(function($) {
        var usernamesArray = <?php echo json_encode($user_names); ?>;  // Convert php array into jQuery array
        $("#author").select2({
          data: usernamesArray
        });
      });
    </script>

The above codes work somewhat and slow. After refreshing the page, it becomes blank.

What is the right way of maker a filter searchable at WP backend?

Many thanks in advance.

Here are custom codes in functions.php for adding Author filter:

  function rudr_filter_by_the_author() {
    $params = array(
      'name' => 'author', // this is the "name" attribute for filter <select>
      'show' => 'user_login',
      'orderby' => 'user_login',
      'order' => 'ASC',
      'show_option_all' => 'All Authors' // label for all authors (display posts without filter)
    );
   
    if ( isset($_GET['user']) )
      $params['selected'] = $_GET['user']; // choose selected user by $_GET variable
   
    wp_dropdown_users( $params ); // print the ready author list
  }
  add_action('restrict_manage_posts', 'rudr_filter_by_the_author');

Many thanks

I have a dropdown menu of all authors or usernames on the page of post table or post list. I would like to make that dropdown menu searchable. Here are my codes:

    <?php

    // Get an array of WP usernames:
    $users = get_users();
    $user_names = wp_list_pluck( $users, 'user_login' );

    ?>

    <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>

    <script type="text/javascript">
      jQuery(document).ready(function($) {
        var usernamesArray = <?php echo json_encode($user_names); ?>;  // Convert php array into jQuery array
        $("#author").select2({
          data: usernamesArray
        });
      });
    </script>

The above codes work somewhat and slow. After refreshing the page, it becomes blank.

What is the right way of maker a filter searchable at WP backend?

Many thanks in advance.

Here are custom codes in functions.php for adding Author filter:

  function rudr_filter_by_the_author() {
    $params = array(
      'name' => 'author', // this is the "name" attribute for filter <select>
      'show' => 'user_login',
      'orderby' => 'user_login',
      'order' => 'ASC',
      'show_option_all' => 'All Authors' // label for all authors (display posts without filter)
    );
   
    if ( isset($_GET['user']) )
      $params['selected'] = $_GET['user']; // choose selected user by $_GET variable
   
    wp_dropdown_users( $params ); // print the ready author list
  }
  add_action('restrict_manage_posts', 'rudr_filter_by_the_author');

Many thanks

Share Improve this question edited Dec 31, 2023 at 0:52 daro2013 asked Dec 30, 2023 at 16:59 daro2013daro2013 251 silver badge6 bronze badges
Add a comment  | 

1 Answer 1

Reset to default -1

here are some notes:

  1. It's important to enqueue scripts and styles properly in WordPress. You should enqueue the Select2 script and its styles using the WordPress enqueue system. This ensures that they are loaded correctly and in the right order.
  2. Use WordPress AJAX for Dynamic Data Loading: If the list of users is large, loading all usernames at once can be slow and resource-intensive. To improve performance, you can use WordPress AJAX to load usernames dynamically as the user types in the search box.
  3. Add this code to your themes functions.php file
// Enqueue scripts and styles
function wpb_enqueue_scripts_author_dropdown() {
    wp_enqueue_style('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css');
    wp_enqueue_script('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js', array('jquery'), null, true);
    wp_enqueue_script('author-dropdown-script', get_stylesheet_directory_uri() . '/includes/js/author-dropdown.js', array('jquery', 'select2'), mt_rand(00000, 9999999), true);

    wp_localize_script('author-dropdown-script', 'wpb_author_dropdown', array(
        'ajax_url' => admin_url('admin-ajax.php')
    ));
}
add_action('admin_enqueue_scripts', 'wpb_enqueue_scripts_author_dropdown');

// AJAX handler for fetching usernames
function wpb_ajax_fetch_usernames() {
    $search_term = isset($_GET['q']) ? sanitize_text_field($_GET['q']) : '';
    $users = get_users(array('search' => '*' . esc_attr($search_term) . '*'));
    $user_names = wp_list_pluck($users, 'user_login');
    wp_send_json($user_names);
}
add_action('wp_ajax_fetch_usernames', 'wpb_ajax_fetch_usernames');

// Create a shortcode for the dropdown
function wpb_author_dropdown_shortcode() {
    ob_start();
    ?>
    <select id="author" style="width: 50%"></select>
    <?php
    return ob_get_clean();
}
add_shortcode('wpb_author_dropdown', 'wpb_author_dropdown_shortcode');

Now you can call your html by using the shortcode [wpb_author_dropdown] in a text editor or code box, or, you can use the do_shortcode function in a php file like this:

<?php echo do_shortcode('[wpb_author_dropdown]'); ?>

OR

echo do_shortcode('[wpb_author_dropdown]');

Now, in your theme directory create this file: /includes/js/author-dropdown.js In that add this code:

jQuery(document).ready(function($) {
    $("#author").select2({
        ajax: {
            url: wpb_author_dropdown.ajax_url,
            dataType: 'json',
            data: function (params) {
                return {
                    action: 'fetch_usernames',
                    q: params.term // search term
                };
            },
            processResults: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item,
                            id: item
                        };
                    })
                };
            }
        }
    });
});

本文标签: dropdownMaking a filter searchable on the page of post list at Wordpress backend