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.
Cool Tip:Ā How to send a message to a Telegram channel using PHP!Ā Read more ā
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:
For example:
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📖 Continue Reading", false, $post->ID), $arr);
$message = sprintf( "🌐 <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 );
?>
Here is how the new WordPress post published to the Telegram channel will look like:
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>