0

I want to populate an array with post titles and change the title of the post (which is a draft) to a random member of the array of titles. Something like this?

function set_random_title ($title)
{
  $title1[0] = "a title";
  $title1[1] = "another title";
  /*and so on*/
  $randomize = rand(0,1);
  return ($title1[$randomize]);
}
add_filter('the_title', 'set_random_title', 10, 2); 
3
  • Wait, this actually kind of works...
    – atub
    Commented Nov 21, 2015 at 2:19
  • Are your trying to randomize the title every time the post displays?
    – s_ha_dum
    Commented Nov 21, 2015 at 3:36
  • All I care about is a random title when the post goes live. I'm noticing that my code randomizes the titles every time I reload the all posts page (drafts or otherwise) though if the post is already posted the "live" title stays what it was when it was posted.
    – atub
    Commented Nov 21, 2015 at 3:56

1 Answer 1

0

You could randomize the array with array_rand which will return the key, and then use array_flip to switch the key with the value (ie get your random title).

Hook into save_post, so the random title is assigned and update the DB when you actually publish a post as opposed to using the_title filter.

function save_title( $post_id ){

    global $wpdb;

    $title = array (
        '1' => 'another title',
        '2' => 'here is again, a title',
        '3' => 'random titles',
        '4' => 'RANDOM TITLE',
        '5' => 'ANOTHER RanDom TiTlE!',
        '6' => 'titles everywhere'
    );

    $wpdb->update( $wpdb->posts, 
        array( 'post_title' =>  array_rand( array_flip( $title ) ) ),
        array( 'ID' => $post_id ) ); 
}

add_action( 'save_post', 'save_title');
2
  • Thanks Tim, I'm going to investigate your solution, really appreciate it!
    – atub
    Commented Nov 21, 2015 at 20:34
  • Not a problem at all atub :)
    – Tim Elsass
    Commented Nov 23, 2015 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.