Get multiple posts by multiple slugs - wordpress

I have an array with multiple slugs (post names) and I want to get all posts where the slug is in the array.
I use Event Organsier and want to get all events these slugs. I haven't worked with WordPress for a couple of years so I need some help.
$events = eo_get_events(array(
'numberposts'=>5,
'event_start_after'=> $year.'-'.$month.'-'.$list_day,
'event_end_before'=> $year.'-'.$month.'-'.$list_day,
'showpastevents'=>false,//Will be deprecated, but set it to true to play it safe.
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array('slug-example-1', 'slug-example-2'),
'operator' => 'IN'
)
)
));
This should (imo) return all posts that has a slug that is slug-example-1 or slug-example-2.
I don't even know if tax_query/taxonomy is the right thing to use.

You can use the post_name__in argument in conjunction with get_posts(), it's available since Version 4.4.
E.g. :
$args = [
'post_name__in' => [ 'slug-1', 'slug-2' ],
'post_type' => 'page',
'post_status' => 'publish',
];
$result = get_posts( $args );

Related

Show related posts based on two custom taxonomies in WordPress - AND relationship issue

I have a custom post type "product", and two custom taxonomies: "productfamily" and "industry".
On my single product page, I need to show products that are in the same productfamily and industry.
Some products might be in a few different industries...and my related products section only needs to match one of the industries of the current post to show up.
Here's what I have so far...
$wp_query = new WP_Query(
array(
'posts_per_page' => '4',
'post_type' => 'product',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'productfamily',
'field' => 'slug',
'terms' => $prodfam,
'operator' => 'IN'
),
array(
'taxonomy' => 'industry',
'field' => 'term_id',
'terms' => $prodindustry,
'operator' => 'IN'
),
),
'orderby' => 'title',
'order' => 'ASC',
)
);
If I change the "AND" relation to "OR", it seems to partly work by showing products from the same "productfamily", but doesn't seem to be taking the "industry" into account at all.
How can I get this to show related products based off of my two custom taxonomies please? Thanks in advance for your help.
As you described in comment that you have slugs array in variables but in one of your tax query condition, you've used term_id to match with slug. that is incorrect.
You can directly use the terms ids instead of slugs since it's dynamic things. in function wp_get_post_terms you can pass array( 'fields' => 'ids' ) as 3rd param and it will give you array of ids. so you don't have make an extra loop.
Then you'll have to check both terms array if they both are empty of one of them or both of them as values?
then you can check them individually and then add the tax query part if ids are available.
This is how you can write the code in a clean way with proper checks:
global $post;
// Get the terms ids array,
// we can pass 'fields' => 'ids' in 3rd param so we don't need to run the loop to collect ids.
$product_family_ids = wp_get_post_terms( $post->ID, 'productfamily', array( 'fields' => 'ids' ) );
$industry_ids = wp_get_post_terms( $post->ID, 'industry', array( 'fields' => 'ids' ) );
// Prepare query args.
$query_args = array(
'posts_per_page' => '4',
'post_type' => 'product',
'orderby' => 'title',
'order' => 'ASC',
'tax_query' => array(
'relation' => 'AND',
),
);
// We need to check if both ids are not empty.
// if both empty we don't wanna run query.
if ( ! empty( $product_family_ids ) || ! empty( $industry_ids ) ) {
// If product family terms are available.
if ( ! empty( $product_family_ids ) ) {
$query_args['tax_query'][] = array(
'taxonomy' => 'productfamily',
'field' => 'term_id',
'terms' => (array) $product_family_ids,
'operator' => 'IN',
);
}
// If industry terms are available.
if ( ! empty( $industry_ids ) ) {
$query_args['tax_query'][] = array(
'taxonomy' => 'industry',
'field' => 'term_id',
'terms' => (array) $industry_ids,
'operator' => 'IN',
);
}
$related_posts = new WP_Query( $query_args );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) {
$related_posts->the_post();
/**
* DO you thing here.
*/
}
}
wp_reset_postdata();
}
Note: I have not tested the code so there might be syntax errors, if you use the code and find errors after using the code please let me know so that I could fix errors in my answers. Also, Make sure you have site backup and FTP access to fix the errors, Don't add code from WordPress backend

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

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!
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/
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();

Woocommerce Get all product variations by category

I need to get all Woocommerce product variations that belongs to selected category. I tried to query that this way:
$args = array(
'post_type' => 'product_variation',
'post_status' => array( 'private', 'publish' ),
'tax_query' => array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $selected_category_id
)
);
$variations = get_posts( $args );
but "tax_query" part seems to be ignored and no matter what will be provided inside, it does not affect the query.
Any ideas how to do that?
Tax Query Docs
Important Note: tax_query takes an array of tax query arguments arrays
(it takes an array of arrays). This construct allows you to query
multiple taxonomies by using the relation parameter in the first
(outer) array to describe the boolean relationship between the
taxonomy arrays.
I suggest you to use new WP_QUERY() instead get_posts() using WP_QUERY you can see query ran against your arguments via var_dump($variations->request);
$args = array(
'post_type' => 'product_variation',
'post_status' => array('private', 'publish'),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $selected_category_id
)
)
);
$variations = new WP_Query($args);
var_dump($variations->request); // dump SQL query

Can't get tax_query to work

I have a custom WP Query where I list custom post types. I am trying to set up filters to filter listings by custom taxonomy.
My query setup is as follows:
// WP_Query arguments
$args = array (
'post_type' => 'opps',
'post_status' => 'publish',
'pagination' => true,
'posts_per_page' => $postsperpage,
'posts_per_archive_page' => $postsperpage,
'ignore_sticky_posts' => true,
'order' => 'DESC',
'orderby' => 'date',
'cache_results' => true,
'update_post_meta_cache' => true,
'update_post_term_cache' => true,
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'sector',
'field' => 'slug',
'terms' => 'business-services'
),
)
);
So in the above example I should get only posts with taxonomy 'sector' with slug 'business-services', but ALL posts from custom post types 'opps' get listed instead.
I have looked everywhere on stackoverflow and beyond but I just can't figure out what I've been doing wrong.
Your code looks fine.
I have had this issue before because wordpress does not sync taxonomy terms until late in the init phase. Have you tried running this code in a template, after get_header() or wp_head() has been called? If not try that, it should work then. I know if I've echoed it out in functions.php for testing it will not work because wordpress has not synced tax terms yet.
You should really have a look at the codex (WP_Query) when creating custom queries. As your code stands, it will fail. You have the following issues
pagination is not a valid parameter for WP_Query.
You cannot use posts_per_page and posts_per_archive_page together
You don't need to set parameter values that are set by default. Unnecessary parameters used in your code which is by default the default values are order, orderby, post_status, cache_results, update_post_meta_cache and update_post_term_cache
There is no sticky post functionality for custom post types. just remove the ignore_sticky_post parameter
Your code should look something like this ( I hope your variables is defined )
// WP_Query arguments
$args = array (
'post_type' => 'opps',
'posts_per_page' => $postsperpage,
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'sector',
'field' => 'slug',
'terms' => 'business-services'
),
)
);

Only show WordPress 'standard' post format on template?

I recently added post formats to my WordPress theme - on the blog page its fine as they are all styled accordingly. However on my home page template I only want to show 'standard' posts formats (no links, galleries, audio, video etc.).
In my theme options I can decide how many posts to display on the front page which is what 'dft_recent_number' is for.
Does anybody know how I can change the code below to exclude all but 'standard' post formats?
<?php
$query = new WP_Query();
$query->query('posts_per_page='.get_option('dft_recent_number'));
//Get the total amount of posts
$post_count = $query->post_count;
while ($query->have_posts()) : $query->the_post();
?>
Any help is much appreciated!
WP_Query does not seem to have a straightforward parameter for post_format.
From my quick research it appears that post formats are related through taxonomies. So, theoretically, using the taxonomy parameters should work.
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => 'post-format-standard',
)
)
);
$query = new WP_Query( $args );
Note: you'll need to update the taxonomy names and slugs for your blog. This should be the names you set in your functions.php file.
// there's no post-format-standard so you should write it like this to exclude all other postpformats
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array('post-format-quote','post-format-audio','post-format-gallery','post-format-image','post-format-link','post-format-video'),
'operator' => 'NOT IN'
)
I know that's old, but I was facing the same issue and even though I've found a solution I wondered what other have done to "fix" that.
I think a more scalable solution could be something like that:
$post_formats = get_theme_support( 'post-formats' );
$tax_query = false;
if ( $post_formats ) {
$tax_query = array(
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => $post_formats[0],
'operator' => 'NOT IN'
)
);
}
// WP_Query arguments
$args = array(
'post_type' => 'post',
'order' => 'DESC',
'orderby' => 'date',
'tax_query' => $tax_query
);
This would exclude the post formats that have been enabled and also will work in case WP will add more post formats (or add the ability to add more).

Resources