Neep help/guide from -PHP experts ?

Discussion in 'PHP' started by mike4uuu, Apr 19, 2011.

  1. #1
    I'm trying to make this code work . i couldnt figure out why is not working

    I'm trying to insert a custom field name 'views' to each (wordpress) post a random value !

    
    add_action('publish_page', 'add_custom_field_automatically');
    add_action('publish_post', 'add_custom_field_automatically');
    function add_custom_field_automatically($post_ID) {
    	global $wpdb;
           $rand_num = rand(144, 544);
    	if(!wp_is_post_revision($post_ID)) {
    		add_post_meta($post_ID, 'views', '$rand_num', true);
    	}
    }
    
    
    PHP:

     
    mike4uuu, Apr 19, 2011 IP
  2. x319

    x319 Well-Known Member

    Messages:
    90
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    103
    #2
    Hey,

    You wrapped the $rand_num variable in single quotes... You must wrap it in double quotes, in fact, quotes aren't even needed there to pass the value.

    In other words... It should be:
    add_post_meta($post_ID, 'views', $rand_num, true);
    PHP:
     
    x319, Apr 19, 2011 IP
  3. mike4uuu

    mike4uuu Active Member

    Messages:
    832
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    60
    #3
    Thanks its working...

    Is there any way i can change/update (a random num) the value for the custom field name 'views' for old post which is already published and has a custom field value already assign!

    The above code works only for new post in wordpress!
     
    mike4uuu, Apr 19, 2011 IP
  4. x319

    x319 Well-Known Member

    Messages:
    90
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    103
    #4
    Yea, just run a custom SQL command.

    Don't use this, but just for the idea:
    $rand_num = rand(144, 544);
    mysql_query("UPDATE `{$posts_table}` SET `views`='{$rand_num}' WHERE `custom_field`>'';);
    PHP:
     
    x319, Apr 19, 2011 IP
  5. mike4uuu

    mike4uuu Active Member

    Messages:
    832
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    60
    #5
    i try the code below , but no luck , can u help me out
    $rand_num = rand(144, 544);
    mysql_query("update wp_postmeta set meta_value = '[B]{$rand_num}[/B]' WHERE meta_key = 'views';" )
    
    
    PHP:
     
    mike4uuu, Apr 20, 2011 IP