WordPress已成为网站建设者最常用的平台之一,其强大的扩展性能够满足用户的各种需求。其中,插件就是其最大的亮点之一。利用插件,可以轻松实现各种功能,其中就包括采集文章。下面就为大家介绍一下具体的操作步骤:
1.首先,在WordPress后台找到“插件”选项,并点击“新建插件”。
2.进入新建插件页面后,输入插件名称,并在代码编辑区输入如下代码:
```
/**
* Plugin Name: 采集文章插件
* Plugin URI: https://github.com/
* Description: 利用WordPress采集文章的功能插件
* Version: 1.0
* Author: WP
* Author URI: https://wordpress.org/
**/
?>
```
3.在代码编辑区后面,输入以下代码:
```
function crawlnet_get_contents ($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
function crawlnet_save_image($imgUrl,$savePath){
$img = crawlnet_get_contents($imgUrl);
$fp2 = @fopen($savePath, "w");
fwrite($fp2,$img);
fclose($fp2);
}
add_action('init','start_crawl');
function start_crawl()
{
$url = 'https://www.example.com';//输入要采集的网址
$html = crawlnet_get_contents($url);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$as = $xpath->query('//a');
foreach ($as as $a) {
$title = $a->nodeValue;
$link = $a->getAttribute('href');
$content = crawlnet_get_contents($link);
$dirname = './images';//定义存储图片的目录,可以自定义
$imagepath = $dirname.'/'.$title.'.jpg';
if(!is_dir($dirname)){
mkdir($dirname);
}
$doc2 = new DOMDocument();
@$doc2->loadHTML($content);
$xpath2 = new DOMXPath($doc2);
$ps = $xpath2->query('//img');
foreach($ps as $p)
{
$imageUrl = $p->getAttribute('src');
crawlnet_save_image($imageUrl,$imagepath);
}
$content=$doc2->getElementsByTagName("body")->item(0)->nodeValue;//获取文章内容
$my_post = array(
'post_title' => wp_strip_all_tags( $title ),
'post_content' => $content,
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array( 8,39 )
);
wp_insert_post( $my_post );//将内容插入到WordPress中
}
}
?>
```
4.保存插件后,进入插件管理界面,激活插件即可。
总结:
利用WordPress可以非常方便地进行文章采集,不仅可以帮助网站管理员节省大量时间和精力,还可以增加网站的内容丰富度,提高网站的用户黏着度。希望本文能够对大家了解如何利用WordPress进行文章采集有所帮助。
147SEO » wordpress采集文章