Jak wyświetlić pod każdym postem w WordPress 3 losowe posty?

  

4
Rozpoczęcie tematu

Mam witrynę WordPress i pod każdym artykułem (postem) chcę wyświetlić 3 losowe artykuły (posty), aby móc połączyć wszystkie moje posty. Chcę, aby był to prosty kod - wyświetlany tylko jako klikalny tekst - nic wymyślnego...

Czy możesz pomóc?

Może jakiś kod w functions.php?

Dzięki

2 Odpowiedzi
3

W motywie potomnym w functions.php dodaj następujące linie kodu:

/* 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');

Ten kod utworzy shortcode, który możesz umieścić, kiedy tylko chcesz! W linii #8 (posts_per_page) możesz wybrać, ile postów zostanie wyświetlonych - w naszym przypadku: 3. 

Krótki kod do umieszczenia w dowolnym poście/widżecie to: [my-random-posts]

Miłego oglądania!

2

Można również utworzyć własną wtyczkę WP w celu aby zachować kod i shortcode na wypadek zmiany motywu WordPress.

Oto kod mojej wtyczki WordPress pokazujący ostatnie 3 posty (z datami na końcu 🙂 za pomocą 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' );

...a to jest zrzut ekranu z mojego bloga WordPress:

mój skrót ostatnich postów wtyczki wordpress

Udostępnij: