Action Hook Functions – do_action_ref_array()

The do_action_ref_array() function works basically the same way as do_action() does, except for how the arguments are passed.

  • do_action() accepts multiple optional values as additional parameters
  • do_action_ref_array() accepts multiple arguments as an array of arguments. The array of arguments is a required parameter.

The purpose of the do_action_ref_array() function is to pass an object by reference to actions added to a specific hook. Which means the action can just change the object itself without returning it.

<?php
do_action_ref_array( $tag, $args );
?>
  • $tag — The name of the action hook.
  • $args — An array of arguments passed to actions registered for the hook.

Here is an example of where WordPress calls the do_action_ref_array() function. The following example shows the pre_get_posts action hook. The pre_get_posts action hook is fired by WordPress before loading posts from the database and this enables plugins to change how posts are queried.

<?php
do_action_ref_array( 'pre_get_posts', array( &$this ) );
?>
  • first parameter is the pre_get_posts which is the hook’s name.
  • second parameter is an array of query arguments for pulling posts from the database. It is on this array of arguments that our action will act on.

Disclosure : Certain items and links to products/services are affiliate links, and any purchases you make may result in a commission for us. We are paid to give honest opinions on products and/or services on occasion. You will not be charged any additional fees as a result of this.

Example on how to add an action to do_action_ref_array()

Suppose you wanted to randomly order posts on the blog home page rather than have the default ordering by the post date. You would register an action on the pre_get_posts hook and change the order.

Create an empty php file and name it whatever you want, as long as it has a .php extension. Copy the following code into the file and save it. You can personalise the example plugin by changing the header information.

<?php
/*
Plugin Name: Sytech HomePage Random Order Posts
Version: 1.0
Description: Arranges blog post in random order on homepage.
Author: Sydney Chako
Author URI: https://sytech.co.zw
Plugin URI: https://sytech.co.zw/plugin/
*/

add_action( 'pre_get_posts', 'sc_shrop_rand_order_blog_posts' );

function sc_shrop_rand_order_blog_posts( $query ) {
	if ( $query->is_home && empty( $query-> query_vars['suppress_filters'] ) )
		$query->set( 'orderby', 'rand' );
}

?>
  • After saving your plugin file, upload it to the wp-content/plugins folder on your server using FTP.
  • Go to your WordPress installed plugins on admin panel. If everything when well, you should now see your plugin listed among other plugins.
  • Activate it.
  • Then visit the homepage on your site. If the homepage is set to display blog posts, you will see the blog posts randomly ordered.