简体   繁体   中英

Exact terminology for Adding a Custom code in the footer in wordpress by creating a custom plugin

Right now I am using a shortcode function add_shortcode in display contents in the wordpress site. Now I want to inject a code in the footer by not modify the theme or a child them, instead I will do it via plugin. I just do not know the correct function name to search in google. I always use add_shortcode because it will display on all pages. it is just a custom popup code by me but I have to place the code in the footer

I am not really sure what you are asking? Do you need to know how to actually write a plugin? If this is the case then there is plenty of tutorials covering this topic. Some good resources related to this:

  1. https://developer.wordpress.org/plugins/
  2. https://developer.wordpress.org/plugins/hooks/
  3. https://developer.wordpress.org/reference/hooks/wp_footer/

Add good thing might be to check how an existing plugin which does this is structured, for instance:

https://wordpress.org/plugins/insert-headers-and-footers/#developers

Do add something in the footer on every page you would do something like this, this file should be added under the wp-content/plugins directory:

<?php
/**
 * Plugin Name: Footer plugin
 * Description: Adds text to footer
 * Version: 1.0.0
 * Requires at least: 3.0
 * Tested up to: 6.0
 * Author: Author
 * Text Domain: footer-plugin
**/
class FooterPlugin
{
   public function __construct()
   {
      // hook into wp_footer
      add_action('wp_footer', [$this, 'addFooter']);
   }

   public function addFooter()
   {
      echo '<span>footer text</span>';
   }
}
// initialize the plugin when everything is loaded
add_action('plugins_loaded', function () {
   new FooterPlugin();
});

Another way of doing this would be to replace the content of the footer from the generated output for the page:

class FooterPlugin
{
  /** @var string */
  private $replacement = 'SOME TEXT';

  public function __construct()
  {
     add_action('template_redirect', [$this, 'templateRedirect']);
  }

  /**
   * @var string $content
  **/
  public function templateRedirect(string $content)
  {
     ob_start([$this, 'handleBuffer']);
  }

  /**
   * Replace everything in the footer tag
   * @param string $buffer
   * @return string
  **/
  public function handleBuffer(string $buffer): string
  {
     return preg_replace('/(\<footer\s*.*\>)((.|\n)*)(\<\/footer\>)/', '$1' . $this->replacement . '$3', $buffer);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM