Support

Account

Home Forums ACF PRO How to order post by custom fields count

Solving

How to order post by custom fields count

  • Situation: I have a custom post type with a Relational Field which links these posts to another custom post type. I use the first type to let the users upload their pictures of their favourite team, the second type is for the teams. Each picture can be linked to more than one team.

    What I need: a sort of chart that shows the teams with much pictures in descending order

    With the following code I can get teams and number of picture but I can’t order them. Can anybody help me?

    // WP_Query arguments
    $args = array (
        'post_type'              => array( 'squadre' ),
        'post_status'            => array( 'publish' ),
        'pagination'             => false,
    );
    
    // The Query
    $query = new WP_Query( $args );
    
    // The Loop
    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
    
        $teams = get_posts(array(
                'post_type' => 'tifo',
                'meta_query' => array(
                    array(
                        'key' => 'tifosquadra', // name of custom field
                        'value' => '"' . get_the_ID() . '"',
                        'compare' => 'LIKE'
                    )
                )
            ));
    
            ?>
            <?php if( $teams ): ?>
                <?php 
                    $count = count($teams);
                    echo the_title().': '.$count.'<br>';
                    ?> 
            <?php endif; ?>

    (forgive my bad English)

  • Hi,

    I don’t think there’s a way you can do this easily with the current way you’re doing things but maybe..

    I have a little bit of a hard time wrapping my head around what exactly you want to display. You want to show a list of posts “squadre” with the post title + a number of how many of post “tifo” is connected to this post? And show all of these ordered by how many “tifo” posts are connected to each “squadre”?

  • Yes, Jonathan.
    This is exactly what I need to display.

    Any idea?

  • Hi @francescomac

    Do you still require help with this? I’ve been away a few days 🙂

  • Thank you Jonathan. I was away.
    Yes I still need help, I’m trying to find another solution but with no success ’til now. 🙁

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

The topic ‘How to order post by custom fields count’ is closed to new replies.