Domanda

I'm trying to execute another PHP function inside an echo. I could change

<?php echo home_url(); ?>

to

"$home_url"

and it worked.

But I don't know how to change the following:

<?php $categories = get_the_category();
    $cat_slug = $categories[0]->slug;
    echo "$cat_slug" ?>

Here's my full code, with a HEREDOC instead of " ":

<?php   
if( is_page( 3769 ) ):  
    echo 'ANOTHER LOGO';  
else:  
    echo <<<HTML
<a href="$home_url"><img border="0" src="http://WEBSITE.COM/logo<?php $categories = get_the_category();
$cat_slug = $categories[0]->slug;
echo "$cat_slug" ?>
.png" width="500" height="100"></a>
HTML;
endif;     
?>  

Thank you.

È stato utile?

Soluzione

Normally you shouldn't execute any functions inside an echo. It's better to do all "preparations" in advance and echo the results. That way it's simpler to split the logic and the presentation later

<?php   
if( is_page( 3769 ) ):  
    echo 'ANOTHER LOGO';  
else:  
$categories = get_the_category();
$cat_slug = $categories[0]->slug;
    echo <<<HTML
<a href="$home_url"><img border="0" src="http://WEBSITE.COM/logo{$cat_slug}.png" width="500" height="100"></a>
HTML;
endif;     
?> 

Altri suggerimenti

Take the function call out of the string:

<?php   
if( is_page( 3769 ) ):  
    echo 'ANOTHER LOGO';  
else:  
    $categories = get_the_category();
    $cat_slug = $categories[0]->slug;
    echo <<<HTML
    <a href="$home_url"><img border="0" src="http://WEBSITE.COM/logo{$cat_slug}.png" width="500" height="100"></a>
    HTML;
endif;     
?> 

Use single quote, your "$cat_slug" close the first (")

src="http://WEBSITE.COM/logo<?php $categories = get_the_category();
$cat_slug = $categories[0]->slug;
echo "$cat_slug" ?>

Change it to this:

src='http://WEBSITE.COM/logo<?php $categories = get_the_category();
    $cat_slug = $categories[0]->slug;
    echo "$cat_slug" ?>'

Looking at the code block you supplied I'd have gone with something like this

<?php   
if( is_page( 3769 ) ):  
    echo 'ANOTHER LOGO';  
else:
 $categories = get_the_category();
 $cat_slug = $categories[0]->slug;

 echo '<a href="$home_url"><img border="0" src="http://WEBSITE.COM/logo'.$cat_slug.png.'" width="500" height="100"></a>'

endif;     
?> 

Otherwise you were doing a double echo which is probably causing some issues.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top