小編在幫客户開發 WordPress 站
點時經常會遇到各種要求,這次幫一個客户開發項目時,客户要求幫他開發的站點的文章能在其他網站調用,並且要以 HTML 的形式來調用不能使用 js,説是做
鏈輪什麼的。沒辦法顧客就是上帝,繼續折騰唄。下面來説下實現方法,首先在 WordPress 的根目錄新建一個 html_post.php 文件,記住是需
要向外調用文章的 WordPress 站點。 html_post.php 文件的代碼如下:
<?phpdefine('WP_USE_THEMES', false);require('./wp-load.php');query_posts('showposts=10&orderby=new');?>/** charset=UTF-8"防止亂碼 */<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <?php while (have_posts()): the_post(); ?><li><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a></li><?php endwhile; ?> |
這樣就可以調用網站中最新的 10 篇文章了,showposts=10 這個數字可以修改成你想要調用文章的數量。下面我來給大家仔細講解下如何來修改代碼達到調用自己想要調用文章的效果。
1 、如果我想要調用某個分類的下的最新文章該如何實現呢?
其實這點很容易實現的只需要修改下 query_posts 這個參數,比如我指定要調用的分類的 ID 是 1 那麼代碼就變成了:
<?phpdefine('WP_USE_THEMES', false);require('./wp-load.php');/** 如果想同時調用多個分類用半角符分隔如 cat=1,2,3,4 */query_posts('showposts=10&orderby=new&cat=1');?>/** charset=UTF-8"防止亂碼 */<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><?php while (have_posts()): the_post(); ?><li><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a></li><?php endwhile; ?> |
2 、如果我想調用全站站問斬但只屏蔽某個分類下的文章呢?
<?phpdefine('WP_USE_THEMES', false);require('./wp-load.php');/** 如果想同時屏蔽多個分類用半角符分隔如 cat=-1,-2,-3,-4 */query_posts('showposts=10&orderby=new&cat=-1');?>/** charset=UTF-8"防止亂碼 */<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><?php while (have_posts()): the_post(); ?><li><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a></li><?php endwhile; ?> |
3 、如果我想調用隨機文章呢?
<?phpdefine('WP_USE_THEMES', false);require('./wp-load.php');/** 如果想同時屏蔽多個分類用半角符分隔如 cat=-1,-2,-3,-4 */query_posts('showposts=10&orderby=rang');?>/** charset=UTF-8"防止亂碼 */<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><?php while (have_posts()): the_post(); ?><li><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a></li><?php endwhile; ?> |
4 、如果我想輸出摘要呢?
<?phpdefine('WP_USE_THEMES', false);require('./wp-load.php');/** 如果想同時屏蔽多個分類用半角符分隔如 cat=-1,-2,-3,-4 */query_posts('showposts=10&orderby=rang');?>/** charset=UTF-8"防止亂碼 */<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><?php while (have_posts()): the_post(); ?><li><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>" target="_blank"><?php the_title(); ?></a><?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 200,"...",'utf-8'); ?></li><?php endwhile; ?> |
差點都忘了~下面小編就再來説説站外如何來調用~
<?php//該代碼放置在需要調用文章內容和列表的地方$url='http://你的站點地址/html_post.php';echo file_get_contents( $url );?> |
OK
大功告成。調出來的文章都是純 HTML 的~不是什麼 js 噢,對 SEO 非常友好。另外小編提示下:上面介紹的方法都必須要在調用站點支持 php 的情況下才可
行,如果調用站點支持 asp 的話只要把讀取 html_post.php 的 PHP 代碼用 ASP 重寫一遍,但是如果是靜態空間就只能用 js 來調用咯。