skip to Main Content

I have the following query that bring the posts that contain a specific word in the title

SELECT posts_post.ID AS post_ID,
       posts_post.post_date AS post_post_date,
       CONCAT('<a href="',posts_post.guid,'">',posts_post.post_title,'</a>') AS post_title_with_link_to_post
FROM wp_posts AS posts_post
WHERE 1=1 
  AND posts_post.post_title LIKE '%HOTARAR%'
  AND posts_post.post_type = 'post'
GROUP BY post_post_date

The problem now is that I need to bring the posts only from a specific category (tag slug for the category is hotarari-consiliu-local and has the ID 160), how could I modify the above query to bring posts only from a single blog posts category? Thanks!

2

Answers


  1. Try the below query.

    global $wpdb;
    $make = $wpdb->get_results("
        SELECT * FROM 
            $wpdb->posts
        LEFT JOIN 
            $wpdb->term_relationships 
        ON
            ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
        LEFT JOIN 
            $wpdb->term_taxonomy 
        ON
            ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
        WHERE 
            $wpdb->posts.post_type = 'post'
        AND 
            $wpdb->posts.post_title LIKE '%HOTARAR%'
        AND 
            $wpdb->term_taxonomy.taxonomy = 'category'
        AND 
            $wpdb->term_taxonomy.term_id = 160
        ORDER BY 
            post_date DESC
    ");
    
    Login or Signup to reply.
  2. Assuming Bhautik is on the right path, then something like this should work (I don’t know where ‘hotarari-consiliu-local’ belongs in this).

       SELECT p.ID post_ID
            , p.post_date post_post_date
            , CONCAT('<a href="',p.guid,'">',p.post_title,'</a>') post_title_with_link_to_post
         FROM wp_posts p
         JOIN wp_term_relationships pt
           ON pt.object_id = p.ID 
         JOIN wp_term_taxonomy t
           ON t.term_taxonomy_id = pt.term_taxonomy_id 
        WHERE p.post_type = 'post'
          AND p.post_title LIKE '%HOTARAR%'
          AND t.taxonomy = 'category'
          AND t.term_id = 160
        ORDER 
           BY  post_date DESC
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search