Solution: what worked in the end was adding
global $post;
at the top of the query, so before
$custom_taxterms = ...
Bill Erickson's Genesis custom loop is the template I followed in the end.
Original question
I was hoping for some help with an issue that has me stumped.
I have the following query. It works and outputs data.
$custom_taxterms = wp_get_object_terms( $post->ID, 'region', array('fields' => 'ids') );
// arguments
$args = array(
'post_type' => 'stay',
'post_status' => 'publish',
'posts_per_page' => 25, // you may edit this number
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'region',
'field' => 'id',
'terms' => $custom_taxterms
)
),
'post__not_in' => array ($post->ID),
);
$related_items = new WP_Query( $args );
// loop over query
if ($related_items->have_posts()) :
echo '<ul>';
while ( $related_items->have_posts() ) : $related_items->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
echo '</ul>';
endif;
// Reset Post Data
wp_reset_postdata();
If I now put it into a function, it stops working.
add_action( 'genesis_loop', 'related_posts_cpt' );
function related_posts_cpt (){
// same loop as above
}
Just to be clear, if I use the same function with a different output, it does work:
add_action( 'genesis_loop', 'related_posts_cpt' );
function related_posts_cpt() {
?>
<p>AAAAAAAAHHHHHH</p>
<?php
}
What am I missing? Thank you in advance.
Replace default Genesis loop with Custom loop
which may be of some use.wp_get_object_terms()
can also returnWP_Error
, so we might need to check for that too. Most likely your$post
variable is undefined when you move your code inside a function, in a shelter from the global scope.