Can I insert the PHP code for random post link on Child Theme?

  • Anonymous


    Hi guys,

    I have been busy with exams during last few weeks. That’s why I haven’t been here for a long….

    Anyway, I am trying to create a “Random post/page’ link for my site. Read few tutorials on WP and other sites on how to do it. They recommended using a custom page template with the rand function like the following and then assigning that page template to a page.

    query_posts(array('orderby' => 'rand', 'showposts' => 1));
    if (have_posts()) :
    while (have_posts()) : the_post(); ?>

    <h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>

    <?php the_content(); ?>

    <?php endwhile;
    endif; ?>

    My question is, is there a way to create a random posts link on Graphene Child theme without creating a whole new page template? Thanks.


    function le_random_post() {
    if ( isset( $_GET['random'] ) && $_GET['random'] == 1 ) {
    $posts = get_posts( 'post_type=post&orderby=rand&numberposts=1' );
    foreach( $posts as $post ) {
    $link = get_permalink( $post );
    wp_redirect( $link,307 );
    add_action( 'template_redirect','le_random_post' );

    Then add link somewhere, like in the nav manu.



    Wow, fast reply and it works! Thank you Prasanna for coming to my rescue.

Viewing 3 posts - 1 through 3 (of 3 total)

  • You must be logged in to reply to this topic.
Graphene Themes Forum