send message to discord using webhook when ever new post in wordpress in javascript

To send a message to Discord using a webhook whenever a new post is published in WordPress, you can make use of the WordPress REST API and the fetch() function in JavaScript.

First, you need to create a webhook in your Discord server. To do this, go to your Discord server settings, choose Integrations, and create a new Webhooks integration. This will provide you with a webhook URL that you will use in the following steps.

Next, you need to create a JavaScript function that will send a message to the Discord webhook. Here's an example:

index.tsx
function sendMessageToDiscord(message, webhookUrl) {
  fetch(webhookUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ content: message }),
  })
    .then(() => console.log('Message sent to Discord'))
    .catch((error) => console.error('Error sending message to Discord:', error));
}
352 chars
12 lines

Then, you can use the WordPress REST API to execute this function whenever a new post is published. Here's an example:

index.tsx
function sendDiscordMessageOnNewPost() {
  const webhookUrl = 'YOUR_DISCORD_WEBHOOK_URL';
  const apiUrl = 'https://example.com/wp-json/wp/v2/posts';

  fetch(apiUrl)
    .then((response) => response.json())
    .then((posts) => {
      if (posts.length > 0) {
        const latestPost = posts[0]; // Assuming the latest post is the first item in the array

        const message = `New post published: ${latestPost.title.rendered}\n${latestPost.link}`;

        sendMessageToDiscord(message, webhookUrl);
      }
    })
    .catch((error) => console.error('Error retrieving posts from WordPress:', error));
}

// Call the function whenever necessary, for example, on page load
sendDiscordMessageOnNewPost();
709 chars
21 lines

Make sure to replace 'YOUR_DISCORD_WEBHOOK_URL' with the actual webhook URL you obtained earlier.

Note that this example assumes you're using the default WordPress REST API endpoints and that you have appropriate access permissions. You may need to adjust the code depending on the specifics of your WordPress setup.

Remember to include the necessary error handling and security measures to protect your system and user data.

related categories

gistlibby LogSnag