WordPress add a function

If you want to add custom code to the theme, then we suggest you to install and activate child theme. Otherwise, after each update of Kalium you have to re-insert that custom code you had previously used.

We occasionally ask our users to add custom code to their WordPress website to add simple features to GiveWP. We do this because 80% of GiveWP users don’t need that feature so we don’t want to add it to the core plugin. But where and how exactly are you supposed to add this custom code to your website? This article gives you an overview of why and how to do this right.

Dispelling the Myths of Custom Code in WordPress

Experienced developers know the best way to extend the functionality of a plugin is by adding their own code into what’s often called a “Functionality Plugin“. You might think that you can simply go into the plugin files and change them there. While it is true that you CAN do that, it’s not “best practice” because the next time your plugin is updated you will lose that custom code.

Another thing you’ll often hear is that you should just put this code into your theme’s `functions.php` file. Again, while this will work, it’s not considered “best practice” because your site most likely will update it’s theme in the near future and again you’ll lose that added functionality to the plugin once your theme changes.

So, the GiveWP Support team gave you some custom code to use on your website, or you pulled it from our documentation. But you CAN’T change the plugin, you can’t add it to your theme’s `functions.php` file, and you don’t know how to create a Functionality Plugin. What are you supposed to do?

It is not “Best Practice” to put custom plugin code in your theme’s functions.php file.

Use the “Code Snippets” plugin

WordPress add a function

The “Code Snippets” plugin is an easy and safe way to insert custom functions into your WordPress website without having to learn how to use a Custom Functionality plugin. It’s also recommend because it allows you to avoid potentially taking down the site if a custom snippet is missing some syntax or throws an error. You can avoid issues like this for example:

WordPress add a function
This tool helps folks to avoid adding a snippet that breaks the site. Check your snippets before activating!

To get started:

  • Install the Code Snippets just like any other WordPress plugin and activate it.
  • After it is activated, go to to the “Snippets” page and click “Add New” to add your custom code snippet.
  • Paste the code and add a description or tags for the snippet, then click “Save Changes and Activate” to see the snippet in action.
  • If the code provided is correct, the snippet will run.
WordPress add a function
An example of a simple translation snippet

The snippets page includes some example snippets for reference, those can be deleted as needed. Included in those examples are snippets that can be helpful in sorting snippets on this page by name or by date if you plan to add multiple snippets.

WordPress add a function

If needed, the snippet settings can be adjusted and configured under Snippets > Settings. This will allow you to adjust general settings and settings within the editors. Be sure to click “Save Changes” when finished.

With Great Power Comes Great Responsibility

We provide this documentation in order to help our GiveWP users to add custom functions. Please be aware that this type of customization can create conflicts or issues on your website. We always highly recommend that you add custom functions in an environment that allows you to quickly undo what you’ve done without causing issues your live site. We also recomend you test thoroughly before going live. Here are a few important things to keep in mind

  • Use Desktop Server. We recommend it for local development. Read our review of it here.
  • Make backups before you do this work, and know how to restore your backup immediately.
  • Learn how to deactivate all your plugins via (S)FTP with this WPBeginner tutorial.

Last updated 1 year ago

Thank you for your feedback!

Loading...

Sending feedback...

There was an error recording your feedback. We have been notified and will look into the problem. Please try again later.

Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Plugins can specify that one or more of its PHP functions are executed at these points, using the Action API.


add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );
0 string Required

The name of the action to add the callback to.

add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );
1 callable Required

The callback to be run when the action is called.

add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );
2 int Optional

Used to specify the order in which the functions associated with a particular action are executed.
Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.

Default:

add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );
3

add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );
4 int Optional

The number of arguments the function accepts.

Default:

add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );
5


true Always returns true.


add_action( $hook, $function_to_add, $priority, $accepted_args );

To find out the number and name of arguments for an action, simply search the code base for the matching do_action() call. For example, if you are hooking into ‘save_post’, you would find it in post.php:

do_action( 'save_post', $post_ID, $post, $update );

Your add_action call would look like:

add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );

And your function would be:

function wpdocs_my_save_post( $post_ID, $post, $update ) {
   // do stuff here
}

File:

add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );
6. View all references

function add_action( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) {
	return add_filter( $hook_name, $callback, $priority, $accepted_args );
}


UsesUsesDescriptionadd_filter() wp-includes/plugin.php

Adds a callback function to a filter hook.

Used ByUsed ByDescriptionwp_enqueue_block_support_styles() wp-includes/script-loader.php

Hooks inline styles in the proper place, depending on the active theme.

_wp_theme_json_webfonts_handler() wp-includes/script-loader.php

Runs the theme.json webfonts handler.

wp_enqueue_block_style() wp-includes/script-loader.php

Enqueues a stylesheet for a specific block.

locate_block_template() wp-includes/block-template.php

Finds a block template with equal or higher specificity than a given PHP template file.

WP_Sitemaps::init() wp-includes/sitemaps/class-wp-sitemaps.php

Initiates all sitemap functionality.

WP_Recovery_Mode::initialize() wp-includes/class-wp-recovery-mode.php

Initialize recovery mode for the current request.

WP_Site_Health::__construct() wp-admin/includes/class-wp-site-health.php

WP_Site_Health constructor.

wp_is_site_initialized() wp-includes/ms-site.php

Checks whether a site is initialized.

register_and_do_post_meta_boxes() wp-admin/includes/meta-boxes.php

Registers the default post meta boxes, and runs the

add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );
7 actions.

WP_Privacy_Policy_Content::text_change_check() wp-admin/includes/class-wp-privacy-policy-content.php

Quick check if any privacy info has changed.

WP_Roles::get_roles_data() wp-includes/class-wp-roles.php

Gets the available roles data.

WP_Widget_Text::_register_one() wp-includes/widgets/class-wp-widget-text.php

Add hooks for enqueueing assets when registering all widget instances of this widget class.

WP_Widget_Custom_HTML::_register_one() wp-includes/widgets/class-wp-widget-custom-html.php

Add hooks for enqueueing assets when registering all widget instances of this widget class.

WP_Widget_Media::_register_one() wp-includes/widgets/class-wp-widget-media.php

Add hooks while registering all widget instances of this widget class.

_WP_Editors::enqueue_default_editor() wp-includes/class-wp-editor.php

Enqueue all editor scripts.

_wp_delete_customize_changeset_dependent_auto_drafts() wp-includes/nav-menu.php

Deletes auto-draft posts associated with the supplied changeset.

WP_Customize_Manager::import_theme_starter_content() wp-includes/class-wp-customize-manager.php

Imports theme starter content into the customized state.

WP_Post_Type::register_meta_boxes() wp-includes/class-wp-post-type.php

Registers the post type meta box if a custom callback was specified.

WP_Post_Type::add_hooks() wp-includes/class-wp-post-type.php

Adds the future post hook action for the post type.

WP_Customize_Widgets::selective_refresh_init() wp-includes/class-wp-customize-widgets.php

Adds hooks for selective refresh.

WP_Customize_Selective_Refresh::init_preview() wp-includes/customize/class-wp-customize-selective-refresh.php

Initializes the Customizer preview.

WP_Customize_Selective_Refresh::enqueue_preview_scripts() wp-includes/customize/class-wp-customize-selective-refresh.php

Enqueues preview scripts.

WP_Customize_Selective_Refresh::__construct() wp-includes/customize/class-wp-customize-selective-refresh.php

Plugin bootstrap for Partial Refresh functionality.

rest_api_default_filters() wp-includes/rest-api.php

Registers the default REST API filters.

WP_Customize_Setting::aggregate_multidimensional() wp-includes/class-wp-customize-setting.php

Set up the setting for aggregated multidimensional values.

wp_admin_bar_customize_menu() wp-includes/admin-bar.php

Adds the “Customize” link to the Toolbar.

WP_Widget_Factory::__construct() wp-includes/class-wp-widget-factory.php

PHP5 constructor.

WP_Customize_Site_Icon_Control::__construct() wp-includes/customize/class-wp-customize-site-icon-control.php

Constructor.

WP_Customize_Nav_Menu_Item_Setting::__construct() wp-includes/customize/class-wp-customize-nav-menu-item-setting.php

Constructor.

WP_Customize_Nav_Menus::customize_preview_init() wp-includes/class-wp-customize-nav-menus.php

Adds hooks for the Customizer preview.

WP_Customize_Nav_Menus::__construct() wp-includes/class-wp-customize-nav-menus.php

Constructor.

WP_Site_Icon::__construct() wp-admin/includes/class-wp-site-icon.php

Registers actions and filters.

login_header() wp-login.php

Output the login page header.

Language_Pack_Upgrader::bulk_upgrade() wp-admin/includes/class-language-pack-upgrader.php

Bulk upgrade language packs.

Theme_Upgrader::install() wp-admin/includes/class-theme-upgrader.php

Install a theme package.

Theme_Upgrader::upgrade() wp-admin/includes/class-theme-upgrader.php

Upgrade a theme.

Plugin_Upgrader::install() wp-admin/includes/class-plugin-upgrader.php

Install a plugin package.

Plugin_Upgrader::upgrade() wp-admin/includes/class-plugin-upgrader.php

Upgrade a plugin.

WP_List_Table::__construct() wp-admin/includes/class-wp-list-table.php

Constructor.

WP_Theme_Install_List_Table::prepare_items() wp-admin/includes/class-wp-theme-install-list-table.phpwp_plugin_update_rows() wp-admin/includes/update.php

Adds a callback to display update information for plugins with updates available.

wp_theme_update_rows() wp-admin/includes/update.php

Adds a callback to display update information for themes with updates available.

uninstall_plugin() wp-admin/includes/plugin.php

Uninstalls a single plugin.

add_menu_page() wp-admin/includes/plugin.php

Adds a top-level menu page.

add_submenu_page() wp-admin/includes/plugin.php

Adds a submenu page.

WP_Plugin_Install_List_Table::prepare_items() wp-admin/includes/class-wp-plugin-install-list-table.phpWP_Internal_Pointers::enqueue_scripts() wp-admin/includes/class-wp-internal-pointers.php

Initializes the new feature pointers.

Custom_Image_Header::__construct() wp-admin/includes/class-custom-image-header.php

Constructor – Register administration header callback.

Custom_Image_Header::init() wp-admin/includes/class-custom-image-header.php

Set up the hooks for the Custom Header admin page.

Custom_Background::__construct() wp-admin/includes/class-custom-background.php

Constructor – Registers administration header callback.

Custom_Background::init() wp-admin/includes/class-custom-background.php

Sets up the hooks for the Custom Background admin page.

WP_Customize_Manager::customize_preview_init() wp-includes/class-wp-customize-manager.php

Prints JavaScript settings.

WP_Customize_Manager::setup_theme() wp-includes/class-wp-customize-manager.php

Starts preview and customize theme.

WP_Customize_Manager::__construct() wp-includes/class-wp-customize-manager.php

Constructor.

wp_cron() wp-includes/cron.php

Register _wp_cron() to run on the {@see ‘wp_loaded’} action.

_custom_header_background_just_in_time() wp-includes/theme.php

Registers the internal custom header and background routines.

add_thickbox() wp-includes/general-template.php

Enqueues the default ThickBox js and css.

wp_auth_check_load() wp-includes/functions.php

Loads the auth check for monitoring whether the user is still logged in.

wp_maybe_load_widgets() wp-includes/functions.php

Determines if Widgets library should be loaded.

WP_Widget_Recent_Comments::__construct() wp-includes/widgets/class-wp-widget-recent-comments.php

Sets up a new Recent Comments widget instance.

WP_Embed::__construct() wp-includes/class-wp-embed.php

Constructor

WP_Admin_Bar::add_menus() wp-includes/class-wp-admin-bar.php

Adds menus to the admin bar.

WP_Admin_Bar::initialize() wp-includes/class-wp-admin-bar.php

Initializes the admin bar.

register_activation_hook() wp-includes/plugin.php

Set the activation hook for a plugin.

register_deactivation_hook() wp-includes/plugin.php

Sets the deactivation hook for a plugin.

WP_Customize_Setting::preview() wp-includes/class-wp-customize-setting.php

Add filters to supply the setting’s value when accessed.

wp_enqueue_media() wp-includes/media.php

Enqueues all scripts, styles, settings, and templates necessary to use all media JS APIs.

wp_playlist_scripts() wp-includes/media.php

Outputs and enqueues default scripts and styles for playlists.

WP_Rewrite::wp_rewrite_rules() wp-includes/class-wp-rewrite.php

Retrieves the rewrite rules.

WP_Rewrite::flush_rules() wp-includes/class-wp-rewrite.php

Removes rewrite rules and then recreate rewrite rules.

add_feed() wp-includes/rewrite.php

Adds a new feed type like /atom1/.

WP_Scripts::__construct() wp-includes/class-wp-scripts.php

Constructor.

WP_Customize_Header_Image_Control::prepare_control() wp-includes/customize/class-wp-customize-header-image-control.phpWP_Customize_Widgets::customize_preview_init() wp-includes/class-wp-customize-widgets.php

Adds hooks for the Customizer preview.

WP_Customize_Widgets::__construct() wp-includes/class-wp-customize-widgets.php

Initial loader.

WP_Customize_Widgets::schedule_customize_register() wp-includes/class-wp-customize-widgets.php

Ensures widgets are available for all types of previews.

wp_set_comment_status() wp-includes/comment.php

Sets the status of a comment.

_WP_Editors::editor_settings() wp-includes/class-wp-editor.phpwp_print_media_templates() wp-includes/media-template.php

Prints the templates used in the media manager.


ChangelogVersionDescription1.2.0Introduced.

  1. You must log in to vote on the helpfulness of this noteVote results for this note: 45You must log in to vote on the helpfulness of this note

    Contributed by Codex

    Using with a Class
    To use

    add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );
    8 when your plugin or theme is built using classes, you need to use the array callable syntax. You would pass the function to
    add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );
    8 as an array, with
    function wpdocs_my_save_post( $post_ID, $post, $update ) {
       // do stuff here
    }
    0 as the first element, then the name of the class method, like so:

    /**
     * Class WP_Docs_Class.
     */
    class WP_Docs_Class {
    
    	/**
    	 * Constructor
    	 */
    	public function __construct() {
    		add_action( 'save_post', array( $this, 'wpdocs_save_posts' ) );
    	}
    
    	/**
    	 * Handle saving post data.
    	 */
    	public function wpdocs_save_posts() {
    		// do stuff here...
    	}
    }
    
    $wpdocsclass = new WP_Docs_Class();

    • Don’t use this in themes you want to distribute. It won’t be possible to remove the action as $this would be a different value; — By theking2 —

    Log in to add feedback
  2. You must log in to vote on the helpfulness of this noteVote results for this note: 23You must log in to vote on the helpfulness of this note

    Contributed by Codex

    Using with static functions in a class
    If the class is called staticly the approach has to be like below as

    function wpdocs_my_save_post( $post_ID, $post, $update ) {
       // do stuff here
    }
    0 is not available. This also works if class is extended. Use the following:

    /**
     * Class WP_Docs_Static_Class.
     */
    class WP_Docs_Static_Class {
    
    	/**
    	 * Initializer for setting up action handler
    	 */
    	public static function init() {
    		add_action( 'save_post', array( get_called_class(), 'wpdocs_save_posts' ) );
    	}
    
    	/**
    	 * Handler for saving post data.
    	 */
    	public static function wpdocs_save_posts() {
    		// do stuff here...
    	}
    }
    
    WP_Docs_Static_Class::init();

    • If we have callback function which is static in another class, we can use the following:

      function wpdocs_my_save_post( $post_ID, $post, $update ) {
         // do stuff here
      }
      2 — By sumeetboga95 —

    Log in to add feedback
  3. You must log in to vote on the helpfulness of this noteVote results for this note: 9You must log in to vote on the helpfulness of this note

    Contributed by Codex

    Simple Hook
    To email some friends whenever an entry is posted on your blog:

    /**
     * Send email to my friends.
     *
     * @param int $post_id Post ID.
     * @return int Post ID.
     */
    function wpdocs_email_friends( $post_id ) {
    	$friends = '[email protected], [email protected]';
    	wp_mail( $friends, "sally's blog updated", 'I just put something on my blog: http://blog.example.com' );
    
    	return $post_id;
    }
    add_action( 'publish_post', 'wpdocs_email_friends' );

    Log in to add feedback
  4. You must log in to vote on the helpfulness of this noteVote results for this note: 9You must log in to vote on the helpfulness of this note

    Contributed by mkormendy

    To pass a variable to the called function of the action, you can use closures (since PHP 5.3+) when the argument is not available in the original coded do_action. For example:

    add_action('wp_footer', function($arguments) use ($myvar) { 
        echo $myvar;
    }, $priority_integer, $accepted_arguments_integer);

    • Don’t use anonymous closures on themes you want to distribute. It would be impossible to remove the action. Instead use closure variables:

      function wpdocs_my_save_post( $post_ID, $post, $update ) {
         // do stuff here
      }
      3 which can be removed with:
      function wpdocs_my_save_post( $post_ID, $post, $update ) {
         // do stuff here
      }
      4 with the advantage that typos in the closure name will yeild a helpfull Undfined variable error on typos. — By theking2 —

    Log in to add feedback
  5. You must log in to vote on the helpfulness of this noteVote results for this note: 5You must log in to vote on the helpfulness of this note

    Contributed by Anthony Hortin

    Related:

    do_action()
    remove_action()

    Log in to add feedback
  6. You must log in to vote on the helpfulness of this noteVote results for this note: 3You must log in to vote on the helpfulness of this note

    Contributed by Lucas Bustamante

    Passing parameters while using in a Class
    To pass parameters to your method in a Class while calling it with add_action, you can do as following:

    public function __construct() {
        // Actions
        add_action('init', array($this, 'call_somefunction'));
    }
    
    /**
     *    Intermediate function to call add_action with parameters
     */
    public function call_somefunction() {
        $this->somefunction('Hello World');
    }
    
    /**
     *    Actual function that does something
     */
    public function somefunction($text) {
        echo $text;
    }

    Log in to add feedback
  7. You must log in to vote on the helpfulness of this noteVote results for this note: 3You must log in to vote on the helpfulness of this note

    Contributed by Christian Saborio

    How to add an action that calls a function (with parameters) from an instantiated class:

    do_action( 'save_post', $post_ID, $post, $update );
    0

    Log in to add feedback
  8. You must log in to vote on the helpfulness of this noteVote results for this note: 1You must log in to vote on the helpfulness of this note

    Contributed by Codex

    Accepted Arguments
    A hooked function can optionally accept arguments from the action call, if any are set to be passed. In this simplistic example, the

    function wpdocs_my_save_post( $post_ID, $post, $update ) {
       // do stuff here
    }
    5 function takes the
    function wpdocs_my_save_post( $post_ID, $post, $update ) {
       // do stuff here
    }
    6 argument, which is automatically passed to when the
    function wpdocs_my_save_post( $post_ID, $post, $update ) {
       // do stuff here
    }
    7 call using the
    function wpdocs_my_save_post( $post_ID, $post, $update ) {
       // do stuff here
    }
    8 filter hook is run.

    do_action( 'save_post', $post_ID, $post, $update );
    1

    Log in to add feedback
  9. You must log in to vote on the helpfulness of this noteVote results for this note: -3You must log in to vote on the helpfulness of this note

    Contributed by theking2

    To prevent runtime errors due to easy typo errors (defensive programming) and prevent pollution of the global namespace use closures instead of function names. The sample code adjusted:

    do_action( 'save_post', $post_ID, $post, $update );
    2

    • Do not do this in themes or plugins you intend to distribute, as it will prevent others from removing your callables if desired. — By crstauf —

      How do I add a function to a specific page in WordPress?

      You can use the is_page() conditional tag to target a specific WordPress page to make your changes. You can also use the is_single() tag to target an individual post in the exact same way. You'll do a conditional check for this page (or post if using is_single() instead) by targeting the page ID, title, or slug.

      How to add custom function to functions php in WordPress?

      To add your code to functions. php go to Appearance > Editor then select Theme Functions file and paste your code in the end of editor and click Update File: If there is a syntax error on that code, your site will stop working! Before making changes backup your functions.

      How do I call a custom function in WordPress?

      So effectively:.
      Rename your function to something a bit more unique, like naser_send_notitification().
      Put this code in /wp-content/mu-plugins/custom-funtions.php..

      How do I trigger a function in WordPress?

      You have three options for this:.
      Code the function directly into your theme template file (or another plugin file)..
      Attach it to an action hook..
      Attach it to a filter hook..