Jake Funchion
Jake Funchion

Reputation: 81

How to echo out a php variable into an html link in a wordpress shortcode

In my short code I am dynamically grabbing some custom posts and displaying them. These custom posts have a custom field labeled 'url'. What I'm trying to do is grab the value from that custom field and put it in the href of an anchor tag. The problem is that I can't seem to use echo in a shortcode. It seems that the function do_shortcode might be the answer, but I am not sure how to use it in my case. The problem is in this line:

$retour .= "<a href='".echo $meta_values;."'>";

Here is the rest of the code for the shortcode

function sc_liste($atts, $content = null) {
    extract(shortcode_atts(array(
            "cat" => ''
    ), $atts));
    global $post;

    $myposts = get_posts('post_type=section_modules&category_name='.$cat.'&order=ASC');
    $retour = "<div class='container-fluid sectionBoxContainer'><div class='row-fluid'>";
    foreach($myposts as $post) :
    $meta_values = get_post_meta( $post->ID, 'url', true );
         $retour .= "<a href='".echo do_shortcode();."'>";
         $retour.="<div class='sectionBox span4'><h2>".$post->post_title."</h2><div class='hrule_black'></div><p>".$post->post_content."</p></div>";
         $retour .="</a>";
    endforeach;
    $retour .= "</div></div>";

    return $retour;


}

Upvotes: 0

Views: 2649

Answers (3)

Niamul
Niamul

Reputation: 75

You shouldn't echo an item within shortcode. Just store them in a variable and return the result at the end of your shortcode function. In your case, you can do that in this way:

$retour .= "<a href='" . $meta_values . "'>";

And at the end-

return $retour;

Upvotes: 1

Olaf Dietsche
Olaf Dietsche

Reputation: 74078

Maybe I misunderstand your question, but when you leave out the echo and put $meta_values in your string, this should work

$retour .= "<a href='$meta_values'>";

Upvotes: 0

scrowler
scrowler

Reputation: 24425

You don't echo into a variable, you just concatenate it:

$retour .= "<a href='".$meta_values."'>";
echo $retour;

Upvotes: 2

Related Questions