Last active
March 29, 2018 18:24
-
-
Save tripflex/a5f01d9f162e1b9e4844eebdc440c4a9 to your computer and use it in GitHub Desktop.
Output external RSS feed from URL in field value when using WP Job Manager Field Editor (untested)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// ^ the <?php above should only be in your functions.php file ONCE, at the top | |
// The filter is field_editor_output_as_value_METAKEY | |
// where you need to replace METAKEY with the actual meta key you want to filter the output for | |
// This example is used for the "job_external_rss_feed" meta key | |
add_filter( 'field_editor_output_as_value_job_external_rss_feed', 'smyles_output_rss_feed_from_field_value' ); | |
// It is STRONGLY recommended that you set this field type to an HTML5 URL field, to force validation of the URL | |
/** | |
* Output list formatted RSS feed from external URL | |
* | |
* @author Myles McNamara | |
* @url https://plugins.smyl.es | |
* | |
* @param $value The value before it is output on the listing | |
*/ | |
function smyles_output_rss_feed_from_field_value( $value ) { | |
if ( empty( $value ) ) { | |
return $value; | |
} | |
// Return empty string if value entered by user is not a valid URL | |
if ( filter_var( $value, FILTER_VALIDATE_URL ) === false ) { | |
return ''; | |
} | |
if ( ! function_exists( 'fetch_feed' ) ) { | |
include_once( ABSPATH . WPINC . '/feed.php' ); | |
} | |
$maxitems = 5; // Max items to display | |
// RSS feed code from Stackoverflow post | |
// @see https://wordpress.stackexchange.com/questions/99584/display-external-rss-feed-on-pages | |
// Updated based on code from WordPress Codex | |
// @see https://developer.wordpress.org/reference/functions/fetch_feed/ | |
// Get a SimplePie feed object from the specified feed source. | |
$feed = fetch_feed( esc_url( $value ) ); | |
if ( is_wp_error( $feed ) || ! $feed->get_item_quantity() ) { | |
return ''; // Return empty string if error or not items, you could also output custom message here too for when feeds are down | |
} | |
$rss_items = $feed->get_items( 0, $maxitems ); | |
$lis = array(); | |
if ( empty( $rss_items ) ) { | |
return ''; // If for some weird reason no items returned from get_items() return empty string (just like above) | |
} | |
foreach ( (array) $rss_items as $item ) { | |
if ( '' === $title = esc_attr( strip_tags( $item->get_title() ) ) ) { | |
$title = __( 'Untitled' ); | |
} | |
$lis[] = sprintf( | |
'<a href="%1$s" target="_blank">%2$s</a>', | |
esc_url( strip_tags( $item->get_permalink() ) ), | |
$title | |
); | |
} | |
return '<ul class="feed-list"><li>' . join( '</li><li>', $lis ) . '</ul>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment