Support

Account

Home Forums General Issues How do I get PHP function to affect what’s displayed on my page?

Helping

How do I get PHP function to affect what’s displayed on my page?

  • I’ve found all kinds of posts about how to create the PHP functions to achieve various results when outputting ACF data. I’ve had some success getting this to work with Gravity Forms. However, I am stumped on how to get the desired output in my pages (created with Elementor). I assume the php for various actions should be saved in functions.php. However, I’m not sure about the steps between the function(s) and the output on the page. Below is one of the uses I am working with.

    I have a post archive called Staff Members Archive which pulls in the ACF posts for my Staff type. However, I am trying to sort the archive by Last Name (Ulitimately I want to sort by Department, Position, and Last Name).

    My archive is pulling in the desired records from the Staff Member post type, but they are ordered by date.

    I’ve included the following function below in my functions.php file. However, I’m not sure if this is even correct, or how to get it to apply to the Staff Members Archive. My post type is “Staff Members”.

    I am working with Elementor and the loop/archive elements. Everything is working well except the sorting.

    
    function sort_staff( $query ) {
        
        // do not modify queries in the admin
        if( is_admin() ) {
            
            return $query;
            
        }
        
        // only modify queries for 'staff' post type
        if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'Staff Member' )  {
            
            $query->set('orderby', 'meta_value');    
            $query->set('meta_key', 'lname');    
            $query->set('order', 'ASC'); 
            
        }
        
        // return
        return $query;
    
    }
    add_action('pre_get_posts', 'sort_staff');
    

    If I was doing this in SQL, my query would be

    SELECT * FROM Staff 
    WHERE active='Active'
    ORDER BY FIELD(Department,'Admin','Fiscal', 'Maintenance'), 
    FIELD(Position, 'Manager', 'Supervisor', 'Staff'), 
    lname ASC;
  • ACF does not work directly with page builders.

    For elementor you either need to get the pro version that has ACF integration for most fields, use the ACF shortcode for simple fields or build your own shortcode for complex fields.

    Something like a pre_get_posts query should work as usual placed in your functions.php file.

    This part of your code looks to be incorrect

    
    $query->query_vars['post_type'] == 'Staff Member'
    

    You need to post type name there, not the label.

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

You must be logged in to reply to this topic.