Support

Account

Home Forums Backend Issues (wp-admin) How can I dynamically filter the list of posts?

Solved

How can I dynamically filter the list of posts?

  • Hello!

    Great plugin and the repeater field is a nice add-on!

    I am working on a new project and need to setup a custom field that show a list of posts, but the list of posts that are displayed needs to be dynamically filtered by the categories the user selects for the post. I can get the list of posts ( a custom post type ) to display and even tested out some filtering using this code

    function my_acf_result_query( $args, $field, $post )
    {
        // eg from https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
     
        
      $args['cat'] = '3';
     
        return $args;
    }
    
    // acf/fields/relationship/result/name={$field_name} - filter for a specific field based on it's name
    add_filter('acf/fields/relationship/query/name=post_image', 'my_acf_result_query', 10, 3);

    but now I need the category filter list to be dynamic and update on the fly as the user select categories for the post they are adding.

    I think I need to create a my own field type, but not 100% sure on the best way to proceed.

    What I am trying to achieve is to give the user that is adding the post a list of images that can be used as featured image filtered by categories. I have created a custom post type that allows users to add images for each category, but not I need to hook it up as indicated above.

    Suggestion, code examples or feedback is more then welcome!

  • Hi @ebud

    Your are half way through the code needed to perform this AJAX lookup.

    Your PHP filter correctly modifies the query arguments which will take place on page load, however, you will now need to write some JS to listen to a CHANGE event on the trigger field, and then reload the select field.

    The easiest way to do this is to use the jQuery function load. This function allows you to target an element on a page, and just load that HTML!

    What you want to do is load the same wp-admin page, but target the correct select field (either via classes or id attribute). Then just replace the original one with what the AJAX returns.

    Does this help?

    Thanks
    E

  • Thanks for the prompt reply!

    Should I be creating a new field type using your instruction?
    http://www.advancedcustomfields.com/resources/tutorials/creating-a-new-field-type/

    Currently I have the filter setup in the themes functions.php file.

    Any pointers or code snips you can forward or point me at to help me understand where and how to include the AJAX/jQuery piece?

  • Another related question, I think I might be better off using the post object, but this does not appear to do anything when I would expect the list of posts to filtered by category?

    function my_post_object_query( $args, $field, $post )
    {
    	
        
    	$args['cat'] = get_all_category_ids();
    
        return $args;
    }
    
    // filter for a specific field based on it's name
    add_filter('acf/fields/post_object/query/name=post_image', 'my_post_object_query', 10, 3);
    

    even hard coding a number rather then using get_all_category_ids() does nothing – am I missing something?

  • Hi @ebud

    As for your last question, can you please debug the code within the function. Can you confirm that the filter is fireing?

    Perhaps there is a problem with the filter using the ‘name’. Instead, can you try using the field key?

    There is no need to write a new field type.

    As for AJAX JS stuff, this would take quite some time for me to explain, so I encourage you first to jump on google and research how to add JS to an admin screen (there is a ACF action called acf/input/admin_head) for this, and also learn how to perform an AJAX call.

    Thanks
    E

  • Thanks!

    Making some headway, here is my new test code:

    function my_post_object_query( $args, $field, $post )
    {
    	
    	$args['cat'] = wp_get_post_categories($post->ID);
    	echo '<pre>';
    	print_r($args);
    	echo '</pre>';
    	//die;
        return $args;
    }
    
    // filter for a specific field based on it's key
    add_filter('acf/fields/post_object/query/key=field_524f02159316d', 'my_post_object_query', 10, 3);

    This returns the following array:

    Array
    (
        [numberposts] => -1
        [post_type] => post_images
        [orderby] => title
        [order] => ASC
        [post_status] => Array
            (
                [0] => publish
                [1] => private
                [2] => draft
                [3] => inherit
                [4] => future
            )
    
        [suppress_filters] => 
        [sort_column] => menu_order, post_title
        [sort_order] => ASC
        [cat] => Array
            (
                [0] => 5
            )
    
    )

    you can see the cat id is getting added, but the results that come back in the dropdown are not filter to only include posts form catid 5

  • Hi There

    I am switching back to the Relationship field as it seems to sort of handle the cat filter.

    Here is my code

    function my_relationship_query( $args, $field, $post )
    {
        // increase the posts per page
        //$args['cat'] = wp_get_post_categories($post->ID);
    	$args['cat'] = '3,5';
    	
        return $args;
    }
     
    // filter for a specific field based on it's key
    add_filter('acf/fields/relationship/query/key=field_524f02159316d', 'my_relationship_query', 10, 4);

    using 3,5 works, but wp_get_post_categories($post->ID) does not work, just displays the loading icon.

    Also – Is it possible to limit the number of items that can be added from left to right to only 1?

  • Hi @ebud

    Can you turn on DEBUG MODE and debug what:

    
    wp_get_post_categories($post->ID)
    

    produces?

    Perhaps debug $post as well to make sure it is the correct value you are expecting.

    You can set a max setting for the relationship field too.

    Thanks
    E

  • Thanks! got part if it working now.
    $args['cat'] = implode(",", wp_get_post_categories($post->ID));
    I was sending an array and your code is looking for a string.

    I still need to figure out a couple of things:

    For the Relationship field I would like to limit the number of items that the user can add to the right to only one item instead of multiple items. I know through the UI you can set a max number of records to return, but this is not what I am trying to figure out.

    I have some jQuery that listens for category changes and captures the string of categories. You mentioned this “What you want to do is load the same wp-admin page, but target the correct select field (either via classes or id attribute). Then just replace the original one with what the AJAX returns.” in the your original response. This is the part I am struggling. with now. I have have the bits of code and now I just need to do the final hook up.

    Any points or threads you can point me at?

  • Hi @ebud

    I’m a bit confused about your statement:

    
    For the Relationship field I would like to limit the number of items that the user can add to the right to only one item instead of multiple items. I know through the UI you can set a max number of records to return, but this is not what I am trying to figure out.
    

    The max UI option is to limit the number of items allows to be added.

    The jQuery load code is going to be pretty complex. I’ll try to find some time to write up a tutorial, but can’t guarantee I will be able to help you with this any time soon.

    Perhaps you could read up on jQuery docs regarding .load() and .on()

    Thanks
    E

  • Got it! I didn’t realize the the Maximum Post setting was limiting the number of items that can be select or added (+). I thought that was limiting the number of items returned to the UI. Setting this this to 1 does exactly what I needed! – Thank you.

    In terms of jQuery load() I have some code the uses this function to re-load the relationship field, as the categories are checked/unchecked/, this refreshed the UI, but in the case of the relationship field the contents never get reloaded, just the spinning loading icon.
    jQuery( "#acf_957 " ).load("<?php echo $_SERVER['REQUEST_URI'] ?> #acf_957 > *" );

    If I test this against the Post Object select field the re-load works as expected.

    If I could solve the above I would be 75% there! The last 25% is how do I use ajax to force a ACF to re-query the posts based on a new category id list.

  • This reply has been marked as private.
  • Hi @ebud

    Thanks for attaching the code. For this functinality, you do not want to use the WP AJAX PHP functions via add_action(‘wp_ajax’…

    I have a feeling that the AJAX may not even be needed. Can you please attach a screenshot of the repeater field to demonstrate what you want to happen.

    Thanks
    E

  • Hi Elliot,

    I did purchase the repeater, but it is not used in this specific project. In this project I am using ACF in 2 ways:
    1- A custom post type called post_image that is using your “image” field to store a single image per post.
    2- In the standard post type a “Relationship” field is setup that pulls in posts where post_type = post_image…ideally dynamically filtered by category as the user selects/deselects categories.

    The idea is to populate the post_image area with a bunch of images in a various categories. And then when the user goes to create a new post they have the option of selecting a single image based based on the category(s) that post is being created in.

    Hopefully this give you enough background, but please let me know if you need more details.

  • Hi @ebud

    I don’t think it is yet possible to use the post’s taxonomy data to update the relationship field query on the fly.

    On page load, you can do this just fine as your code already shows, but you may need to ask your client to select the taxonomies first, then save the page, then select the images.

    Thanks
    E

  • This reply has been marked as private.
  • Hi @ebud

    I’m sorry but this functionality is just not possible using the native fields. You will have to write a custom field type to handle the custom jQuery events and AJAX posting data.

    I am unable to take on any freelance jobs at the moment. Perhaps this is something you could post on a freelance web board?

    Thanks
    E

Viewing 18 posts - 1 through 18 (of 18 total)

The topic ‘How can I dynamically filter the list of posts?’ is closed to new replies.