Skip to content

Instantly share code, notes, and snippets.

@alhoseany
Created April 28, 2018 12:21
Show Gist options
  • Save alhoseany/d3c306545bb2506a43672fdd9613a669 to your computer and use it in GitHub Desktop.
Save alhoseany/d3c306545bb2506a43672fdd9613a669 to your computer and use it in GitHub Desktop.
Example of Use cases for Actions
<?php
/**
* code #1 - removes excess Wordpress header tags from default themes.
*/
function clean_wp_header() {
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'rel_canonical');
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'feed_links',2);
remove_action('wp_head', 'feed_links_extra',3);
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
}
add_action('init', 'clean_wp_header');
/**
* code #2 - display Wordpress database query times and memory consumption in footer
*/
function footer_stats_display($visible = false) {
$stat = sprintf( '%d queries in %.3f seconds, using %.2fMB memory',
get_num_queries(),
timer_stop( 0, 3 ),
memory_get_peak_usage() / 1024 / 1024);
echo $visible ? $stat : "&gt;!-- {$stat} -->" ;
}
add_action('wp_footer', 'footer_stats_display', 20);
/**
* code #3 - output the current post/page template name in your header area
*/
function display_template_name() {
global $template;
print_r($template);
}
add_action('wp_head', 'display_template_name');
/**
* code #4 - Change Login Page Logo, URL and title tag
*/
function custom_login_logo() {
echo '<style type="text/css">h1 a { background: url('.get_bloginfo('template_directory').'/companylogo.png) 50% 50% no-repeat !important; }</style>';
}
add_action('login_head', 'custom_login_logo');
function change_wp_login_url() {
return bloginfo('url');
}
add_filter('login_headerurl', 'change_wp_login_url');
unction change_wp_login_title() {
return get_option('blogname');
}
add_filter('login_headertitle', 'change_wp_login_title');
/**
* code #5 - Redirect To Post If Search Results Return One Post
*/
add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
if (is_search()) {
global $wp_query;
if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
exit;
}
}
}
/**
* code #6 - Change user base rewrite url from "/author/name" to "/profile/name"
*/
add_action('init', 'cng_author_base');
function cng_author_base() {
global $wp_rewrite;
$author_slug = 'profile'; // change slug name
$wp_rewrite->author_base = $author_slug;
}
@alhoseany
Copy link
Author

We can also use this function
get_theme_file_uri('/companylogo.png')
https://developer.wordpress.org/reference/functions/get_theme_file_uri/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment