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:
- Create a public channel and a Telegram BOT (via BotFather).
- Remember the bot token.
- 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 );
Note: Do remember to replace
TOKEN
with your actual bot token andchannel_name
with the name of the channel.
Now, all the new posts will be also published in your Telegram channel.
Top comments (4)
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?
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?!
Don't remember to replace
to
Do remember to replace
Thanks π