admin管理员组

文章数量:1295690

i mean like in the middle of the article, i will put a link that link to a random post in my website.

i'm new with this thing. and i'm trying to find a solution, because i've tried with a plugins, but i can not find the solution for this problem.

What is the best way of make a internal post-linking with PHP?

TIA

i mean like in the middle of the article, i will put a link that link to a random post in my website.

i'm new with this thing. and i'm trying to find a solution, because i've tried with a plugins, but i can not find the solution for this problem.

What is the best way of make a internal post-linking with PHP?

TIA

Share Improve this question asked Oct 8, 2018 at 6:34 dedemithdedemith 1
Add a comment  | 

1 Answer 1

Reset to default 0

You can create a shortcode which can be used anywhere inside a post. The shortcode would be responsible for fetching a random post and displaying it. Example code:

<?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' );

本文标签: next post linkmake random internal linking in the middle of posting