Skip Navigation

[Resolved] Can't order by meta field

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Tagged: 

This topic contains 1 reply, has 2 voices.

Last updated by Jamal 1 month ago.

Assigned support staff: Jamal.

Author
Posts
#1703265

Can someone please take a look at this code? It displays all the information I want it to display but not ordering.

<?php

$child_args = array(
'post_type' => 'city',
'numberposts' => 10,
'meta_key' => 'city_visits',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'toolset_relationships' => array(
'role' => 'child',
'related_to' => get_the_ID(),
'relationship' => 'state2city'
)
);

$query = new WP_Query( $child_args );

$child_posts = toolset_get_related_posts( get_the_ID(), 'state2city', array( 'query_by_role' => 'parent', 'return' => 'post_object' ) );

echo '<ul id="sidebar-pop-cities">';

foreach ($child_posts as $child_post)
{ ?>

  • <a href="<?php echo get_permalink($child_post->ID); ?>"><?php echo $child_post->post_title; ?></a>

  • <?php }

    echo '';

    ?>

    #1703461

    Jamal
    Supporter

    Languages: English (English ) French (Fran├žais )

    Timezone: Africa/Casablanca (GMT+01:00)

    Hello and thank you for contacting the Toolset support.

    The code seems correct to me, so I suppose that you have put a wrong meta_key name. If the field "city_visits" was created in Toolset, the meta key is most probably "wpcf-city_visits" because Toolset prefixes each custom field with "wpcf-", so when using WordPress API directly we'll need to add the prefix.

    Can you try it this way:

    $child_args = array(
      'post_type' => 'city',
      'numberposts' => 10,
      'meta_key' => 'wpcf-city_visits',
      'orderby' => 'meta_value_num',
      'order' => 'DESC',
      'toolset_relationships' => array(
        'role' => 'child',
        'related_to' => get_the_ID(),
        'relationship' => 'state2city'
      )
    );
    

    If this does not work, I'll need to check your website, and I'll need to know a test example(we expect to get ..., instead, we got ...) and I'll see what I can find.