Home › Forums › Front-end Issues › Query posts with tag specified by custom field
I have a profile page on which i want to show all posts with a the tag xy, that is specified in a custom field. I’m having trouble handing the String, which i got from the field over to the wp-query, which gives me the posts with the tag.
I have currently this to setup my query:
$original_query = $wp_query;
$tagstr = '' + the_field('usertag');
$wp_query = null;
$wp_query = new WP_Query( 'tag=$tagstr');
The akward thing is, that it outputs the String of the field itself onto the page sourcecode. I have no echo of the $tagstr variable and am not getting the value of the “usertag” field anywhere else on the page whatsoever, so i absolutely don’t know where this is coming from.
The funny thing is it works fine if i hardcode the String into my code like this:
$original_query = $wp_query;
$wp_query = null;
$wp_query = new WP_Query( 'tag=test');
I’m really confused about what is going wrong there…
Hi @flowbob,
That would be because the_field
echoes the output.
You want to use get_field
=> http://www.advancedcustomfields.com/resources/functions/get_field/
I tried
$original_query = $wp_query;
$tagstr = get_field('usertag');
echo $tagstr;
$wp_query = null;
$wp_query = new WP_Query( 'tag=$tagstr')
but it does nothing. (i echo’d $tagstr to check whether it’s the right value and it seems to be correct).
If echo $tagstr; shows a value, then it sounds like tag=$tagstr is just returning zero results.
“Tag=” can only look for tag slugs. Are you sure that the value of $tagstr is equal to the tag slug?
http://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters
Hi @flowbob
Becuase your WP_Query uses a literal string 'tag=$tagstr'
, the variable will not be converted.
If you wish to use the parameter in this manor, just cahnge to double quotes like so:
"tag=$tagstr"
You can also wrap variables like so:
"tag={$tagstr}"
Your best bet is to always use an array instead of a string. Also make sure you use the post_type param.
Thanks
E
@sdawson26 the tag was the right one the issue was the conversion of the string, as elliot pointed out.
@elliot this was exactly what solved the issue for me. thaks!
I should really try to lern PHP – at least the very basics like these datatypes…
I really appreciate the support you guys give here! It’s awesome.
And @elliot: the plugin and the page here is just plain awesome! Thanks!
The topic ‘Query posts with tag specified by custom field’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.