Reputation: 497
My WordPress site needs to have a different RSS feed on every page. In the short-term, I need to find a way to output an RSS feed with category = "2" (which will later become a number from different pages). I'm relatively new to PHP though.
Is there a way to get a variable echo'd WITHIN an echo?
I've tried:
<?php
$category = '2';
echo do_shortcode('[rssfeed cat="$category"]');
?>
and
<?php
$category = '2';
echo do_shortcode('[rssfeed cat='echo "$category"']');
?>
... But obviously they don't work. Can anyone suggest a work-around? Thanks
Upvotes: 0
Views: 141
Reputation: 497
Rizier123's answer above worked great:
<?php
$category = '2';
echo do_shortcode("[rssfeed cat='" . $category . "']");
?>
I actually needed to pull a value from each WordPress page through Advanced Custom Fields, using the_field(category). When I tried to do:
<?php
$category = the_field(category);
echo do_shortcode("[rssfeed cat='" . $category . "']");
?>
It didn't work - even though
echo $category;
produced the right value. Lots of suggested variations didn't work either - possibly this is a problem with Wordpress. I figured I needed to somehow pass a printed value of a variable into another variable, for it to work. For anyone trying to do what I was doing, a solution I found that worked is:
<?php
function abc(){
print the_field(category);
}
ob_start();
abc();
$category = ob_get_clean();
echo do_shortcode("[rssfeed cat='" . $category . "']");
?>
Upvotes: -1
Reputation: 326
You can adapt your first attempt but swap the " and ' around - variables will be parsed if you use double quotes http://php.net/manual/en/language.types.string.php#language.types.string.parsing
<?php
$category = '2';
echo do_shortcode("[rssfeed cat='$category']");
?>
Upvotes: 2
Reputation: 38238
Variable interpolation only happens between double quotes. But shortcodes can use either single or double quotes for their attributes, so if you put your quotes the other way around, it should just work:
<?php
$category = '2';
echo do_shortcode("[rssfeed cat='$category']");
?>
The PHP string now has double quotes, so $category
will be interpolated to its value, and the attribute has single quotes, which will still work fine ("Shortcode macros may use single or double quotes for attribute values"), and not terminate the enclosing PHP string.
Upvotes: 1
Reputation: 59691
You can just concatenate your strings like this:
$category = '2';
echo do_shortcode("[rssfeed cat='" . $category . "']");
Upvotes: 4