WordPress.org

Ready to get started?Download WordPress

Forums

Modifying Matt's Random Post Plugin (10 posts)

  1. umair
    Member
    Posted 6 years ago #

    I want to modify Matt's Random Post Plugin so that it displays post from a particular category?

    This is the proginal query present in the plugin:

    function matt_random_redirect() {
    	global $wpdb;
    	$random_id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_type = 'post' AND post_password = '' AND post_status = 'publish' ORDER BY RAND() LIMIT 1");
    	wp_redirect( get_permalink( $random_id ) );
    	exit;
    }
    
    if ( isset( $_GET['random'] ) )
    	add_action( 'template_redirect', 'matt_random_redirect' );
    
    ?>

    I am adding AND post_category='2' in $random_id
    but it start displaying only the same post again n again and donot randomize :( ??

  2. umair
    Member
    Posted 6 years ago #

    any one >?

  3. umair
    Member
    Posted 6 years ago #

    any one
    ?

  4. umair
    Member
    Posted 6 years ago #

    once again ... can any one help me on this ?

  5. umair
    Member
    Posted 6 years ago #

    ??

  6. umair
    Member
    Posted 6 years ago #

    i am going to make a world record out of this ....

  7. umair
    Member
    Posted 6 years ago #

    do you have any idea how to solve it, if yes... please update.

  8. umair
    Member
    Posted 6 years ago #

    am i near?

  9. umair
    Member
    Posted 6 years ago #

    no ... i think i am not ... :(

  10. alexleonard
    Member
    Posted 6 years ago #

    Hi umair,

    My php knowledge isn't the best and this might be incorrect, so someone please correct me if I'm wrong, but I can't ignore that many pleas for help!

    <?php
    function matt_random_redirect() {global $wpdb; $random_id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_type = 'post' AND post_password = '' AND post_status = 'publish' AND $wpdb->term_taxonomy.term_id = 1,2,3 AND $wpdb->term_taxonomy.taxonomy = 'category' ORDER BY RAND() LIMIT 1"); 
    
    wp_redirect( get_permalink( $random_id ) ); exit; } if ( isset( $_GET['random'] ) ) add_action( 'template_redirect', 'matt_random_redirect' ); ?>

    I may be missing out on LEFT JOIN or something more complicated. The problem you've had is something to do with the fact that as this is a direct database query you can't just use AND post_category = "2" as that's not correct for $wpdb->posts, I think...

    There's a good bit more information on this page:

    Displaying Posts Using a Custom Select Query

    Which might be fairly relevant (especially the example at the very end of the page).

    There's also more information here:

    Function Reference: wpdb_Class

    Where you should look at the information on using get_var as this is what Matt has utilised for this plugin.

    Hopefully that helps, again I could be completely wrong...

Topic Closed

This topic has been closed to new replies.

About this Topic