Sending posts from WordPress site to your Telegram channel

liashchynskyi

Petro Liashchynskyi

Posted on February 8, 2020

Sending posts from WordPress site to your Telegram channel

Hi! I'm gonna show you how you can send a message (WordPress post) to a Telegram channel. All you need is a public Telegram channel and a bot. The last one you can create via BotFather in Telegram.

Steps:

  1. Create a public channel and a Telegram BOT (via BotFather).
  2. Remember the bot token.
  3. Add the bot to administrators of previously created channel.

At the final step you should add the following code to your functions.php:


function telegram_send_message( $new_status, $old_status, $post ) {
  if( $new_status == 'publish' &&  $old_status != 'publish' && $post->post_type == 'post') {
    $apiToken = "TOKEN";
    $data = [
      'chat_id' => '@channel_name',
      'text' => "\nRead more: " . get_permalink($post->ID)
    ];
   $response = file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" . http_build_query($data) );
  }
}
add_action( 'transition_post_status', 'telegram_send_message', 10, 3 );
Enter fullscreen mode Exit fullscreen mode

Note: Do remember to replace TOKEN with your actual bot token and channel_name with the name of the channel.

Now, all the new posts will be also published in your Telegram channel.

💖 💪 🙅 🚩
liashchynskyi
Petro Liashchynskyi

Posted on February 8, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related