您可以创建一个短代码,它可以在帖子中的任何位置使用。短代码将负责获取随机帖子并显示它。示例代码:
<?php
/*
* Plugin Name: Random Post
* Description: Display random post
* Version: 1.0
* Author: windyjonas
* Author URI: https://www.jonasnordstrom.se
*/
function display_random_post() {
ob_start();
$current_id = get_queried_object_id();
$args = [
\'orderby\' => \'rand\',
\'posts_per_page\' => 1,
\'ignore_sticky_posts\' => true,
\'post__not_in\' => [ $current_id ],
];
$random_posts = get_posts( $args );
if ( ! empty( $random_posts ) ) :
$the_post = $random_posts[0]; ?>
<p><a href="<?php echo get_permalink( $the_post->ID); ?>"><?php echo get_the_title( $the_post->ID ); ?></a></p>
<?php endif;
return ob_get_clean();
}
add_shortcode( \'random_post\', \'display_random_post\' );