Note that there are some explanatory texts on larger screens.

plurals
  1. POwordpress query with custom fields help
    text
    copied!<p>My posts have a bunch of custom fields and are currently being ordered by "over-lenght"</p> <p>I have another custom field called "over-lenghtin".</p> <p>I'd like to continue to order my posts by over-lenght but if 2 posts had the same value for this field I'd like to also order them by over-lengthin.</p> <p>I'm wondering how I can modify my query or add a function to execute this?</p> <p>Here's by current query</p> <pre><code>$loop = new WP_Query( array ( 'post_type' =&gt; 'new', 'orderby' =&gt; 'meta_value_num', 'meta_key' =&gt; 'over-length', 'meta_query' =&gt; array( array( 'key' =&gt; 'over-make', 'value' =&gt; 'Doral', 'compare' =&gt; 'LIKE') ) ) ); </code></pre> <p>Ok so I've rewritten by query to use $wpdb->get_results, but I'm still a bit confused on how to go about ordering by 2 different custom fields.</p> <p>Here's my new query:</p> <pre><code>$wpdb-&gt;get_results("SELECT * FROM $wpdb-&gt;posts, wp_postmeta WHERE wp_posts.ID = wp_postmeta.post_id AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'new' AND wp_postmeta.meta_value = 'Doral' ORDER BY"); </code></pre> <p>Now I need to order by my custom fields 'over-length' and then 'over-lengthin'</p> <p>I seem to have this working now, here's my final query:</p> <pre><code>$wpdb-&gt;get_results("SELECT * FROM $wpdb-&gt;posts LEFT JOIN $wpdb-&gt;postmeta AS overlength ON( $wpdb-&gt;posts.ID = overlength.post_id AND overlength.meta_key = 'over-length' ) LEFT JOIN $wpdb-&gt;postmeta AS overlengthin ON( $wpdb-&gt;posts.ID = overlengthin.post_id AND overlengthin.meta_key = 'over-lengthin' ) LEFT JOIN $wpdb-&gt;postmeta AS overmake ON( $wpdb-&gt;posts.ID = overmake.post_id AND overmake.meta_key = 'over-make' ) WHERE wp_posts.post_status = 'publish' AND wp_posts.post_type = 'new' AND overmake.meta_value = 'Doral' ORDER BY 0+overlength.meta_value DESC, 0+overlengthin.meta_value DESC"); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload