Vladimir Štus
Vladimir Štus

Reputation: 217

Calling PHP function from within a string

I can't find a solution how to combine single and double quotes to echo HTML and call a function at the same time:

foreach ($result as $r) { 
    echo "<a href='get_permalink(get_page($r->id))'>".get_permalink(get_page($r->id)).'</a><br>';
}

Problem is this part is parsed as text, not php

"<a href='get_permalink(get_page($r->id))'>"

Cansome one help me to combine this? get_permalinks and get page are wordpress built in functions, so they should have function behavior

Upvotes: 1

Views: 97

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173522

It's not possible to run PHP code when it's inside a string (unless with eval). However, you can use printf() to separate code from string:

$url = get_permalink(get_page($r->id));
printf('<a href="%s">%1$s</a><br>', htmlspecialchars($url, ENT_QUOTES, 'UTF-8'));

The %1$s is a positional format specifier; this is done so that the encoded $url value only has to be passed once.

Upvotes: 2

Ashique C M
Ashique C M

Reputation: 683

try this way:

if($result as $r)
{ 
  echo "<a href='" . get_permalink(get_page($r->id)) . "'>" . get_permalink(get_page($r->id)) . '</a><br>';
}

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

Just concat the string like this:

echo "<a href='". get_permalink(get_page($r->id)) . "'>" . get_permalink(get_page($r->id)) . "</a><br>";

Also if you want to know what's the difference between single and double quotes see this: What is the difference between single-quoted and double-quoted strings in PHP?

Upvotes: 1

Mahendra Jella
Mahendra Jella

Reputation: 5596

You can't call a function inside double " quotes.

foreach ($result as $r)
        { 
            echo "<a href='".get_permalink(get_page($r->id))."'>".get_permalink(get_page($r->id)).'</a><br>';
        }

Upvotes: 2

Related Questions