Tengo un sitio WordPress y debajo de cada artículo (post) quiero mostrar 3 artículos al azar (posts) para que pueda interrelacionar todos mis posts. Quiero que esto sea simple código - sólo se muestra como un texto en el que se puede hacer clic - nada de fantasía ...
¿Puede ayudarnos, por favor?
¿Quizás algún código en functions.php?
Gracias
En su tema hijo en functions.php añadir estas líneas 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 creará un shortcode que puedes poner cuando quieras. En la línea #8 (posts_per_page) puedes elegir cuántos posts se mostrarán - en nuestro caso: 3.
El shortcode para poner en cualquier post/widget es: [my-random-posts]
¡Que aproveche!
También puede crear su propio plugin WP para para mantener el código y el shortcode en caso de que cambies o cambies el tema de tu WordPress.
Aquí está el código de mi plugin WordPress mostrando los últimos 3 posts (con las fechas al final 🙂 usando el 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' );
...y esta es la captura de pantalla de mi blog WordPress:

