0

I am using wordpress and I have an SQL statement (as below) to gather the tags for a specific category. The only issue with this is that the table names may change (i.e. they will not always be wp_*). The function $pfx = $wpdb->base_prefix; returns what the wordpress database prefix is.

How can I use $pfx inside my SQL statement below (instead of wp_ ).

global $wpdb;
$tags = $wpdb->get_results
("
SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name, null as tag_link, t2.count as post_total
    FROM
        wp_posts as p1
        LEFT JOIN wp_term_relationships as r1 ON p1.ID = r1.object_ID
        LEFT JOIN wp_term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
        LEFT JOIN wp_terms as terms1 ON t1.term_id = terms1.term_id,

        wp_posts as p2
        LEFT JOIN wp_term_relationships as r2 ON p2.ID = r2.object_ID
        LEFT JOIN wp_term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
        LEFT JOIN wp_terms as terms2 ON t2.term_id = terms2.term_id

    WHERE
        t1.taxonomy = 'category' AND p1.post_status = 'publish' AND terms1.term_id IN (".$args['categories'].") AND
        t2.taxonomy = 'post_tag' AND p2.post_status = 'publish'
        AND p1.ID = p2.ID
    ORDER BY post_total DESC
");

Thanks.

1 Answer 1

1

Change for example

LEFT JOIN wp_term_relationships 

into

LEFT JOIN ".$pfx."term_relationships 
Sign up to request clarification or add additional context in comments.

7 Comments

Sorry, I got the quotes wrong, since you are using double quotes. Corrected.
Thanks, but I'd already tried with double quotes, and again it still doesn't work. I'm not really sure what's going on..
Have you made sure that $pfx actually contains a value, and that the table specified actually exists? Also, do you receive any errors when you do it? Just saying that it "doesn't work" doesn't help us help you.
Yes I can verify that variable $pfx does contain the correct database prefix. However, the query is actually a function to which a category ID is passed and (if it all works), said category's tags are returned. However after changing the wp_ with ".$pfx." the function does not return any tags when used.
You did set $pfx inside the function and dumped its content there, too, didn't you?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.