如何在Wordpress中使用If、If Else和Else


How to use If, If Else and else in Wordpress

我想在wordpress主页上使用If、If else和else,我使用以下条件

<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
}?>
<?php if else { 
<img src="<?php echo catch_that_image() ?>" width="64" height="64" alt="<?php the_title(); ?>" />
} else {
<img src="http://www.technoarea.in/wp-content/themes/TA/images/TA_Logo.png" width="64" height="64" alt="<?php the_title(); ?>" />}
?>
<?php  ?>

我想先在主页上显示缩略图,如果缩略图不可用,那么它必须使用帖子中的第一个图像作为缩略图,如果帖子中没有图像,那么它使用这个图像

http://www.technoarea.in/wp-content/themes/TA/images/TA_Logo.png

你能告诉我我错在哪里吗,因为上面的代码不起作用

替代方案是:

<?php if ($condition) : ?>
   <p> Some html code </p> <!-- or -->
   <?php echo "some php code"; ?>
<?php else : ?>
    <p> Some html code </p> <!-- or -->
   <?php echo "some php code"; ?>
<?php endif;  ?>
php的语法如下:
<?php
if(statement that must be true)
{
    (code to be executed when the "if" statement is true);
}
else
{
    (code to be executed when the "if" statement is not true);
}
?>

您只需要打开和关闭php标记(<?php…?>)一次;一个在php代码之前,另一个在之后。您还需要使用"echo"或"print"语句。这些命令告诉您的程序输出将由浏览器读取的html代码。echo的语法如下:

echo "<img src='some image' alt='alt' />";

它将输出以下html:

<img src='some image' alt='alt' />

你应该得到一本关于php的书。www.php.net也是一个很好的资源。以下是有关if、echo和print语句的手册页面链接:
http://us.php.net/manual/en/control-structures.if.php
http://us.php.net/manual/en/function.echo.php
http://us.php.net/manual/en/function.print.php

编辑:您还可以使用"elseif"来给出下一段代码必须满足的新条件。例如:

&lt;?php
if(condition 1)
{
    (code to be executed if condition 1 is true);
}
elseif(condition 2)
{
    (code to be executed if condition 1 is false and condition 2 is true);
}
else
{
    (code to be executed if neither condition is true);
}
?&gt;

参考ElseIf/Else-If.

但看起来a)您在错误地混合PHP和HTML方面遇到了问题,b)您不确定测试后图像是否存在的逻辑(抱歉,对此无能为力)。试试这个:

<?php 
if ( has_post_thumbnail() ) :
    the_post_thumbnail();
elseif ( /*Some logic here to test if your image exists*/ ): ?>
    <img src="<?php echo catch_that_image() ?>" width="64" height="64" alt="<?php the_title(); ?>" />
<?php else: ?>
    <img src="http://www.technoarea.in/wp-content/themes/TA/images/TA_Logo.png" width="64" height="64" alt="<?php the_title(); ?>" />
//Doing this for over 20 options. 
//Which one is better? The first option will make 20 database calls.
//Only those filters will be invoked for whom the settings are enabled.

// ==A==
if(get_option('some_setting')=='yes')
{
    add_action( 'woocommerce_checkout_process', 'abc_xyz' );
}
function abc_xyz() {

            //Do Something here
}
//=========================OR=========================
//==B==
function abc_xyz() {
        if(get_option('some_setting')=='yes')
        {
            //Do Something here
        }
}
add_action( 'woocommerce_checkout_process', 'abc_xyz' );