Support » Themes and Templates » Functions.php – Random Widget Class

  • Hey Guys,
    I’m trying to edit functions.php so that my widget titles get assigned a random class. In my style.css file I have a bunch of classes named .menu1, .menu2, .menu3 all the way up to .menu13. So what I want is to give each widget the class of anything from menu1 to menu13. It should be easy, I just don’t know enough about PHP.

    This is what I am trying to achieve:

    <?php
    if ( function_exists('register_sidebar') )
    register_sidebar(array('name'=>'Main Sidebar',
            'before_widget' => '<li><div id="%1$s" class="%2$s">',
            'after_widget' => '</div></li>',
            'before_title' => '<h2 class="widgettitle menuRANDOM#">',
            'after_title' => '</h2>',
    		));
    ?>

    If I can use the following random code where I have RANDOM# above:
    <?php echo rand(5, 15);?>

    Thanks for the help!
    Drew

Viewing 5 replies - 1 through 5 (of 5 total)
  • Drew, I suspect you could throw the output of rand(5, 15); into a variable, and then use the variable where RANDOM# is in your register_sidebar array.

    Cheers!

    Thread Starter Drew Baker

    (@dbaker)

    Thanks, that’s what I thought. But how do I do that? I have the idea, just not the skills!

    <?php
    function get_rand(){
       $rand = (string) rand(5,15);
       return $rand;
    }
    if ( function_exists('register_sidebar') )
    register_sidebar(array('name'=>'Main Sidebar',
            'before_widget' => '<li><div id="%1$s" class="%2$s">',
            'after_widget' => '</div></li>',
            'before_title' => '<h2 class="widgettitle menu'.get_rand().'>',
            'after_title' => '</h2>',
    		));
    ?>

    That’s untested, but I think it ought to work okay.

    Thread Starter Drew Baker

    (@dbaker)

    Hey RGlover,
    That worked, except you missed a ” after the rand verible. It worked like this:

    <?php
    function get_rand(){
       $rand = (string) rand(5,15);
       return $rand;
    }
    if ( function_exists('register_sidebar') )
    register_sidebar(array('name'=>'Main Sidebar',
            'before_widget' => '<li><div id="%1$s" class="%2$s">',
            'after_widget' => '</div></li>',
            'before_title' => '<h2 class="widgettitle menu'.get_rand().'">',
            'after_title' => '</h2>',
    		));
    ?>

    Thanks again!

    I have another question for you. How to remove shortcodes from the_excerpt? I have a thread here: http://wordpress.org/support/topic/291261?replies=1

    Glad that worked for you. My bad on the dropped \”

    I’m looking into the shortcode issue. I’ll get back to you in the other thread if I find anything.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Functions.php – Random Widget Class’ is closed to new replies.