Custom Fields
Re-Envisioned
Support Meta Box Group Clonable select_advanced with ajax

  • Creator
    Topic
  • #8536
    Resolved fexy
    Participant

    Hi, we need to be able to link a post to one or more other posts so we used metabox.io to create a group of clonable fields with a type of “post” to do this. However, since we have a few thousand posts, the performance was really poor once a user had associated a few posts (sometimes they associate as many as 30+).

    No we are hoping to make the field a “select_advanced” field and performance ajax lookups instead to avoid these performance issues. We did this by creating a simple wp_ajax endpoint that returned the matching posts in json as select2 expects and that almost works. The select_advanced dropdown renders properly and the ajax search works returning results but clicking on a result does nothing.

    Shouldn’t this work?

    Following is our metabox group definition:

    
    $meta_boxes[] = array(
        'id' => "finite_scroll",
        'title' => __('Finite Scroll'),
        'post_types' => array('recipe'),
        'fields' => array(
            array(
                'id' => $prefix . 'related_recipe',
                'type' => 'group',
                'clone' => true,
                'sort_clone' =>true,
                'fields' => array(
                    array(
                        'name' => __('Related Recipe:'),
                        'id' => $prefix . 'rel_recipe',
                        'type' => 'select_advanced',
                        'options' => array('' => ''),
                        'js_options' => array (
                            'ajax' => array(
                                'url' => '/wp-admin/admin-ajax.php?action=select_advanced_post_lookup&post_type=recipe',
                                'dataType' => 'json',
                                'type' => 'get',
                                'delay' => '250'
                            ),
                            'minimumInputLength' => 3,
                            'allowClear' => true, 
                            'placeholder' => 'Select recipe'
                        ) 
                    )
                )
            )
        )
    );
    

    Here is the wp_ajax function that sends search results to select2:

    
    add_action('wp_ajax_select_advanced_post_lookup', 'select_advanced_post_lookup');
    function select_advanced_post_lookup() {
        global $wpdb;
        $post_types = "'".implode("','", explode(',', $_GET['post_type']))."'";
        $keyword = "%".$wpdb->esc_like($_GET['q'])."%"; 
    
        $sql = "SELECT ID, post_title".
            " FROM $wpdb->posts".
            " WHERE post_title LIKE '". $keyword . "'" .
            " AND post_type IN (". $post_types .")" .
            " AND post_status='publish' ".
            " ORDER BY post_title LIMIT 0,15;";
        $results = $wpdb->get_results($sql);
        $response = array(
            'results' => array()
        );
        foreach ( $results as $result ) {
            $response['results'][] = array( 'id:' => $result->ID, 'text' => $result->post_title );
        }
        wp_send_json($response);
    }
    
Viewing 8 replies - 1 through 8 (of 8 total)
  • Author
    Replies
  • #8540
    Anh Tran
    Keymaster

    Hello,

    The logic should work. There is just a small typo in your code. In the response, the param should be id instead of id:.

    However, loading selected posts to show after updating is the next problem. We need to update options parameter to make the field renders properly. So, I added 2 more functions to get the saved data and put them in the options:

    https://pastebin.com/QNdW8cty

    #8550
    fexy
    Participant

    Nice catch on the id param! Two of us were looking at the code so I don’t know how we missed that typo. That is what was causing the issue where we couldn’t select an item from the drop-down.

    I figured we’d have to solve for the post being selected after an update so I appreciate the code sample to get that working too! We’ve made the changes and it appears to be working great.

    Thanks for your help!

    #16465
    badabingbreda
    Participant

    Has this changed by any chance? I’ve implemented this successfully a few months ago on a site that’s in development, but I just got a call from my client that it doesn’t work any more.

    Specifically, when I look in the database, and see that on older posts the metavalue for my key is stored, so it also gets the corresponding value. That indicates to me that that part is still working correctly. What is NOT working is when I create a new post, have it search the matching values that are showing in the select_advanced field and try to save it. It stores all but that meta_key to the database… It doesn’t store the value on the select2 field, and doesn’t seem to pass it on.

    #16477
    Anh Tran
    Keymaster

    You probably don’t need to implement custom solution for ajax anymore. We have added ajax support for object fields in version 5.2. See this blog post for details.

    #16485
    badabingbreda
    Participant

    Thanks Anh, that helped!

    #16553
    wgstjf
    Participant

    @badabingbreda – Did you figure out why it wasn’t storing the value in the end?

    Cheers,

    Will

    #16556
    badabingbreda
    Participant

    Actually, no.

    I was able to fix it because the post-field now also support request by ajax so I changed the code. The strangest thing is, that on the exact same page, there is still a cloneable group field with the same routine (also select_advanced, pulling products from a custom table) that was and is still working as expected. It is still using the same code as before without any problems… for now.

    I’ve seen you’re other post https://metabox.io/support/topic/select_advanced-with-ajax/ suggesting that adding with the sanitize_callback might have fixed it. If I can, I’ll test that theory.

    #16557
    wgstjf
    Participant

    Was just about to update my post on this topic to reflect the progress we’ve made. Good to se you’ve found it already and good luck with your tests.

    Cheers,

    Will

Viewing 8 replies - 1 through 8 (of 8 total)
  • You must be logged in to reply to this topic.