WordPress: Auto-Post to Telegram Channel (No Plugin)

You can easily increase visitor traffic to your WordPress website by integrating it with a Telegram channel.

However, manually sharing every blog post to the Telegram channel can become a time-consuming task – especially if you publish an article every day.

In this note i will show how to create a callback function that will automatically publish new posts from your WordPress website to the Telegram channel without any plugins.

Cool Tip: How to enable a DEBUG mode in a WordPress! Read more →

WordPress: Auto-Post to Telegram Channel

Step 1: Create a Telegram Channel

To create a Telegram channel:

  • Desktop: In the upper left corner, click on the “☰ Menu”.
  • Android: In the bottom right corner, click on the “ Pencil”.
  • iOS: In the upper right corner, click on the “ New message”.

Select the “ New Channel”, enter the name (title) of the channel, make it public and enter the unique t.me/public_channel_name.

If you want your Telegram channel to be private, you can change its type after you get the channel’s chat ID in the step #4 of this guide.

Step 2: Create a Telegram Bot

To create a new Telegram bot, search for a @BotFather in the main “ Search” field, start a conversation and send the commands as follows:

: /newbot

: Alright, a new bot. How are we going to call it?
    Please choose a name for your bot.

: Display Bot Name

: Good. Now let's choose a username for your bot. It must end in `bot`.
    Like this, for example: TetrisBot or tetris_bot.

: username_bot

: Done!
    ....
    Use this token to access the HTTP API:
    5082654068:AAF7quCLZ4xuTq2FBdo3POssdJsM_FRHwTs

Step 3: Add the Bot to the Telegram Channel Admins

To add your bot to administrators of the Telegram channel, open the channel settings, choose “Administrators” → “Add Administrator”, search for the earlier created @username_bot and promote it to “Admins” that will automatically subscribe it to the channel.

Step 4: Get the Telegram Channel’s Chat ID

To get the chat ID of the Telegram channel, open the below URL in your web-browser and send some message to this channel using the token of the Telegram bot created earlier:

https://api.telegram.org/bot<botToken>/sendMessage?chat_id=@<pubChannelName>&text=some_message

For example:

https://api.telegram.org/bot5082654068:AAF7quCLZ4xuTq2FBdo3POssdJsM_FRHwTs/sendMessage?chat_id=@public_channel_name&text=some_message

This way you will get the chat ID of your public Telegram channel:

...
chat:	
  id:        -1002623654901
  title:     "<channel_title>"
  username:  "<public_channel_name>"
  type:      "channel"

Step 5: Edit functions.php

The hooks and callback functions in the WordPress should be registered in a child theme’s functions.php file.

To edit this file, you can log in to your WordPress “Dashboard”, in the left sidebar hover over the “Appearance” and click on the “Theme Editor”.

Then, on the right, under the “Theme Files”, select the “Theme Functions (functions.php)”.

This will bring you up to the functions.php code editor.

Alternatively you can access the functions.php file over FTP or SSH on this path:

/wp-content/themes/<child_theme>/functions.php

About Actions & Callbacks

Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur.

To trigger an action firstly you need to write a custom function known as a callback, and then register it with a WordPress hook using the add_action function:

add_action( '<hook>', '<callback>', <priority>, <args> )
Argument Description
hook The name of the action to add the callback to (hooks list).
callback The callback to be run when the action is called.
priority Used to specify the order in which the functions associated with a particular action are executed. Lower numbers correspond with earlier execution (default value: 10).
args The number of arguments the function accepts (default value: 1).

Step 6: Send New WordPress Posts to Telegram

Here is a callback function post_to_telegram that will be trigger by the transition_post_status hook (fires when a post is transitioned from one status to another i.e. in our case when the post changes it status to ‘publish’ from any ‘non-publish’ status):

<?php
  function post_to_telegram( $new_status, $old_status, $post ) {
  if( $new_status == 'publish' &&
      $old_status != 'publish' &&
      $post->post_type == 'post') {
  $apiToken = "5082654068:AAF7quCLZ4xuTq2FBdo3POssdJsM_FRHwTs";
  $post_url = get_permalink($post->ID);
  $post_title = get_the_title($post->ID);
  // HTML tags supported by Telegram (https://core.telegram.org/bots/api#html-style)
  $arr = array( 'a' => array(
                  'href' => array()
                ),
                'b' => array(),
                'code' => array(),
                'del' => array(),
                'em' => array(),
                'i' => array(),
                'ins' => array(),
                'pre' => array(),
                's' => array(),
                'span' => array(),
                'strike' => array(),
                'strong' => array(),
                'tg-spoiler' => array(),
                'u' => array()
              );
  // Get the post content but keep the supported HTML tags only
  $post_content = wp_kses(get_the_content($more_link_text = "
\n&#128214; Continue Reading", false, $post->ID), $arr);
  $message = sprintf( "&#127760; <a href=\"%s\">%s</a>\n\n%s", $post_url,
                                                               $post_title,
                                                               $post_content );
  $data = [
      'chat_id' => '-1002623654901',
      'text' => $message,
      'parse_mode' => 'html'
  ];
  $response = file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" .
                                 http_build_query($data));
  }
  }
  add_action( 'transition_post_status', 'post_to_telegram', 10, 3 );
?>

 

To start using this hook and the callback function, simply copy/paste the code above to your WordPress child theme’s functions.php file and replace the data in bold with your own.

In case of the error below, look at your php.ini, search for allow_url_fopen = Off and allow it by setting the value to On:

PHP Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in <path>/functions.php on line <number>
PHP Warning: file_get_contents(https://api.telegram.org/…): failed to open stream: no suitable wrapper could be found in <path>/functions.php on line <number>

  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

How to Change the Display Name of a WordPress User Account?

You can change the display name of your WordPress account which show on a WordPress post or...

How to add a new category in WordPress?

1. Login to your WordPress admin dashboard.2. Under the dashboard menu, hover your mouse on Posts...

How to remove the Uncategorized category from WordPress?

You can not remove "Uncategorized" Category but you can rename it1. Login to your WordPress admin...

How to remove a category in WordPress?

If you want to remove WordPress category then follow this instruction:1. Login to your WordPress...

How to Install a New Theme in WordPress?

You can install a new WordPress theme without having any technical knowledge. It"s so easy and...