代码基本原理,新建一个自定义分类法“shot”,自动从另一个站点的RSS抓取文章,放在一个数组中,再用这个数组创建“shot”文章,并为文章添加自定义栏目image和link_url,方便调用缩略图和原文链接。
将下面代码添加到当前主题functions.php中即可。
- <?
- add_action( \’init\’, \’register_cpt_shot\’ );
- register_cpt_shot() {
- = (
- \’name\’ => _x( \’Dribble Shots\’, \’shot\’ ),
- \’singular_name\’ => _x( \’Dribbble Shot\’, \’shot\’ ),
- \’add_new\’ => _x( \’Add New\’, \’shot\’ ),
- \’add_new_item\’ => _x( \’Add New Dribbble Shot\’, \’shot\’ ),
- \’edit_item\’ => _x( \’Edit Dribbble Shot\’, \’shot\’ ),
- \’new_item\’ => _x( \’New Dribbble Shot\’, \’shot\’ ),
- \’view_item\’ => _x( \’View Dribbble Shot\’, \’shot\’ ),
- \’search_items\’ => _x( \’Search Dribble Shots\’, \’shot\’ ),
- \’not_found\’ => _x( \’No dribble shots found\’, \’shot\’ ),
- \’not_found_in_trash\’ => _x( \’No dribble shots found in Trash\’, \’shot\’ ),
- \’parent_item_colon\’ => _x( \’Parent Dribbble Shot:\’, \’shot\’ ),
- \’menu_name\’ => _x( \’Dribble Shots\’, \’shot\’ ),
- );
- = (
- \’labels\’ => ,
- \’hierarchical\’ => false,
- \’supports\’ => ( \’title\’, \’custom-fields\’ ),
- \’\’ => true,
- \’show_ui\’ => true,
- \’show_in_menu\’ => true,
- \’show_in_nav_menus\’ => false,
- \’publicly_queryable\’ => true,
- \’exclude_from_search\’ => false,
- \’has_archive\’ => true,
- \’query_var\’ => true,
- \’can_export\’ => true,
- \’rewrite\’ => true,
- \’capability_type\’ => \’post\’
- );
- register_post_type( \’shot\’, );
- }
- get_image() {
- preg_match_all(\’/<img[^>]+>/i\’,, );
- = ();
- ( [0] )
- {
- preg_match_all(\’/(src)=(]*
- \’);
- }
- (ABSPATH . WPINC . \’/feed.php\’);
- = fetch_feed(\’http:
- = ->get_items(0);
- = ();
- ( ) :
- [->get_date(\’Ymd\’)] = (
- \’id\’ => ->get_date(\’Ymd\’),
- \’url\’ => esc_url( ->get_permalink() ),
- \’\’ => ->get_date(\’Y-m-d H:i:s\’),
- \’title\’ => esc_html( ->get_title() ),
- \’image\’ => get_image(->get_description())
- );
- ;
- ( ) {
- = (
- \’post_type\’ => \’shot\’,
- \’post_status\’ => \’publish\’,
- \’post_author\’ => 1,
- \’post_title\’ => [\’title\’],
- \’post_date\’ => [\’\’]
- );
- = (
- \’link_url\’ => [\’url\’],
- \’image\’ => [\’image\’]
- );
- = get_posts(
- (
- \’post_type\’ => \’shot\’,
- \’meta_key\’ => \’link_url\’,
- \’meta_value\’=> [\’link_url\’]
- )
- );
- (() == 0) {
- = wp_insert_post();
- add_post_meta(, \’link_url\’, [\’link_url\’], true);
- add_post_meta(, \’image\’, [\’image\’], true);
- }
- }
- ?>
修改第66行的”http://dribbble.com/tammyhart/shots.rss“为准备抓取文章站点的RSS地址,还可以修改第80行后的”shot“为你所用主题自定义分类法名称,抓取的文章会自动添加到该分类法中。
上述代码中并没有抓取文章内容的功能,仅供参考学习之用。
暂无评论内容