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
You can just concatenate your strings like this:
$category = '2';
echo do_shortcode("[rssfeed cat='" . $category . "']");
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']");
?>
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.
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 . "']");
?>
Related
I am convinced that the solution is very simple, however I have searched many pages and questions and I am slightly frustrated with the lack of solution.
I'm trying to create a span element which has the onclick property.
The onclick event should pass to the displayStory function path to the text file.
Unfortunately, all slashes are missing.
Slashes are fine if I dont use apostrophes inside $dir, however i have to insert them somehow
PHP:
<?php
$allStories = scandir("./stories");
foreach($allStories as $story){
$dir = "'/stories/$story'";
$element = ("<span class='listElement' onclick='displayStory($dir)'>$story</span>");
echo $element;
}
?>
Output:
<span class="listElement" onclick="displayStory(" stories="" example.txt')'="">example.txt</span>
You need to learn how to escape characters:
<?php
$allStories = scandir("./stories");
foreach($allStories as $story){
// No single quotes here
$dir = "/stories/$story";
// No parenthesis needed to assign a value
// Escape double quotes for attributes preceding them with a backslash \"
// Use single quotes for function parameter
$element = "<span class=\"listElement\" onclick=\"displayStory('$dir');\">$story</span>";
echo $element;
}
?>
Output should be:
<span class="listElement" onclick="displayStory('stories/example.txt');">example.txt</span>
I am trying to redirect a page to:
product_page.php?rest_id=$rest_id&area=$rest_city
for example:
product_page.php?rest_id=3&area=Enfield
At the moment the page is redirecting to:
http://localhost/PhpProject2/product_page.php?rest_id=&area=
Even though i have specified :
if (isset($_GET['rest_id'])){
$rest_id = mysqli_real_escape_string($dbc,$_GET['rest_id']);
}
if (isset($_GET['area'])){
$area = mysqli_real_escape_string($dbc,$_GET['area']);
}
if (isset($_GET['add_item'])) {
(int)$_GET['add_item']]){
$_SESSION['Shopping_cart_' . (int) $_GET['add_item']]+='1';
//redirect
echo"<script>window.open('product_page.php?rest_id=$rest_id&area=$rest_city','_self')</script>"; //header does not work
}
How would i go about getting the echo to re-direct to the correct page.
What i have tried:
Calling both add_item, rest_id and rest_city in the same if asset.
Moving the $_GET rest_id and rest_city closing tag after the echo.
The two above options just stop the page from re-directing all together, this is my first time doing this, any suggestions or tips would be greatly appreciated.
You should use double qotes ["string $variable string"] for variable to work inside a string or if not you should concatenate the string with [.] sign.
echo"<script>window.open('product_page.php?rest_id=$rest_id&area=$rest_city','_self')</script>";
This will not work because of single qoute [']
Regards
There are many syntax errors in your code. Also, the way you echo the string is wrong. You need to concat the variables with the string, using the PHP concatenation operator, else use double quotes.
Below fixed your errors:
if (isset($_GET['rest_id'])){
$rest_id = mysqli_real_escape_string($dbc,$_GET['rest_id']);
}
if (isset($_GET['area'])){
$area = mysqli_real_escape_string($dbc,$_GET['area']);
}
if (isset($_GET['add_item'])) {
$_SESSION['Shopping_cart_'] = (int) $_GET['add_item']+='1';
echo"<script>window.open('product_page.php?rest_id=" . $rest_id . "&area=" . $rest_city . "','_self')</script>";
}
I am simply trying to echo or print out specific data from a DB into a string (i hope thats the right name), which should be a very simple process as I've done it before. The point is everytime a user inserts information into the database this string echo's or prints out the inserted data.
But for some very odd reason this time around when i try to echo out the data, I literally get this.
Very frustrating. As you can see from the image above i have tried using 2 different ways to do this a variable and a session, but the echo literally just prints it out. I have done this before so i am aware that it is possible. I am just a little lost into how i am meant to achieve this or even better where i went wrong. I know how to do this using a different style of coding, but i am trying to keep everything uniformed (newbie).
$addon_name = $_SESSION['Add_On_OpName'];
mysqli_report(MYSQLI_REPORT_INDEX); //overrid a common php nonsense error
$prod_sel = $dbc->query("SELECT * FROM Add_On WHERE Add_On_OpName = '$addon_name'");
$prod_sel->data_seek(0);
while ($output = $prod_sel->fetch_assoc()) {
$prod_run .= $output['Add_On_OpName'] . $output['Prod_Name'] . $output['Add_On_Price'] . $output['Add_On_Select'] . '<br>';
$addon = $output['Add_On_OpName']; //echo out product name
$_SESSION['Prod_Name'] = $output['Prod_Name']; //echo out product desc
$_SESSION['Add_On_Price'] = $output['Add_On_Price']; //echo out price
echo '
<p>$addon . " " . $_SESSION["Add_On_Price"]; </p>
';
My session is started and the php file is connected to the DB.
I also have error handling which has not given out any error messages.
You must do:
echo "<p>$addon ".$_SESSION["Add_On_Price"]."; </p>";
A string encapsulated into ' is rendered just as it is.
Use " to render a string that contains variables. Example:
$a = 3;
$a++;
echo "the result is $a";
will result in the result is 4.
On the other hand,
echo 'the result is $a';
gives the result is $a.
As the documentation points out:
Single quoted ¶ The simplest way to specify a string is to enclose it
in single quotes (the character ').
Doued ¶
If the string is enclosed in double-quotes ("), PHP will interpret
more escape sequences for special characters
Try not mix it..
And if within double quotes you have an associative array you may concat.
echo "string $variable". $array["index"];
or
echo "string $variable {$array["index"]}";
Then your code should look like
$addon_name = $_SESSION['Add_On_OpName'];
mysqli_report(MYSQLI_REPORT_INDEX); //overrid a common php nonsense error
$prod_sel = $dbc->query("SELECT * FROM Add_On WHERE Add_On_OpName = '$addon_name'");
$prod_sel->data_seek(0);
while ($output = $prod_sel->fetch_assoc()) {
$prod_run .= $output['Add_On_OpName'] . $output['Prod_Name'] . $output['Add_On_Price'] . $output['Add_On_Select'] . '<br>';
$addon = $output['Add_On_OpName']; //echo out product name
$_SESSION['Prod_Name'] = $output['Prod_Name']; //echo out product desc
$_SESSION['Add_On_Price'] = $output['Add_On_Price']; //echo out price
echo "<p>$addon {$_SESSION["Add_On_Price"]}; </p>'";
}
Long time ago
I never use double quotes due to it require parse the whole string for special notations. However it.
Try not mix single quotes with double quotes. pick up a standard for you code you will not notice any difference than is easy to code and read without surprises
You're mixing single quotes and double quotes. Single quotes do not perform interpolation of variables so when you write this:
echo '... whatever including " char and $ sign';
PHP will just literally print everything inside.
You forget some ' or " !
echo '<p>' . $addon . ' ' . $_SESSION["Add_On_Price"] . '</p>';
Use double quotes
echo "<p>$addon $_SESSION['Add_On_Price']; </p>";
I'm writing Wordpress page template that will get the page slug and use a WP_query to make a list of all posts with tag=page slug. My code doesn't throw up any errors but rather gives me an empty list, when there are definitely posts with the appropriate tag.
Code:
<?php
$tag = $post -> post_name;
$query = new WP_Query('tag = $tag');
while ($query -> have_posts()) {
$query -> the_post();
echo '<li>' . get_the_title() . '</li>';
}
?>
I'm using a local version of Wordpress 4.0.1 on Mac, Yosemite.
Any advice would be much appreciated,
Cheers!
This is a very common mistake (I've done this myself several times.) In PHP, variables substitution only works with strings that are bound by double quotes. Single quotes indicate literal strings. Try this:
$query = new WP_Query("tag = $tag");
or this:
$query = new WP_Query('tag = '.$tag);
More info on PHP strings: http://php.net/manual/en/language.types.string.php
I'm trying to pass GET variables inside the URL with a bit of html inside of my PHP but can't figure out the quotes situation. I need to embed two variables inside the URL. I have one in but don't know how to embed the other. Here is the string:
echo "<a href='?id=".($id-1)."' class='button'>PREVIOUS</a>";
and here is what I need to go inside
&City=$City
Thanks for the help
Its pretty simple,
echo "<a href='?id=".($id-1)."&city=" . $City . "' class='button'>PREVIOUS</a>";
In php double quotes "" can eval variables inside them.
$test = "123;"
echo "0$test456"; // prints 0123456
In your case you better use single quote ''.
echo '<a href=\'?id=' . ($id-1) . '&City=' . $City . '\' class=\'button\'>PREVIOUS</a>';
or better
echo 'PREVIOUS';
Use something like this:
echo "<a href='?id=".$id."&City=".$city."'>";
You do need (well, it's good practice anyway) to use & for your ampersand. Otherwise it's fairly straight forward;
echo "<a href='?id=".($id-1)."&City=$City' class='button'>PREVIOUS</a>";
This is because you are using double quotes, which means you can put variables directly into the string (there are some exceptions which you might need to put in curly brackets {}).
I suggest you get a text editor with syntax highlighting, such as jEdit (other editors are available).
Hope this helps.
Maybe is it better to use the sprintf function
$id = 100;
$previousId = $id - 1;
$City = 'Amsterdam';
$link = 'PREVIOUS';
echo sprintf($link, $id, $City);