简体   繁体   中英

WP_Query by cat where cat comes from $_GET[] returns all post

I am trying to get all post of a cetegory throught a WP_Query:

//url whould be www.blablabla.com/?cat=4
$featured = new WP_Query('cat=$_GET["cat"]');

where cat is the Http GET param. This retuns all the post ignoring the "cat" parameter. But if I write an integer value instead of the $_GET I get the expected post, ie:

//This returns all the post of the category with slug = 4
$featured = new WP_Query('cat=4');

If I write $_GET["cat"] before then a 4 appears on screen. I supposse That WP_Query is getting the param as string and this is making the condition to be ignored, but I have try to cast in anyway the param but I can't get it to work. I am new to Wordpress so I am sure this is pretty much stupid.

Thanks in advance!

Try

$featured = new WP_Query('cat='.$_GET["cat"]);

The parameter you're passing to WP_Query is a single-quoted string. No variable interpolation is done on single-quoted strings, so you're actually passing the literal string cat=$_GET["cat"], when you want to pass cat=4

Are you sure $_GET["cat"] is giving you the expected value?

try: $cat = $_GET["cat"];//You should add validation here var_dump($cat);//just to check to see that the right value is there, remove this line when done $featured = new WP_Query("cat=$cat");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM