Return to Support

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

Home Forums Graphene WordPress theme Support Can I insert the PHP code for random post link on Child Theme?

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #8514
    sanuja.com
    Participant

    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.

    <?php
    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.

    #41354
    Prasanna SP
    Member
    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 );
    exit;
    }
    }
    add_action( 'template_redirect','le_random_post' );

    Then add http://sanuja.com/blog/?random=1 link somewhere, like in the nav manu.

    #41355
    sanuja.com
    Participant

    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.