现在,在头版的帖子摘录部分,我有这样一个代码:
<div class="wiadPodtyt">
<ul>
<?php
$piwa = get_posts(
array(
\'posts_per_page\' => 2,
\'cat\' => 81,
\'post__not_in\' => $news_ids,
\'offset\' => 1
)
);
foreach ( $piwa as $post ) {
setup_postdata( $post );
?>
<li><a href=\'<?php the_permalink(); ?>\' class="subtytulyWiad"><?php the_title(); ?></a> </li>
它用于避免双重帖子,因为在另一个地方,我显示了几乎所有类别的最新帖子。我想缩短这段代码,因为我重复了几次(在div类wiadPodtyt中)。问题是,此函数会随诸如POST数量(posts\\u per\\u page)和类别id(cat)等变量而更改。如何正确书写?
更新为了响应@totels,我尝试了以下方法:
function print_alko($allpost=8, $postpage=1, $postcat=81)
{
$news = get_posts(
array(
\'posts_per_page\' => $allpost,
\'cat\' => -88
)
);
// Get an array with just the IDs of the posts in the $fruit array
$news_ids = wp_list_pluck( $news, \'ID\' );
//\'post__not_in\' => $news_ids powinno by? po cat=>...
$piwo = get_posts(
array(
\'posts_per_page\' => $postpage,
\'cat\' => $postcat,
\'post__not_in\' => $news_ids
)
);
foreach ( $piwo as $post ) {
setup_postdata( $post );
echo \'<div class="alpha wiadImg_a">\';
the_post_thumbnail();
echo \'<!-- koniec wiadImg_a --></div>\';
echo \'<div class="alko"><div class="wiadTyt_a">\';
echo \'<h1 class="wiadTyt">\';
echo "<a href="."/\'"."the_permalink()"."/\'";
echo \'class=/"wiadTyt_a/">\'.the_title().\'</a></h1><!-- koniec wiadTyt_a --></div>\';
}
echo \'<div class="wiadPodtyt"><ul>\';
$piwa = get_posts(
array(
\'posts_per_page\' => 2,
\'cat\' => $postcat,
\'post__not_in\' => $news_ids,
\'offset\' => 1
)
);
foreach ( $piwa as $post ) {
setup_postdata( $post );
echo "<li><a href=/\'/";
the_permalink();
echo "/\'";
echo \'class=/"subtytulyWiad/">\';
the_title();
echo \'</a></li>\';
}
wp_reset_query();
echo \'</ul><!-- koniec wiadPodtyt --></div><!-- koniec alko #prawe pude?ko --></div>\';
//koniec fcji print_alko
}
结果只有最后一条新闻,图形上正确,但内容错误。wp\\u查询有问题-它进行了错误的查询。
最合适的回答,由SO网友:totels 整理而成
您可以使用自己的函数来最小化每次要重复调用时键入的字符get_posts
:
在里面functions.php
(可能):
function print_piwa($postcount=2, $cat_id=81) {
?>
<div class="wiadPodtyt">
<ul>
<?php
$piwa = get_posts(array(
\'posts_per_page\' => $postcount,
\'cat\' => $cat_id,
\'post__not_in\' => $news_ids,
\'offset\' => 1
));
foreach ($piwa as $post) {
setup_postdata($post);
?>
<li>
<a href=\'<?php the_permalink(); ?>\' class="subtytulyWiad">
<?php the_title(); ?>
</a>
</li>
<?php
}
?>
</ul>
</div>
<?php
}
显然,您需要弄清楚要设置哪些变量并相应地使用它们,但没有理由不使用
get_posts
在你自己创造的功能中。
然后,您可以在模板中调用函数:
<?php print_piwa(5, 81); ?>