Search code examples
twitterrandomgeneratedphrase

PHP: Using randomly generated and integrating a retweet/share button


I am trying to create a randomly generated phrase that can easily be shared amongst social media websites, specifically twitter. I am using the following PHP code to generate a random phrase.

This code looks in 'responses.txt' for a line with a phrase and I can call that line.

<!-- HEADER -->
<?php
$randomThings = file('**responses.txt**', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

<!-- CALL SCRIPT -->
<?php
echo $randomThings[mt_rand(0,count($randomThings)-1)];
?>

How would I be able to have, for example, retweet button next to this generated line that retweets the phrase with a predetermined #hatchtag (via #[websitename]).

I'm more interested in the twitter aspect, but other social media websites could help other people.


Solution

  • The re-tweet intent itself has problems right now. It's been filed as a bug since November so I don't think you'll want to use the re-tweet functionality from an external website. You can simulate a re-tweet with a regular tweet intent and pre-filling in the text, (which sounds like what you actually want to do). With the tweet intent you send a HTTP request to https://twitter.com/intent/tweet. You could then include the text parameter to pre-fill the text when the HTTP request is sent, or the link is clicked.

    Using your example it would look something like this:

    <!-- HEADER -->
        <?php
        $randomThings = file('**responses.txt**', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        ?>
    
        <!-- CALL SCRIPT -->
        <?php
        $newThings = $randomThings[mt_rand(0,count($randomThings)-1)]; //must evaluate to a string
        echo $newThings;
        echo '<a href="https://twitter.com/intent/tweet?text='.$newThings.'">Link text</a>';
        ?>
    

    this would be an unstyled link instead of a "button" but you can adapt it to be a button using standard HTML/CSS styling.


    ref: https://dev.twitter.com/docs/intents