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

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x