someone please help me 🙂
So, here’s the situation: I’m using WordPress, and within it, there’s a query I’ve created using the Code Snippet plugin.
Plugins used:
Product: WooCommerce
Custom fields & custom posts: Secure Custom Fields Code
Snippet: Code Snippet PHP
Here’s my current code:
function my_query_by_post_types1( $query ) {
if ( is_product() && $query->is_main_query() ) {
$term_names = wp_get_post_terms( get_the_ID(), 'product_cat', array( 'fields' => 'names' ) );
if ( $term_names ) {
$query->set( 'post_type', 'news' );
$meta_query = array( 'relation' => 'OR' );
foreach ( $term_names as $term_name ) {
$meta_query[] = array(
'key' => 'product_category', // The meta key for the custom field in "news"
'value' => $term_name,
'compare' => 'LIKE',
);
}
$query->set( 'meta_query', $meta_query );
}
}
}
add_action( 'elementor/query/product_related_news', 'my_query_by_post_types1' );
This query is intended to be used on the single product page to display “news” (custom post type). The “news” post type has a custom field, which is a checkbox field named product_category. The goal is to display “news” posts on the single product page that have the same product_category as the product’s category.
The code snippet I created successfully displays the news section on the single product page. However, it displays all news items from the database instead of filtering them based on the product category. For instance, although the product being displayed belongs to the “Computer” category and the news section includes custom fields with a return value of “Computer,” the filtering mechanism does not function as intended. Consequently, all news items are shown, regardless of their associated product categories.
I have tried several methods:
- Using taxonomy instead of custom fields as categories for the custom post type “News” that I created.
- Using
"fields => name"
to retrieve the names from the array generated bywp_get_post_terms
.
Custom Posts Fields
Custom Field Settings