The Support Forums will be in read-only mode for a scheduled maintenance window on 01 September 2016 14:00 UTC - 20:00 UTC. More information.

query taxonomy less than a value (2 posts)

  1. jakehuffman
    Posted 3 years ago #

    I have a custom taxonomy (delay) associated with a custom post type (article). I am trying to figure out a good way to build the query without resorting to building the query in sql. All of the content of delay is captured as integers, so the following query does work, but i'm looking for a better solution that keeps with the spirit of using wp_query.

    $querystr = 'SELECT wp_posts.* FROM wp_posts
                        INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
                        INNER JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
                        INNER JOIN wp_terms ON (wp_term_taxonomy.term_id = wp_terms.term_id)
                        WHERE 1=1
                        AND wp_posts.post_type = \'article\'
                        AND (wp_posts.post_status = \'publish\')
                        AND (wp_term_taxonomy.taxonomy = \'delay\')
                        AND (CAST(wp_terms.name AS SIGNED) <= ' . $dayCount . ')
                        ORDER BY (CAST(wp_terms.name AS SIGNED)) ASC
                        LIMIT 0, 150';

    plus it doesn't play well with paging as it stands right now.

  2. ianhaycox
    Posted 3 years ago #

    You could try the posts_clauses filter,

    function add_article_tax_query($clauses, $wp_query) {
      global $wpdb;
      if ( !is_admin() && $wp_query->is_main_query() ) {
        // Only need this CPT
        if ( is_post_type_archive( 'article' ) ) {
          $clauses['join'] .= " INNER JOIN {$wpdb->term_relationships} ON ...";
          $clauses['fields'] .= ",{$wpdb->terms}.name AS term_name";
          $clauses['where'] .= " AND ({$wpdb->term_taxonomy}.taxonomy = ...";
          $clauses['orderby'] .= "(CAST({$wpdb->terms}.name AS SIGNED)) ASC";
      return $clauses;
    add_filter('posts_clauses','add_article_tax_query', 10, 2);

    Then the loop for the custom post type article uses wp_query with all the extra joins, fields, etc. specified above.

    Untested, but something like that.


Topic Closed

This topic has been closed to new replies.

About this Topic