DEV Community

Cover image for Sending posts from WordPress site to your Telegram channel
Petro Liashchynskyi
Petro Liashchynskyi

Posted on

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.

Top comments (4)

Collapse
 
rechtvh profile image
Recht • Edited

Using the above code:

Can you add Category like below and is the hook tag correct?

function telegram_send_message( $new_status, $old_status, $post ) {
if( $new_status == 'publish' && $old_status != 'publish' && $post->post_type == 'post' && $category_id=='Category ID') {

Instead of just sending all new posts, how could we add a specific category, so that any new post with a specified category get sent?

Collapse
 
nadiaam profile image
Nadia

I get the error file_get_contents failed to open stream: Connection timed out in ! I search a lot but i didn't find anything to solve my problem! can you help me why i am getting this error?!

Collapse
 
freedom profile image
Freedom

Don't remember to replace

to

Do remember to replace

Collapse
 
liashchynskyi profile image
Petro Liashchynskyi

Thanks 😉