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?



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:

* Plugin Name: Random Post
* Description: Display random post
* Version: 1.0
* Author: windyjonas
* Author URI: https://www.jonasnordstrom.se
function display_random_post() {
    $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' );
  • ok. ill try this. just insert it into any posting? thx – dedemith Oct 9 '18 at 6:13
  • hi @windjonas do i need to install plugins to put that code? and i just put that code on my post with text mode? because its not working – dedemith Oct 11 '18 at 3:34
  • What I posted is the code of a plugin. The plugin defines a shortcode, that means that you can put the text: [random_post] anywhere in your post content and the plugin will replace it with the title and link to a random post. – windyjonas Oct 12 '18 at 7:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.