skip to Main Content

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:

  1. Using taxonomy instead of custom fields as categories for the custom post type "News" that I created.
  2. Using "fields => name" to retrieve the names from the array generated by wp_get_post_terms.

Custom Posts Fields

Custom Field Settings

I have tried debugging using the code below, but no posts matching the filter I created were found. Even though I have added a news post with a product category exactly the same as the product i am displaying.

function my_query_by_post_types1($query) {
   if (is_singular('product')) {
       // Get product categories
       $terms = get_the_terms(get_the_ID(), 'product_cat');
       
       if ($terms && !is_wp_error($terms)) {
           // Get all category names
           $category_names = array();
           foreach ($terms as $term) {
               $category_names[] = $term->name;
           }
           
           if (!empty($category_names)) {
               $query->set('post_type', 'news');
               $query->set('meta_query', array(
                   array(
                       'key'     => 'product_category',
                       'value'   => $category_names,
                       'compare' => 'IN'
                   )
               ));
               
               // Debug output for admins
               if (current_user_can('administrator')) {
                   echo '<div style="background: #f1f1f1; padding: 10px; margin: 10px;">';
                   echo 'Categories found: ' . implode(', ', $category_names) . '<br>';
                   // Debug the query object
                   echo 'Query object:<pre>';
                   print_r($query->query_vars); // Outputs query parameters
                   echo '</pre>';
                   
                   if ($query->have_posts()) {
                        while ($query->have_posts()) {
                            $query->the_post();
                            echo get_the_title() . '<br>';
                        }
                    } else {
                        echo 'No posts found!';
                    }
                   
                   echo '</div>';
               }
           }
       }
   }
}
add_action('elementor/query/product_related_news', 'my_query_by_post_types1');

debugging output

example of a news post I have created

2

Answers


  1. Chosen as BEST ANSWER

    The issue has been resolved. This code snippet may be helpful to others who encounter similar problems.

    function my_query_by_post_types1($query) {
       if (is_singular('product')) {
           // Get product categories
           $terms = get_the_terms(get_the_ID(), 'product_cat');
           
           if ($terms) {
               // Get all category names
               $category_names = wp_list_pluck($terms, 'name');
               
               if ($category_names) {
                   $query->set('post_type', 'news');
                   $query->set('meta_query', array(
                       array(
                           'key'     => 'product_category',
                           'value'   => '"' . implode('","', $category_names) . '"',
                           'compare' => 'LIKE'
                       )
                   ));
               }
           }
       }
    }
    add_action('elementor/query/product_related_news', 'my_query_by_post_types1');
    
    

  2. Because you are referencing multiple values for the same meta_key, you can use the ‘IN’ compare value, and you can put all of the values for that meta_key in an array.

    You do not need to add multiple items in the meta_query array for this implementation.

    Here is the modified code below, from your example:

    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(
            'key'     => 'product_category', // The meta key for the custom field in "news"
            'value'   => $term_names, // Use the $term_names array here instead of looping through it   
            'compare' => 'IN', // Use 'IN' and not 'LIKE' for the array value
          );
    
          $query->set( 'meta_query', $meta_query );
        }
      }
    }
    add_action( 'elementor/query/product_related_news', 'my_query_by_post_types1' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search