Tenho um site WordPress e por baixo de cada artigo (post) quero mostrar 3 artigos (posts) aleatórios para poder interligar todos os meus posts. Quero que seja um código simples - apenas mostrado como um texto clicável - nada de especial...
Podem ajudar-me?
Talvez algum código no functions.php?
Agradecimentos
No seu tema filho em functions.php, adicione estas linhas de código:
/* Shortcode for random posts */
/* The shortcode to put in any post/widget is [my-random-posts] */
function my_rand_posts() {
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 3,
);
$the_query = new WP_Query($args);
$string = "";
if ($the_query->have_posts()) {
$string .= '<ul>';
while ($the_query->have_posts()) {
$the_query->the_post();
$string .= '<li><a href="' . get_permalink() . '" target="_blank">' . get_the_title() . '</a></li>';
}
$string .= '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
$string .= 'no posts found';
}
return $string;
}
add_shortcode('my-random-posts', 'my_rand_posts');
add_filter('widget_text', 'do_shortcode');
Este código irá criar um shortcode que pode colocar quando quiser! Na linha #8 (posts_per_page) pode escolher quantos posts serão mostrados - no nosso caso: 3.
O shortcode para colocar em qualquer post/widget é: [my-random-posts]
Desfrutar!
Também pode criar o seu próprio plugin WP para para manter o código e o shortcode no caso de mudar/trocar de tema no WordPress.
Aqui está o código do meu plugin WordPress que mostra os últimos 3 posts (com as datas no final 🙂 utilizando o shortcode: [my-plugin-recent-posts]:
<?php
/*
Plugin Name: My plugin recent posts shortcode
Plugin URI: https://mypluginrecentpostsshortcode.com
Description: WP plugin for showing recent posts with a shortcode
Author: My plugin recent posts shortcode Ltd.
Version: 1.0
Author URI: https://mypluginrecentpostsshortcode.com
Text Domain: my-plugin-recent-posts-shortcode
Domain Path: /languages/
*/
function my_plugin_recent_posts_shortcode() {
$buffer = '<h4>Recent Posts:</h4><ul>';
$args = array(
'post_type' => 'post',
'posts_per_page' => 3,
);
$q = new WP_Query( $args );
while ( $q->have_posts() ) {
$q->the_post();
$buffer .= '<li><a href=" ' . get_the_permalink() . '">' . get_the_title() . '</a> - ' . get_the_date() . ' </li>';
}
wp_reset_postdata();
$buffer .= '</ul>';
return $buffer;
}
add_shortcode( 'my-plugin-recent-posts', 'my_plugin_recent_posts_shortcode' );
...e esta é a captura de ecrã do meu blogue WordPress:

