Home Forums ACF PRO conditional sort


conditional sort

  • I have searched the forums extensively for what I suspect is simple to achieve but is evading me at the moment.

    I have a custom post type called “Partners” and have created fields that all work well and display properly. There is one option that sets some conditional fields. For simplicity, I’ll only mention the one that’s relevant.

    When entering a “Partner” one can choose that Partner’s “type” (partner_type) to either be a Person (person) or Organization (org).

    Depending which they choose, they will either get a “Last Name”(last_name) and “First Name”(first_name) field or an “Organization Name”(org_name) field, respectively.

    What I would like to do is sort my archives page by name, but it should be ‘last_name’ in the case of ‘person’s and ‘org_name’ in the case of ‘org’s. There is no need to separate the two.

    What I would like to do is something like this:

    $type = 'partner_type';
    if $type = 'org':
    $name = 'org_name';
    elsif $type ='person'
    $name = 'last_name';  // The meta keys to sort on
    $args = array(
       'meta_key' => $name,
       'orderby' => 'meta_value',
       'order' => 'ASC',
    global $wp_query;

    1. I understand that ‘if..’ clause can’t possibly work— I include it to help clarify what I’m trying to accomplish.

    2. How can I make it work? I know just enough php that I can follow along, but not enough to generate a solution without a similar example.

  • What you’re trying to do can’t really be done, basically because sorting posts by two different meta keys and intermixing them in WP is beyond what WP is capable of. However, you can do this by saving the value of org_name in the last_name field when the post is saved.

    add_filter('acf/update_value/name=org_name', 'insert_org_into_last_name', 10, 3);
    function insert_org_into_last_name($value, $post_id, $field) {
        // replace the value of $last_name_field_key
        // with the field key of the last name field
        $last_name_key = "field_123456789ABCD";
        update_field($last_name_key, $value, $post_id);
        return $value;

    Now you can do a query and sort by last name. The value in last name will not be seen because it’s in a conditional field.

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

The topic ‘conditional sort’ is closed to new replies.