auto_rss.php

auto_rss.php

This PHP snippet is designed for integration with a WordPress website to automatically fetch and create new posts from an external RSS feed. By loading the WordPress core, the script gains access to its inherent functionalities. The script then defines an RSS feed URL, retrieves its content, and parses it using the SimpleXML PHP extension. Iterating through each item in the RSS feed, it checks whether a post with an identical title already exists in the WordPress database to prevent content duplication. If no matching post is found, it crafts a new post object populated with the RSS item's title and description, and subsequently inserts this into the WordPress database as a published post authored by the primary user in the default category. While functional, real-world application might necessitate additional checks, error handling, and customizations tailored to the specific RSS feed and WordPress site requirements.

<?php // Load WordPress require( dirname( __FILE__ ) . '/wp-load.php' ); // Set the RSS feed URL $feed_url = "http://example.com/rss"; // Get the RSS feed content $feed = simplexml_load_file( $feed_url ); // Loop through each feed item and create a post foreach ( $feed->channel->item as $item ) { // Check if post already exists $existing_post = get_page_by_title( $item->title, 'OBJECT', 'post' ); if ( $existing_post === null ) { // Create post object $new_post = array( 'post_title' => $item->title, 'post_content' => $item->description, 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array( 1 ) ); // Insert the post into the database wp_insert_post( $new_post ); } } ?>

Frequently Asked Questions

This code fetches items from an RSS feed and creates WordPress posts for each unique item not already present in the posts database.