Saturday 21 November 2015

Examples WordPress of Hooks in Action

More than 200 hooks exist in WordPress. Below you will find a few examples of common hooks in use.
Register a Custom Menu in the Admin


function register_my_custom_menu_page() {
 add_menu_page( 'custom menu title', 'custom menu', 'manage_options', 'myplugin/myplugin-admin.php', '', 'dashicons-admin-site', 6 );
}
add_action( 'admin_menu', 'register_my_custom_menu_page' );
 
In the example above you can see the function register_my_custom_menu_page being hooked into the admin_menu action hook. This allows you to run code when the admin menu is being generated. This is most commonly used to add a custom menu link for a plugin or theme.
Change the Excerpt Length
function excerpt_length_example( $words ) { return 15; } add_filter( 'excerpt_length', 'excerpt_length_example' ); In this example, we are using the excerpt_length filter, which provides us with an integer that determines the length used with the_excerpt(). If you are unsure about what value is passed to a filter, you can search the WordPress core code for apply_filters( ‘filter_name’ and look deeper into what is going on with that filter.
Hook into Post Publishing
function publish_post_tweet($post_ID) { global $post; // Code to send a tweet with post info } add_action('publish_post', 'publish_post_tweet'); In the pseudo example above, you can see that we are hooking into an action called “publish_post” which runs when a post is published. You could use this to do something like sending a tweet with information about the published post.
The actual code for this is more complex than we have space to cover, but it serves as a good example of an action you can run when a post is published.

Hook Into Widget Initialization 
function create_my_widget() { register_sidebar(array( 'name' => __( 'My Sidebar', 'mytheme' ), 'id' => 'my_sidebar', 'description' => __( 'The one and only', 'mytheme' ), )); } add_action( 'widgets_init', 'create_my_widget' ); Creating a widget is a very simple and common action to add to a theme or plugin. When you do so, you have to hook into the widget_init action. This hook lets you run your code when widgets are being generated within WordPress, so it’s the perfect hook to add your own widgets at the same time.

Hook Into Front-end Scripts and Styles

function theme_styles() {
 wp_enqueue_style( 'bootstrap_css', get_template_directory_uri() . '/css/bootstrap.min.css' );
 wp_enqueue_style( 'main_css', get_template_directory_uri() . '/style.css' );
 wp_enqueue_script( 'bootstrap_js', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '', true );
 wp_enqueue_script( 'theme_js', get_template_directory_uri() . '/js/theme.js', array('jquery', 'bootstrap_js'), '', true );
}
add_action( 'wp_enqueue_scripts', 'theme_styles' );

 

No comments:

Post a Comment

Popular Articles