// Define shortcode function
function feed_carousel_shortcode($atts, $content = null) {
// Extract shortcode attributes
$atts = shortcode_atts(
array(
'url' => '', // Feed URL
'limit' => 5, // Number of posts to display
'title' => '', // Title for the feed
'extra_link' => '', // Optional link for the extra element
'extra_text' => '', // Optional anchor text for the extra element
),
$atts
);
// Initialize output variable
$output = '';
// Fetch feed data
$feed_url = esc_url($atts['url']);
$limit = intval($atts['limit']);
$rss = fetch_feed($feed_url);
if (!is_wp_error($rss)) {
$items = $rss->get_items(0, $limit);
if (!empty($items)) {
// Start building the HTML structure
$title = esc_html($atts['title']);
$extra_link = esc_url($atts['extra_link']);
$extra_text = esc_html($atts['extra_text']);
// Add title with optional link
$output .= '
'; // Start row
// Loop through each item
foreach ($items as $item) {
$title = esc_html($item->get_title());
$description = wp_strip_all_tags($item->get_description());
$description = wp_trim_words($description, 18, '...'); // Limit to 18 words with ellipsis
$content = $item->get_content();
$image = ''; // Placeholder for image URL, extract from description or content
$link = esc_url($item->get_permalink()); // Get the post permalink
// Convert CDATA section into a SimpleXMLElement object
$xml = simplexml_load_string($description . $content, 'SimpleXMLElement', LIBXML_NOCDATA);
// Find all img tags
$imgs = $xml->xpath('//img');
// Iterate through each img tag and check the srcset attribute
foreach ($imgs as $img) {
$srcset = $img['srcset'];
// Check if srcset contains the desired pattern
if (strpos($srcset, '300x200.webp') !== false) {
$image = $img['src'];
break; // Exit loop if image is found
}
}
// Add post HTML
$output .= '
'; // End feed-item div
}
// Close HTML structure
$output .= '
'; // End row
}
} else {
$output = 'Error fetching feed. Please check the URL.
';
}
return $output;
}
add_shortcode('feed_carousel', 'feed_carousel_shortcode');