Hi,
I am trying to figure out how to get the post object to auto fill for a post type.
So the logic would go like this. If the related posts are not set it would go and get 4 random posts in the post type.
here is what I have to set the post manualy. How do I get it to auto fill if I don’t put anything in?
<div class="row no-gutters">
<?php $post_objects = get_field('testimonials_related');
if( $post_objects ): ?>
<?php foreach( $post_objects as $post_object): ?>
<div class="col-xs-6 col-sm-3 ">
<?php $video_id = get_post_meta( $post_object->ID, 'youtube_video_main', true ); ?>
<a href="<?php echo get_permalink($post_object->ID); ?>">
<img src="http://img.youtube.com/vi/<?php echo $video_id; ?>/mqdefault.jpg" />
</a>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
Untested but here’s something to get you started:
$post_objects = get_field( 'testimonials_related' );
if ( $post_objects ) {
// your normal stuff here..
} else {
// no post objects found, query the post type for 4 random posts
// you should cache this query with either the object cache or transients api
// http://wordpress.stackexchange.com/questions/183698/way-to-cache-a-query-for-24-hrs
$current_post_id = get_the_id();
$testimonials = new WP_Query(
'post_type' => 'testimonials',
'post_status' => 'publish',
'posts_per_page' => 4,
'orderby' => 'rand',
'post__not_in' => array( $current_post_id ) // exclude the current post
);
if ( $testimonials->have_posts() ) {
while ( $testimonials->have_posts() ) {
$testimonials->the_post();
// display the posts...
}
wp_reset_postdata();
}
}