Custom SQL Query on Custom Post Type. Order by Taxonomy?

Just looking at the term_taxonomy table, you are selecting everything correctly, but the last part:

WHERE $wpdb->posts.post_type="publications"
AND $wpdb->terms.slug = %s
AND $wpdb->term_taxonomy.taxonomy = 'category'
ORDER BY $wpdb->term_taxonomy.taxonomy = 'topics' DESC

from the post_type of publications, the terms slug of %s, and has the taxonomy of categories, but you are never selecting the taxonomy topics. If you look at the table, you have one column reading taxonomy. In this column, you can either have category or topics. This is an example of two rows (plus the header):

<tr>
    <td>term_taxonomy_id</td>
    <td>term_id</td>
    <td>taxonomy</td>
    <td>description</td>
    <td>parent</td>
    <td>count</td>
</tr>
<tr>
    <td>1</td>
    <td>1</td>
    <td>category</td>
    <td>This is the description for the category taxonomy</td>
    <td>0</td>
    <td>1</td>
</tr>
<tr>
    <td>1</td>
    <td>1</td>
    <td>topics</td>
    <td>This is the description for the topics taxonomy</td>
    <td>0</td>
    <td>1</td>
</tr>

(I put it in tabular notation to express it easier)

try throwing the topics into the select query, then sorting by it:

WHERE $wpdb->posts.post_type="publications"
AND $wpdb->terms.slug = %s
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->term_taxonomy.taxonomy = 'topics'
ORDER BY $wpdb->term_taxonomy.taxonomy = 'topics' DESC

Leave a Comment