最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

search - Filter WP user acf field by ajax

programmeradmin1浏览0评论

I have a search page where search result of user is displaying by postal code or county name. while on the search page i have checkbox to filter user by attribute like developer, designer, and account, so visitor can filter the user of the postal code by attribute. All the field was create by advance custom field. I am displaying the user data by ajax. but don't know where is the problem. please help

here is the form to display checkbox field.

        <div class="sectionContent filter_list">
            <?php 
                acf_form([
                    'field_groups' => ['50'],
                    'fields' => ['category', 
                                'type_of_session', 
                                'wheelchair_access', 
                                'telephone_life_coaching', 
                                'face_to_face_life_coaching',
                                'home_visits',
                                'sign_language',
                            ],
                    'form' => false
                ])
            ?>
        </div> 

    <script>
    jQuery(function($){
        $('.filter_list input').on('change', function()
        {
            var url = '<?php echo admin_url( 'admin-ajax.php' ); ?>?action=find_coach';
            $('.filter_list input').each(function()
            {
                var thisVal, metaKey;

                                if($(this).prop('checked') == true)
                                {
                                    thisVal = $(this).val();
                                    //may be the problem in metakey
                                    metaKey = getParamFromUrl('pin_code');
                                    url += '&acf['+metaKey+'][]='+thisVal;
                                }


            });

            $.get(url, function(res){
                $.each(res, function(key, val){
                    $user_row = '<div data-template="member" class="member">\
                        <div class="user">\
                            <div class="article_left">\
                                <a href="'+val.user_url+'"><img src="'+val.avatar+'"></a>\
                            </div>\
                            <div class="article_right">\
                                <div class="profile-display-address">\
                                    <h2 class="member-name">\
                                        <a href="'+val.user_url+'">'+val.display_name+'</a>\
                                    </h2>\
                                    <div class="col-6">'+val.address+'</div>\
                                    <div class="col-6">'+val.address_2+'</div>\
                                    <div class="col-6">'+val.pin_code+'</div>\
                                </div>\
                                <div class="contact-form contact-links"><a href="#">Contact me</a></div>\
                            </div>\
                        <div class="button-profile"><a class="button whitebg" href="'+val.user_url+'">View profile</a></div>\
                    </div>';
                    document.getElementById('member_list').innerHTML = $user_row;
                });
            });
        }); 

        $('.filter_list input').each(function(){
            //checkbox handling
            if($(this).prop('tagName') == 'INPUT' && $(this).attr('type') == 'checkbox'){
                var val = getParamFromUrl($(this).attr('name'))
                if(val.indexOf($(this).val()) > -1){
                    $(this).prop('checked', true);
                }
            }
        });     
    });

    function getParamFromUrl(name){
        var url = new URL(window.location.href);
        var c = url.searchParams.getAll(name);
        return c;
    }
</script>
    add_action('wp_ajax_search_coach', 'searchLifeCoach');
     add_action('wp_ajax_nopriv_search_coach', 'searchLifeCoach');
     function searchLifeCoach(){
     //print_R($_GET);
     $metaData = [];

     $fields = acf_get_fields($field_group_key);
    if(isset($_GET['acf']) && !empty($_GET['acf'])){
        foreach($_GET['acf'] as $key => $field){
            $metaData[] = [
                'key'   => $key,
                'value' => $field,
                'compare' => is_array($field) ? 'LIKE' : '=' 
            ];
        }
    }

    $args = array (
        'order'      => 'ASC',
        'orderby'    => 'display_name', 
        'role__not_in' => 'administrator',
        //'fields' => 'all_with_meta', 
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'pincode',
                'value'   => sanitize_text_field($_GET['city']),
                'compare' => '='
            ),
            array(
                'key'     => 'city',
                'value'   => sanitize_text_field($_GET['city']),
                'compare' => '='
            ),
        ),
        'meta_query' => array(
            'relation' => 'AND',
            $metaData
        )
    );

    // Create the WP_User_Query object
    $wp_user_query = new WP_User_Query( $args );
    //echo '<pre>'; print_r($wp_user_query); echo '</pre>';
    // Get the results
    $authors = $wp_user_query->get_results();

    foreach($authors as $author){
        $userMeta = get_user_meta($author->data->ID);
        //echo '<pre>'; print_r($userMeta); echo '</pre>';
        $userList[] = [
            'uid' => $author->data->ID,
            'display_name' => $author->data->display_name,
            'email' => $author->data->user_email,
            'user_url' => $author->data->user_url,
            'avatar' => (isset($userMeta['avatar']) ? wp_get_attachment_url($userMeta['avatar'][0]) : ''),
            'first_name' => (isset($userMeta['first_name']) ? $userMeta['first_name'][0] : ''),
            'last_name' => (isset($userMeta['last_name']) ? $userMeta['last_name'][0] : ''),
            'user_phone' => (isset($userMeta['phone']) ? $userMeta['phone'][0] : ''),
            'address' => (isset($userMeta['address']) ? $userMeta['address'][0] : ''),
            'address_2' => (isset($userMeta['address_2']) ? $userMeta['address_2'][0] : ''),
            'pin_code' => (isset($userMeta['pin_code']) ? $userMeta['pin_code'][0] : ''),
            'age' => (isset($userMeta['age']) ? $userMeta['age'][0] : ''),
            'bio' => (isset($userMeta['coach_bio']) ? $userMeta['coach_bio'][0] : ''),
            'city' => (isset($userMeta['city']) ? $userMeta['city'][0] : ''),
            'city_2' => (isset($userMeta['city_2']) ? $userMeta['city_2'][0] : ''),
            'zip_code_2' => (isset($userMeta['zip_code_2']) ? $userMeta['zip_code_2'][0] : ''),
            'zip_code_2' => (isset($userMeta['zip_code_2']) ? $userMeta['zip_code_2'][0] : ''),
        ];
    }
    return wp_send_json($userList);
    exit();
}

I have a search page where search result of user is displaying by postal code or county name. while on the search page i have checkbox to filter user by attribute like developer, designer, and account, so visitor can filter the user of the postal code by attribute. All the field was create by advance custom field. I am displaying the user data by ajax. but don't know where is the problem. please help

here is the form to display checkbox field.

        <div class="sectionContent filter_list">
            <?php 
                acf_form([
                    'field_groups' => ['50'],
                    'fields' => ['category', 
                                'type_of_session', 
                                'wheelchair_access', 
                                'telephone_life_coaching', 
                                'face_to_face_life_coaching',
                                'home_visits',
                                'sign_language',
                            ],
                    'form' => false
                ])
            ?>
        </div> 

    <script>
    jQuery(function($){
        $('.filter_list input').on('change', function()
        {
            var url = '<?php echo admin_url( 'admin-ajax.php' ); ?>?action=find_coach';
            $('.filter_list input').each(function()
            {
                var thisVal, metaKey;

                                if($(this).prop('checked') == true)
                                {
                                    thisVal = $(this).val();
                                    //may be the problem in metakey
                                    metaKey = getParamFromUrl('pin_code');
                                    url += '&acf['+metaKey+'][]='+thisVal;
                                }


            });

            $.get(url, function(res){
                $.each(res, function(key, val){
                    $user_row = '<div data-template="member" class="member">\
                        <div class="user">\
                            <div class="article_left">\
                                <a href="'+val.user_url+'"><img src="'+val.avatar+'"></a>\
                            </div>\
                            <div class="article_right">\
                                <div class="profile-display-address">\
                                    <h2 class="member-name">\
                                        <a href="'+val.user_url+'">'+val.display_name+'</a>\
                                    </h2>\
                                    <div class="col-6">'+val.address+'</div>\
                                    <div class="col-6">'+val.address_2+'</div>\
                                    <div class="col-6">'+val.pin_code+'</div>\
                                </div>\
                                <div class="contact-form contact-links"><a href="#">Contact me</a></div>\
                            </div>\
                        <div class="button-profile"><a class="button whitebg" href="'+val.user_url+'">View profile</a></div>\
                    </div>';
                    document.getElementById('member_list').innerHTML = $user_row;
                });
            });
        }); 

        $('.filter_list input').each(function(){
            //checkbox handling
            if($(this).prop('tagName') == 'INPUT' && $(this).attr('type') == 'checkbox'){
                var val = getParamFromUrl($(this).attr('name'))
                if(val.indexOf($(this).val()) > -1){
                    $(this).prop('checked', true);
                }
            }
        });     
    });

    function getParamFromUrl(name){
        var url = new URL(window.location.href);
        var c = url.searchParams.getAll(name);
        return c;
    }
</script>
    add_action('wp_ajax_search_coach', 'searchLifeCoach');
     add_action('wp_ajax_nopriv_search_coach', 'searchLifeCoach');
     function searchLifeCoach(){
     //print_R($_GET);
     $metaData = [];

     $fields = acf_get_fields($field_group_key);
    if(isset($_GET['acf']) && !empty($_GET['acf'])){
        foreach($_GET['acf'] as $key => $field){
            $metaData[] = [
                'key'   => $key,
                'value' => $field,
                'compare' => is_array($field) ? 'LIKE' : '=' 
            ];
        }
    }

    $args = array (
        'order'      => 'ASC',
        'orderby'    => 'display_name', 
        'role__not_in' => 'administrator',
        //'fields' => 'all_with_meta', 
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'pincode',
                'value'   => sanitize_text_field($_GET['city']),
                'compare' => '='
            ),
            array(
                'key'     => 'city',
                'value'   => sanitize_text_field($_GET['city']),
                'compare' => '='
            ),
        ),
        'meta_query' => array(
            'relation' => 'AND',
            $metaData
        )
    );

    // Create the WP_User_Query object
    $wp_user_query = new WP_User_Query( $args );
    //echo '<pre>'; print_r($wp_user_query); echo '</pre>';
    // Get the results
    $authors = $wp_user_query->get_results();

    foreach($authors as $author){
        $userMeta = get_user_meta($author->data->ID);
        //echo '<pre>'; print_r($userMeta); echo '</pre>';
        $userList[] = [
            'uid' => $author->data->ID,
            'display_name' => $author->data->display_name,
            'email' => $author->data->user_email,
            'user_url' => $author->data->user_url,
            'avatar' => (isset($userMeta['avatar']) ? wp_get_attachment_url($userMeta['avatar'][0]) : ''),
            'first_name' => (isset($userMeta['first_name']) ? $userMeta['first_name'][0] : ''),
            'last_name' => (isset($userMeta['last_name']) ? $userMeta['last_name'][0] : ''),
            'user_phone' => (isset($userMeta['phone']) ? $userMeta['phone'][0] : ''),
            'address' => (isset($userMeta['address']) ? $userMeta['address'][0] : ''),
            'address_2' => (isset($userMeta['address_2']) ? $userMeta['address_2'][0] : ''),
            'pin_code' => (isset($userMeta['pin_code']) ? $userMeta['pin_code'][0] : ''),
            'age' => (isset($userMeta['age']) ? $userMeta['age'][0] : ''),
            'bio' => (isset($userMeta['coach_bio']) ? $userMeta['coach_bio'][0] : ''),
            'city' => (isset($userMeta['city']) ? $userMeta['city'][0] : ''),
            'city_2' => (isset($userMeta['city_2']) ? $userMeta['city_2'][0] : ''),
            'zip_code_2' => (isset($userMeta['zip_code_2']) ? $userMeta['zip_code_2'][0] : ''),
            'zip_code_2' => (isset($userMeta['zip_code_2']) ? $userMeta['zip_code_2'][0] : ''),
        ];
    }
    return wp_send_json($userList);
    exit();
}
Share Improve this question edited Mar 8, 2020 at 16:54 Tom J Nowell 61.1k7 gold badges79 silver badges148 bronze badges asked Mar 8, 2020 at 16:27 Atif AqeelAtif Aqeel 19312 bronze badges 5
  • 1 You say you don't know where the problem is, but never state what the problem is. Also, where is the PHP code for the Admin AJAX endpoint? Is there a reason you used the legacy Admin AJAX endpoint instead of a modern REST API endpoint? – Tom J Nowell Commented Mar 8, 2020 at 16:36
  • sorry forgot to write about the problem. when you look at the url lifecoachnearme.co.uk/… and click on any checkbox field . you will get the error , bad request 400. i have added the acf from code in by question above. – Atif Aqeel Commented Mar 8, 2020 at 16:40
  • Can you include the code for the endpoint and the hooks that register it? This would be the code that implements Admin AJAX on the server side, not the frontend side/HTML markup. Also, when you test this are you logged in, or logged out? This might be a common issue you've ran into but it's impossible to tell without seeing the PHP code for the Admin AJAX handler ( it's also an issue that doesn't happen when using the modern REST API for AJAX ) – Tom J Nowell Commented Mar 8, 2020 at 16:42
  • added now, but remember this was working fine when last developer touched the code. – Atif Aqeel Commented Mar 8, 2020 at 16:49
  • it was working in the condition that just filtering the user only on based of the checkbox. it mean in you are on the search page by any postal code and then you click any of the checkbox . it just display the database field. We need to display the data by zip code and then filter by the category. so another developer changed the code and it wont work any more. it may be the problem in getting the field name of form. //may be the problem in metakey metaKey = getParamFromUrl('pin_code'); url += '&acf['+metaKey+'][]='+thisVal; – Atif Aqeel Commented Mar 8, 2020 at 17:02
Add a comment  | 

1 Answer 1

Reset to default 1

The problem is your action names don't match

In your frontend code:

?action=find_coach';

But in your backend code:

    add_action('wp_ajax_search_coach', 'searchLifeCoach');
     add_action('wp_ajax_nopriv_search_coach', 'searchLifeCoach');

search_coach != find_coach, they have to match.

Note that if this code used the REST API, it would have given a 404 and stated the problem in human readable language, e.g.

{
    "code":"rest_no_route",
    "message":"No route was found matching the URL and request method",
    "data":{"status":404}
}
发布评论

评论列表(0)

  1. 暂无评论