Order a WP_Query by a custom field that don´t exist in the query (2 posts)

  1. roxperez
    Posted 1 year ago #

    I have some problems trying to order a WP_Query, maybe someone can help me.

    I´ve created a wp_query, the post_type is a custom post type from a plugin, so I cannot modify it.

    I need to add an extra field to each post so I´ve done this (don´t know if this is correct):

    while ( $query->have_posts() ) : $query->the_post();
    $query->post->total = get_total(); endwhile;

    Here I add an extra field "total" to the posts array.

    The problem is that now I need to order the posts by this field (total) and I don´t know how to do it.

    I´ve tried with get_posts, pre_get_posts but nothing works.

    Can anyone help me? Thanks in advance

  2. ajmcfadyen
    Posted 1 year ago #

    $args = array(
    'post_type' => 'the_posttype',
    'meta_key' => 'priority_customfield',
    'orderby' => 'meta_value_num',
    'order' => 'ASC'
    $query = new WP_Query($args);

Topic Closed

This topic has been closed to new replies.

About this Topic