Home › Forums › Backend Issues (wp-admin) › Post Object at random › Reply To: Post Object at random
As I stated I now have an option to pick a molecule of the day. But I want one at random to load. In ACF we have a motd block with Field Type post object. This seems to create a setup where you can choose an item from the existing ones for the post object or search for one.
How can we load a post at random using an ACF Block from the editor with a Gutenberg Block?
current code:
<?php
// ACF updated to work with new block
$motd = get_field('motd');
var_dump($motd); // NULL
$molecule_month = get_the_terms($motd->ID , 'molecules_of_the_month' );
var_dump($molecule_month); // warning trying to read property ID on NULL
?>
<div id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">
<?php
// $molecule_month = get_the_terms($motd->ID , 'molecules_of_the_month' );
// $month = array_pop($molecule_month);
// $molecule_link = get_term_link( $month->term_id, 'molecules_of_the_month' );
// Set the post type here, and sort them randomly
// molecule of the month presented as random molecule of the day.
$args = array(
'post_type' => 'molecule',
'posts_per_page'=> 1,
'post_category' => 'molecule_of_the_month',
'order_by' => 'rand',
);
// Initiate a custom query
$cpt_query = new WP_Query($args);
// If the query has any post, start the loop
if($cpt_query->have_posts()){
while($cpt_query->have_posts()){
// Output a link and a thumbnail of the post
$cpt_query->the_post(); ?>
<div class="random-post">
<div class="motd-img">
<a href="<?php echo $molecule_link ?>">
<?php echo get_the_post_thumbnail( 'full');?>"/>
</a>
</div>
<div class="motd-content">
<h2 class="is-style-highlight">Molecule of the day</h2>
<h3 class="motd-name">
<a href="<?php // echo $molecule_link ?>">
<?php // echo esc_html( $title ); ?><?php // if($month){ ?> - <?php //echo $month->name; } ?>
</a>
</h3>
<a href="<?php the_permalink();?>"><?php the_title();?></a>
</div>
</div>
<?php
}
} ?>
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.