I'm trying to reorder the default "yourdomainname.com/feed" items in WordPress to be sorted after an start and end date meta value.
I have some code that works perfect in the templates and does the front end. However when I insert pretty much the same code in the functions.php
file the feed remains "untouched" by it.
Can anyone may be spot or point me in the right direction to what i'm doing wrong? Here is the code that I put in the functions.php
file.
/*
Sort all posts to be ordered by meta start date.
*/
function feed_filter($query){
if($query->is_feed){
// Find todays date
$date = date('Ymd');
$query_args = array(
'meta_query' => array(
array(
'key' => 'end_date',
'compare' => '>=',
'value' => $date,
)
),
'meta_key' => 'start_date',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
debugIt($query_args);
$query->set( 'meta_query', $query_args );
}
}
add_action( 'pre_get_posts', 'feed_filter');
I fixed the issue by creating my own RSS feed template. Here is an example.
<?php /* Template Name: Event RSS layout */ header("Content-type: text/xml"); echo '<?xml version="1.0" encoding="UTF-8" ?>'; ?>
<rss version="2.0">
<channel>
<?php
$date = date('Ymd');
$args = array(
'numberposts' => -1,
'meta_query' => array(
array(
'key' => 'end_date',
'compare' => '>=',
'value' => $date,
)
),
'meta_key' => 'start_date',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
$posts = get_posts($args);
foreach ($posts as $post){ setup_postdata($post);
$date = get_field('start_date');
$date = strftime("%A den %e. %B", strtotime($date));
?>
<item>
<title><?php echo $date; ?> - <?php the_title(); ?></title>
<link><?php the_permalink(); ?></link>
<guid><?php the_permalink(); ?></guid>
<description>
<![CDATA[
<img src="<?php the_post_thumbnail_url('thumbnail'); ?>" /><?php echo wp_trim_words( get_the_excerpt(), 40, '...' ); ?>]]>
</description>
<pubDate><?php echo date('r', strtotime(get_the_date())); ?></pubDate>
</item>
<?php } ?>
</channel>
</rss>