WordPress.org

Ready to get started?Download WordPress

Forums

random post and 10 next (5 posts)

  1. aassddff
    Member
    Posted 1 year ago #

    Hello,
    I want to choose random id of a post in my wordpress and then display 10 links to next posts that are right after the one that I draw.
    For example I have 10 000 posts in my wordpress. I draw random number 5739, so I want to get links do posts of id-s: 5739, 5740, 5741, 5742 ... 5748.
    Can someone help me with the code that can do such thing?
    Thanks in advance for your help.

  2. cdukes
    Member
    Posted 1 year ago #

    All assets in WP share the ID scheme, so 5739 may be a post, but 5740 may be a page, a custom post type, a link, etc.

    Take a look at http://codex.wordpress.org/Function_Reference/next_post_link

    You could try looping that, though there may be a better function.

  3. aassddff
    Member
    Posted 1 year ago #

    In my wordpress more than 99,9% of id-s are posts so really I don't care about few rare situations. All I care about is the performance (I want to use as little resources as it's possible).

    Could you please write down the code of selecting random post id from my database and I think I will deal with it further.

    Thanks for your reply.

    [ Please do not bump, that's not permitted here. ]

  4. keesiemeijer
    moderator
    Posted 1 year ago #

    Try it with this:

    <?php
    $published_posts = wp_count_posts();
    $random_number = rand(1, ($published_posts->publish-10));
    $random_posts = get_posts('posts_per_page=10&offset='.$random_number);
    foreach ($random_posts as $post) {
    	echo '<a href="' . get_permalink($post->ID) . '">' . $post->post_title . '</a><br/>';
    }
    ?>
  5. aassddff
    Member
    Posted 1 year ago #

    thanks a lot, it works almost OK. the only problem is that is shows posts with every two IDs, for example:
    5739, 5741, 5743, 5745, 5747 ...
    could you please show me how to show posts like this:
    5739, 5740, 5741, 5742, 5743 ...

    anyway - thanks a lot for your help & code !!

Topic Closed

This topic has been closed to new replies.

About this Topic