Guest User

Wordpress to Discord - Without @everyone

a guest
Apr 14th, 2021
222
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. /*
  3. * Plugin Name: Post to Discord
  4. * Plugin URI: https://badecho.com
  5. * Description: Announces new WordPress posts on Discord.
  6. * Version: 1.0
  7. * Author: Matt Weber
  8. * Author URI: https://badecho.com
  9. */
  10.  
  11. function post_to_discord($new_status, $old_status, $post) {
  12. if(get_option('discord_webhook_url') == null)
  13. return;
  14.  
  15. if ( $new_status != 'publish' || $old_status == 'publish' || $post->post_type != 'post')
  16. return;
  17.  
  18. $webhookURL = get_option('discord_webhook_url');
  19. $id = $post->ID;
  20.  
  21. $author = $post->post_author;
  22. $authorName = get_the_author_meta('display_name', $author);
  23. $postTitle = $post->post_title;
  24. $permalink = get_permalink($id);
  25. $message = $authorName . " just posted \"" . $postTitle . "\" for your reading pleasure: " . $permalink;
  26.  
  27. $postData = array('content' => $message);
  28.  
  29. $curl = curl_init($webhookURL);
  30. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
  31. curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postData));
  32. curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
  33. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  34. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
  35. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
  36.  
  37. $response = curl_exec($curl);
  38. $errors = curl_error($curl);
  39.  
  40. log_message($errors);
  41. }
  42.  
  43. function log_message($log) {
  44. if (true === WP_DEBUG) {
  45. if (is_array($log) || is_object($log)) {
  46. error_log(print_r($log, true));
  47. } else {
  48. error_log($log);
  49. }
  50. }
  51. }
  52.  
  53. add_action('transition_post_status', 'post_to_discord', 10, 3);
  54.  
  55. function post_to_discord_section_callback() {
  56. echo "<p>A valid Discord Webhook URL to the announcements channel is required.";
  57. }
  58.  
  59. function post_to_discord_input_callback() {
  60.  
  61. echo '<input name="discord_webhook_url" id="discord_webhook_url" type="text" value="' . get_option('discord_webhook_url') . '">';
  62. }
  63.  
  64. function post_to_discord_settings_init() {
  65. add_settings_section(
  66. 'discord_webhook_url',
  67. 'Post to Discord',
  68. 'post_to_discord_section_callback',
  69. 'general'
  70. );
  71.  
  72. add_settings_field(
  73. 'discord_webhook_url',
  74. 'Discord Webhook URL',
  75. 'post_to_discord_input_callback',
  76. 'general',
  77. 'discord_webhook_url'
  78. );
  79.  
  80. register_setting( 'general', 'discord_webhook_url' );
  81. }
  82.  
  83. add_action( 'admin_init', 'post_to_discord_settings_init' );
RAW Paste Data