Question

I want to fetch all posts whos terms matched the first two letters of the search letters. For example, I have terms 8027179, 8027180, 8247180. Now I want to assign letter 80 and fetch posts attached to 8027179 and 8027180. Let me know if need more explanation.

$args = array(
    'post_type' => 'tax-services',
    'order' => 'DESC',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'store_number',
            'field' => 'slug',
            'terms' => '80', //first letters of slug
        )
    )
);
Was it helpful?

Solution

Unfortunately, there doesn't appear to be a way grab terms "LIKE" a name or slug. See the Taxonomy Parameters in WP_Query. What we can do is break this up into two queries though.

  1. Get the term IDs by a partial slug match.
  2. Query posts assigned to those term IDs.

We can either do this with WPDB or get_terms(). I'd prefer WPDB since get_terms() does not have a slug__like parameter but a name__like. If that's fine then the call would look like this:

$terms_ids = get_terms( array(
    'taxonomy'      => 'store_number',
    'fields'        => 'ids',
    'hide_empty'    => false,
    'name__like'    => '80',
) );

If we want to grab specifically by slug we can use the following function:

/**
 * Grab term IDs by partial slug match
 * 
 * @param String $partial
 * @param String $taxonomy
 * 
 * @return Array $term_ids
 */
function wpse378026_term_ids_by_partial( $partial, $taxonomy ) {
    
    global $wpdb;
    
    $slug_like = $wpdb->esc_like( $partial ) . '%';
    
    $term_ids = $wpdb->get_col( $wpdb->prepare( "
        SELECT t.term_id
        FROM {$wpdb->terms} AS t
        INNER JOIN {$wpdb->term_taxonomy} AS tt ON t.term_id = tt.term_id
        WHERE t.slug LIKE %s AND
            tt.taxonomy = %s
    ",
        $slug_like,
        $taxonomy
    ) );
    
    return $term_ids;
    
}

// Function call
$term_ids = wpse378026_term_ids_by_partial( '80', 'store_number' );

We can then use the term IDs in the WP_Query like so:

$stores = new WP_Query( array(
    'post_type' => 'tax-services',
    'order'     => 'DESC',
    'posts_per_page' => -1,
    'tax_query' => array( array(
        'taxonomy'  => 'store_number',
        'field'     => 'term_id',
        'terms'     => $term_ids,
        'operator'  => 'IN',
    ) )
) );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top