Fetch posts that match term slug first two letters (wp query)

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',
    ) )
) );