PHP:我可以在变量中放入if语句吗?

Ker*_*ynn 2 php wordpress rss if-statement

我仍然是PHP的初学者,很抱歉,如果这是一个愚蠢的问题=)

我想要做的是在WordPress博客中,在我的RSS源中插入一个包含多个值("成分")的自定义字段.(我还有其他帖子不是食谱,这就是为什么标题"成分"和"说明"都在if语句中.)这是我到目前为止的整个代码:

    <?php
    function insertIngredients($content) {
     /* get ingredients into variable $recipeStuff */
     $recipeStuff = 
   if ($ingredients = get_post_custom_values('ingredients')) {
    echo '<h3>Ingredients</h3><ul id="ingredients">';
    foreach ( $ingredients as $key => $value ) {
   echo '<li>';
   echo $value;
   echo '</li>';
    } 
    echo '</ul><h3>Instructions</h3>';
   }
     /* add before content */
        $content = $recipeStuff . $content;
        return $content;
    }
    /* Do it! */
    add_filter('the_excerpt_rss', 'insertIngredients');
    add_filter('the_content_rss', 'insertIngredients');
    ?>
Run Code Online (Sandbox Code Playgroud)

但是得到一个"意外的IF"错误,所以我想我不能把所有内容放在$ recipeStuff变量中=)我只是想不出怎么把它放在那里.

(如果重要的话,IF语句就是我在页面本身的帖子中使用的,它完美无缺!)

非常感谢您的任何帮助!= d

UPDATE!

这就是我现在的代码:

function insertIngredients($content) {
/* test for presence of ingredients & set variables */
if ($ingredients = get_post_custom_values('ingredients')) {
    $heading1 = '<h3>Ingredients</h3><ul id="ingredients">';
    foreach ( $ingredients as $key => $value ) {
        $ings = '<li>' . $value . '</li>';
    }
    $heading2 = '</ul><h3>Instructions</h3>';
}
/* if no ingredients, variables are empty */
else { $heading1=''; $ings=''; $heading2=''; }

$recipeStuff = $heading1 . $ings . $heading2 ;

/* add before content */
    $content = $recipeStuff . $content;
    return $content;
}
/* Do it! */
add_filter('the_excerpt_rss', 'insertIngredients');
add_filter('the_content_rss', 'insertIngredients');
Run Code Online (Sandbox Code Playgroud)

我不再收到错误消息,但这些成分没有出现在rss Feed中.我不确定是不是因为代码仍有问题,或者需要一段时间才能产生效果(虽然我不知道为什么会这样)?我使用FeedBurner,如果这有所作为.

非常感谢你的答案,每个人.我将尝试一些不同的东西,然后再次更新.谢谢!=)

Rha*_*ody 8

为什么不把它转过来?

if (condition) {
$recipeStuff = '';
}
else
{
$recipeStuff = '';
}
Run Code Online (Sandbox Code Playgroud)


Ger*_*der 7

即使这个问题已经很久了,IMO仍然缺少最好的答案,三元运营商:

<?php
    $recipeStuff = (  HERE CHECK FOR INGREDIENTS  ) ? SOMETHING : SOMETHING ELSE ;
?>
Run Code Online (Sandbox Code Playgroud)

$recipeStuffSOMETHING如果检查结果为true,则会得到值,否则会得到SOMETHING ELSE