Home > Blockchain >  In WordPress, get all posts having keyword in Title, Tag or Category?
In WordPress, get all posts having keyword in Title, Tag or Category?

Time:08-08

My question is similar to this one, but it's now 7 years old, so I thought I'd ask again.

I'm using the get_posts() function but it seems that whatever is passed as the 's' parameter is only matched against the post title. For example, this code only returns posts containing 'sunflower' in the title, not posts containing 'sunflower' in one of their tags

$args = array(  'numberposts' => 99,  's' => 'sunflower'); 
$postslist = get_posts( $args );  

I'm just starting out with WP development, so maybe I'm overlooking something or using the wrong function... Any pointers will be greatly appreciated!

CodePudding user response:

To additionally get posts with 'sunflower' as a tag you need to add taxonomy parameters like so:

$args = [
'numberposts' => 99,
's' => 'sunflower',
'tax_query' => [
        [
            'taxonomy' => 'post_tag',
            'field'   => 'slug',
            'terms'   => 'sunflower'
        ]
    ]
]; 

$postslist = get_posts( $args );

Official docs: https://developer.wordpress.org/reference/functions/get_posts/

CodePudding user response:

IMHO this is much more complicated than it should be, but I managed to get what I want with the following code:

$searchTerm =  trim($_REQUEST['search']);

// Get all slugs that are a partial match in tags
$matching_terms_tags = get_terms( array(  'taxonomy' => 'post_tag',  'fields' => 'slugs', 'name__like' => $searchTerm ) );

// Get all slugs that are a partial match in categories
$matching_terms_categories = get_terms( array( 'taxonomy' => 'category',  'fields' => 'slugs', 'name__like' => $searchTerm ) );                       

// Build taxonomy query 
$argsTax = array('numberposts' => 999, 'posts_per_page' => -1, 'nopaging' => true);
$argsTax['tax_query'] = array 
        (
            array
            (
                'relation' => 'OR',
                array ('taxonomy' => 'category', 'field' => 'slug', 'terms'    => $matching_terms_categories,'operator' => 'IN',),
                array ('taxonomy' => 'post_tag', 'field' => 'slug', 'terms'    => $matching_terms_tags, 'operator' => 'IN', ),
            ),
        );            

// Get all posts with matching tags and/or matching categories
$postsTax = get_posts($argsTax);

// Also get all posts matching the term, using the regular WP argument 's'
$argsTerms = array('numberposts' => 999, 'posts_per_page' => -1, 'nopaging' => true, 's' => $searchTerm);
$postsSearch = get_posts($argsTerms);

// Merge the 2 result sets and remove duplicates            
$postsAll = array_merge($postsSearch, $postsTax);            
$postAllNoDupes = array_map("unserialize", array_unique(array_map("serialize", $postsAll)));

foreach ($postAllNoDupes as $post)
{
    echo get_the_title($post);
}

wp_reset_query(); 
  • Related