PHP站外调用WordPress文章列表

2022-10-12,,,,

我们在网站文章推荐的时候如果有遇到基于WordPress不同站点间文章列表的展示,可以使用以下方法来实现PHP站外调用WordPress文章列表。

PHP站外调用WordPress文章列表

一、创建php文件
在被调用的基于WordPress的网站根目录新建一个api.php的php文件,代码如下:

<?php
define('WP_USE_THEMES', false);
require('./wp-load.php');
$recent = new WP_Query('showposts=12&order=DESC&orderby=ID');while($recent->have_posts()) : $recent->the_post(); update_post_caches($posts); ?>
<li><a href="<?php the_permalink(); ?>" target="_blank"><?php echo mb_strimwidth(strip_tags(apply_filters('the_title', $post->post_title)), 0, 50," "); ?></a></li>
<?php endwhile; ?>

二、调用文章
在需要调用文章列表的位置使用以下代码,需要php的支持。

<?php
ini_set("user_agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.37");
$url="https://网站域名/api.php";
echo file_get_contents( $url );
?>

总结:此解决方法可拓展性强,只需要php的支持即可,对于精通php的老手,还能有更多更好的拓展,可根据自己的实际需求进行调整。