function c2_insert_posts_from_feed($atts) { // Default attributes $atts = shortcode_atts(array( 'rss_url' => 'Feed_URL', 'post_type' => 'post', // Change this to your custom post type slug ), $atts, 'fetch_posts_from_feed'); // Fetch the RSS feed $rss = fetch_feed($atts['rss_url']); // Check if the feed is valid if (!is_wp_error($rss)) { // Get the feed items $feed_items = $rss->get_items(); // Initialize output variable $output = ''; // Loop through each feed item foreach ($feed_items as $item) { // Extract item data $title = $item->get_title(); $content = $item->get_content(); $date = $item->get_date('Y-m-d H:i:s'); $description = $item->get_description(); // Get description $enclosure = $item->get_enclosure()->get_link(); // Check if post with same title already exists $existing_post = get_page_by_title($title, OBJECT, $atts['post_type']); // If post doesn't exist, insert a new post if (!$existing_post) { $post_data = array( 'post_title' => $title, 'post_content' => $content, 'post_date' => $date, 'post_status' => 'publish', 'post_author' => 4, // Change this to the desired author ID 'post_type' => $atts['post_type'], // Use the custom post type 'post_excerpt' => $description, ); // Insert the post $post_id = wp_insert_post($post_data); if ($post_id) { if ($enclosure) { $iframe = '<iframe src="'.$enclosure.'" title="Podcast Player" scrolling="no" width="100%" height="165px" frameborder="0"></iframe>'; update_field( 'podcast_iframe', $iframe, $post_id ); // echo $iframe; } $output .= "Post inserted with ID: ($post_id) $title<br>"; //exit(); } else { $output .= "Failed to insert post: $title<br>"; } } else { $output .= "Post already exists: $title<br>"; } } } else { $output = "Error fetching RSS feed: " . $rss->get_error_message() . "<br>"; } return $output; } add_shortcode('c2_fetch_posts_from_feed', 'c2_insert_posts_from_feed');
Jagdish Sarma Asked question April 24, 2024