Jeg har WordPress-websted, og under hver artikel (indlæg) vil jeg vise 3 tilfældige artikler (indlæg), så jeg kan forbinde alle mine indlæg. Jeg ønsker, at dette skal være en simpel kode - kun vist som en klikbar tekst - intet fancy ...
Kan du være så venlig at hjælpe?
Måske noget kode i functions.php?
Tak for hjælpen
I dit Child theme i functions.php skal du tilføje disse kodelinjer:
/* 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');
Denne kode opretter en kortkode, som du kan sætte ind, når du vil! På linje #8 (posts_per_page) kan du vælge, hvor mange indlæg der skal vises - i vores tilfælde: 3.
Kortkoden, der skal indsættes i ethvert indlæg/widget, er: [my-random-posts]
God fornøjelse!
Du kan også oprette dit eget WP-plugin for at for at beholde koden og kortkoden hvis du skifter/ændrer dit WordPress-tema.
Her er koden til mit WordPress-plugin, der viser de seneste 3 indlæg (med datoerne i slutningen 🙂 ved hjælp af kortkoden: [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' );
...og dette er et skærmbillede af min WordPress-blog:

