我正在尝试获取一个函数,以获取三篇文章,并在类处于活动状态时打印/回显第一篇文章,其余的文章将正常。
我在函数中尝试了此代码。php生成,没有达到效果。
function slider_news() {
$args = array(
\'numberposts\' => 3
);
$latest_posts = get_posts($args);
foreach ($latest_posts as $post) {
$num = 0;
$newnum = $num + 1;
$num = $newnum;
if ($num =1) {
echo \'Post with <div class="active">1st Post </div \';
$newnum = $num + 1;
}
else{
echo \'Post with <div class="Normal">All other posts except 1st</div>\';
}
}
}
我从这个函数得到的源代码如下
Post with <div class="active">1st Post </div>
Post with <div class="active">1st Post </div>
Post with <div class="active">1st Post </div>
最合适的回答,由SO网友:CK MacLeod 整理而成
正如我在评论中所指出的,这与其说是WordPress开发问题,不如说是编程语言问题,第二个问题也是如此。然而,我将写出一个答案,而不是增加评论讨论和犯更多错误。
function slider_news() {
$num = 0;
$args = array( \'numberposts\' => 3 );
$latest_posts = get_posts( $args );
foreach ( $latest_posts as $post ) {
$num++; //PHP increment operator ++ (add 1 to value)
if ( 1 === $num ) { //using a single equals as in original would set the value, === is strict equivalence
echo \'Post with <div class="active">1st Post</div>\';
//example was missing final ">"
} else {
echo \'Post with <div class="Normal">All other posts except 1st</div>\';
}
}
}
我看不出上面单引号和双引号之间的交替有任何问题。只要您与使用单引号来分隔字符串保持一致,就可以在字符串中随意使用双引号,但您需要转义要打印的单引号。更多信息,我建议您阅读PHP语法。没有任何特殊的WordPress例外需要关注。