记录生活
简单不先于复杂

wordpress调用指定ID文章的代码

在折腾wordpress模板的时候遇到“调用指定ID文章”的需求,折腾一番成功后分享下:

<?php 
$postsl = get_posts("numberposts=4&post_type=any&include=1,2,3"); 
if($postsl) : foreach( $postsl as $post ) : setup_postdata( $post ); 
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title();?></a></li>
<?php endforeach; endif; ?>

上面代码中的“1,2,3”表示要调用的文章id。

将这段代码放到你所需要的位置即可。

最后来说下遇到的坑,在网上找到的代码里面默认用的变量名是“$posts”,我直接放到首页去,显示倒是显示了,但是首页正常的文章列表里面有相同id的文章就显示不出来了…

后来看了下代码,发现变量名重复了导致的,意思就是最好不要使用系统里面的一些默认字段做变量名。


最后分享下如果要把这东西做到后台主题设置里面怎么搞:

先把自定义字段设置好,然后这么写:

<?php 
$hostid = $options['theme_hotid']; 
$postsl = get_posts("numberposts=4&post_type=any&include=".$hostid); 
if($postsl) : foreach( $postsl as $post ) : setup_postdata( $post ); 
?>

上面这段代码中的“$options['theme_hotid']”就是主题自定义字段名称。

赞(0)
未经允许不得转载:爱安普 » wordpress调用指定ID文章的代码