Skip to content

Instantly share code, notes, and snippets.

@kanakiyajay
Created January 26, 2015 14:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save kanakiyajay/8476dd52b4782920692f to your computer and use it in GitHub Desktop.
Save kanakiyajay/8476dd52b4782920692f to your computer and use it in GitHub Desktop.
Collections of code for your wordpress functions.php file
// CUSTOM ADMIN MENU LINK FOR ALL SETTINGS
function all_settings_link() {
add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
}
add_action('admin_menu', 'all_settings_link');
add_filter( 'login_headerurl', 'namespace_login_headerurl' );
/**
* Replaces the login header logo URL
*
* @param $url
*/
function namespace_login_headerurl( $url ) {
$url = home_url( '/' );
return $url;
}
add_filter( 'login_headertitle', 'namespace_login_headertitle' );
/**
* Replaces the login header logo title
*
* @param $title
*/
function namespace_login_headertitle( $title ) {
$title = get_bloginfo( 'name' );
return $title;
}
add_action( 'login_head', 'namespace_login_style' );
/**
* Replaces the login header logo
*/
function namespace_login_style() {
echo '<style>.login h1 a { background-image: url( ' . get_template_directory_uri() . '/images/logo.png ) !important; }</style>';
}
// REMOVE THE WORDPRESS UPDATE NOTIFICATION FOR ALL USERS EXCEPT SYSADMIN
global $user_login;
get_currentuserinfo();
if ($user_login !== "admin") { // change admin to the username that gets the updates
add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
}
// MAKE CUSTOM POST TYPES SEARCHABLE
function searchAll( $query ) {
if ( $query->is_search ) { $query->set( 'post_type', array( 'site', 'plugin', 'theme', 'person' )); }
return $query;
}
add_filter( 'the_search_query', 'searchAll' );
// ADD CUSTOM POST TYPES TO THE DEFAULT RSS FEED
function custom_feed_request( $vars ) {
if (isset($vars['feed']) && !isset($vars['post_type']))
$vars['post_type'] = array( 'post', 'site', 'plugin', 'theme', 'person' );
return $vars;
}
add_filter( 'request', 'custom_feed_request' );
// ADD CUSTOM POST TYPES TO THE 'RIGHT NOW' DASHBOARD WIDGET
function wph_right_now_content_table_end() {
$args = array(
'public' => true ,
'_builtin' => false
);
$output = 'object';
$operator = 'and';
$post_types = get_post_types( $args , $output , $operator );
foreach( $post_types as $post_type ) {
$num_posts = wp_count_posts( $post_type->name );
$num = number_format_i18n( $num_posts->publish );
$text = _n( $post_type->labels->singular_name, $post_type->labels->name , intval( $num_posts->publish ) );
if ( current_user_can( 'edit_posts' ) ) {
$num = "<a href='edit.php?post_type=$post_type->name'>$num</a>";
$text = "<a href='edit.php?post_type=$post_type->name'>$text</a>";
}
echo '<tr><td class="first num b b-' . $post_type->name . '">' . $num . '</td>';
echo '<td class="text t ' . $post_type->name . '">' . $text . '</td></tr>';
}
$taxonomies = get_taxonomies( $args , $output , $operator );
foreach( $taxonomies as $taxonomy ) {
$num_terms = wp_count_terms( $taxonomy->name );
$num = number_format_i18n( $num_terms );
$text = _n( $taxonomy->labels->singular_name, $taxonomy->labels->name , intval( $num_terms ));
if ( current_user_can( 'manage_categories' ) ) {
$num = "<a href='edit-tags.php?taxonomy=$taxonomy->name'>$num</a>";
$text = "<a href='edit-tags.php?taxonomy=$taxonomy->name'>$text</a>";
}
echo '<tr><td class="first b b-' . $taxonomy->name . '">' . $num . '</td>';
echo '<td class="t ' . $taxonomy->name . '">' . $text . '</td></tr>';
}
}
add_action( 'right_now_content_table_end' , 'wph_right_now_content_table_end' );
// even more smart jquery inclusion :)
add_action( 'init', 'jquery_register' );
// register from google and for footer
function jquery_register() {
if ( !is_admin() ) {
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', ( 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js' ), false, null, true );
wp_enqueue_script( 'jquery' );
}
}
// remove version info from head and feeds
function complete_version_removal() {
return '';
}
add_filter('the_generator', 'complete_version_removal');
// spam & delete links for all versions of wordpress
function delete_comment_link($id) {
if (current_user_can('edit_post')) {
echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&c='.$id.'">del</a> ';
echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&dt=spam&c='.$id.'">spam</a>';
}
}
// delay feed update
function publish_later_on_feed($where) {
global $wpdb;
if (is_feed()) {
// timestamp in WP-format
$now = gmdate('Y-m-d H:i:s');
// value for wait; + device
$wait = '10'; // integer
// http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff
$device = 'MINUTE'; // MINUTE, HOUR, DAY, WEEK, MONTH, YEAR
// add SQL-sytax to default $where
$where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";
}
return $where;
}
add_filter('posts_where', 'publish_later_on_feed');
// REMOVE META BOXES FROM DEFAULT POSTS SCREEN
function remove_default_post_screen_metaboxes() {
remove_meta_box( 'postcustom','post','normal' ); // Custom Fields Metabox
remove_meta_box( 'postexcerpt','post','normal' ); // Excerpt Metabox
remove_meta_box( 'commentstatusdiv','post','normal' ); // Comments Metabox
remove_meta_box( 'trackbacksdiv','post','normal' ); // Talkback Metabox
remove_meta_box( 'slugdiv','post','normal' ); // Slug Metabox
remove_meta_box( 'authordiv','post','normal' ); // Author Metabox
}
add_action('admin_menu','remove_default_post_screen_metaboxes');
// REMOVE META BOXES FROM DEFAULT PAGES SCREEN
function remove_default_page_screen_metaboxes() {
remove_meta_box( 'postcustom','page','normal' ); // Custom Fields Metabox
remove_meta_box( 'postexcerpt','page','normal' ); // Excerpt Metabox
remove_meta_box( 'commentstatusdiv','page','normal' ); // Comments Metabox
remove_meta_box( 'trackbacksdiv','page','normal' ); // Talkback Metabox
remove_meta_box( 'slugdiv','page','normal' ); // Slug Metabox
remove_meta_box( 'authordiv','page','normal' ); // Author Metabox
}
add_action('admin_menu','remove_default_page_screen_metaboxes');
/**
* Set the post revisions unless the constant was set in wp-config.php
*/
if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', 5);
// CUSTOM USER PROFILE FIELDS
function my_custom_userfields( $contactmethods ) {
// ADD CONTACT CUSTOM FIELDS
$contactmethods['contact_phone_office'] = 'Office Phone';
$contactmethods['contact_phone_mobile'] = 'Mobile Phone';
$contactmethods['contact_office_fax'] = 'Office Fax';
// ADD ADDRESS CUSTOM FIELDS
$contactmethods['address_line_1'] = 'Address Line 1';
$contactmethods['address_line_2'] = 'Address Line 2 (optional)';
$contactmethods['address_city'] = 'City';
$contactmethods['address_state'] = 'State';
$contactmethods['address_zipcode'] = 'Zipcode';
return $contactmethods;
}
add_filter('user_contactmethods','my_custom_userfields',10,1);
// the_author_meta('facebook', $current_author->ID)
// CUSTOMIZE ADMIN MENU ORDER
function custom_menu_order($menu_ord) {
if (!$menu_ord) return true;
return array(
'index.php', // this represents the dashboard link
'edit.php?post_type=events', // this is a custom post type menu
'edit.php?post_type=news',
'edit.php?post_type=articles',
'edit.php?post_type=faqs',
'edit.php?post_type=mentors',
'edit.php?post_type=testimonials',
'edit.php?post_type=services',
'edit.php?post_type=page', // this is the default page menu
'edit.php', // this is the default POST admin menu
);
}
add_filter('custom_menu_order', 'custom_menu_order');
add_filter('menu_order', 'custom_menu_order');
// Remove annoying P filter
if(function_exists('capital_P_dangit')) {
foreach ( array( 'the_content', 'the_title' ) as $filter )
remove_filter( $filter, 'capital_P_dangit', 11 );
remove_filter('comment_text', 'capital_P_dangit', 31 );
}
add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');
function my_custom_dashboard_widgets() {
global $wp_meta_boxes;
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
wp_add_dashboard_widget('custom_help_widget', 'Help and Support', 'custom_dashboard_help');
}
// Content for your dashboard
function custom_dashboard_help() {
echo '<p>Lorum ipsum delor sit amet et nunc</p>';
}
/****** Add Thumbnails in Manage Posts/Pages List ******/
if ( !function_exists('AddThumbColumn') && function_exists('add_theme_support') ) {
// for post and page
add_theme_support('post-thumbnails', array( 'post', 'page' ) );
function AddThumbColumn($cols) {
$cols['thumbnail'] = __('Thumbnail');
return $cols;
}
function AddThumbValue($column_name, $post_id) {
$width = (int) 35;
$height = (int) 35;
if ( 'thumbnail' == $column_name ) {
// thumbnail of WP 2.9
$thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
// image from gallery
$attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') );
if ($thumbnail_id)
$thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
elseif ($attachments) {
foreach ( $attachments as $attachment_id => $attachment ) {
$thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
}
}
if ( isset($thumb) && $thumb ) {
echo $thumb;
} else {
echo __('None');
}
}
}
// for posts
add_filter( 'manage_posts_columns', 'AddThumbColumn' );
add_action( 'manage_posts_custom_column', 'AddThumbValue', 10, 2 );
// for pages
add_filter( 'manage_pages_columns', 'AddThumbColumn' );
add_action( 'manage_pages_custom_column', 'AddThumbValue', 10, 2 );
}
function new_excerpt_length($length) {
return 100;
}
add_filter('excerpt_length', 'new_excerpt_length');
// AUTOMATICALLY EXTRACT THE FIRST IMAGE FROM THE POST
function getImage($num) {
global $more;
$more = 1;
$link = get_permalink();
$content = get_the_content();
$count = substr_count($content, '<img');
$start = 0;
for($i=1;$i<=$count;$i++) {
$imgBeg = strpos($content, '<img', $start);
$post = substr($content, $imgBeg);
$imgEnd = strpos($post, '>');
$postOutput = substr($post, 0, $imgEnd+1);
$postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
$image[$i] = $postOutput;
$start=$imgEnd+1;
}
if(stristr($image[$num],'<img')) { echo '<a href="'.$link.'">'.$image[$num]."</a>"; }
$more = 0;
}
//remove pings to self
function no_self_ping( &$links ) {
$home = get_option( 'home' );
foreach ( $links as $l => $link )
if ( 0 === strpos( $link, $home ) )
unset($links[$l]);
}
add_action( 'pre_ping', 'no_self_ping' );
//Enable GZIP output compression
if(extension_loaded("zlib") && (ini_get("output_handler") != "ob_gzhandler"))
add_action('wp', create_function('', '@ob_end_clean();@ini_set("zlib.output_compression", 1);'));
// Sharpen Resized Images
function ajx_sharpen_resized_files( $resized_file ) {
$image = wp_load_image( $resized_file );
if ( !is_resource( $image ) )
return new WP_Error( 'error_loading_image', $image, $file );
$size = @getimagesize( $resized_file );
if ( !$size )
return new WP_Error('invalid_image', __('Could not read image size'), $file);
list($orig_w, $orig_h, $orig_type) = $size;
switch ( $orig_type ) {
case IMAGETYPE_JPEG:
$matrix = array(
array(-1, -1, -1),
array(-1, 16, -1),
array(-1, -1, -1),
);
$divisor = array_sum(array_map('array_sum', $matrix));
$offset = 0;
imageconvolution($image, $matrix, $divisor, $offset);
imagejpeg($image, $resized_file,apply_filters( 'jpeg_quality', 90, 'edit_image' ));
break;
case IMAGETYPE_PNG:
return $resized_file;
case IMAGETYPE_GIF:
return $resized_file;
}
return $resized_file;
}
add_filter('image_make_intermediate_size', 'ajx_sharpen_resized_files',900);
// Display DB Queries, Time Spent and Memory Consumption
function performance( $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 : "<!-- {$stat} -->" ;
}
// remove unnecessary header info
function remove_header_info() {
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'start_post_rel_link');
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'adjacent_posts_rel_link'); // for WordPress < 3.0
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head'); // for WordPress >= 3.0
}
add_action('init', 'remove_header_info');
/**
* Enable WP debugging for usage on a live site
* http://core.trac.wordpress.org/browser/trunk/wp-includes/load.php#L230
* Pass the '?debug=#' parameter at the end of any url on site
*/
if ( isset($_GET['debug']) && $_GET['debug'] == '1' ) {
// enable the reporting of notices during development - E_ALL
define('WP_DEBUG', true);
} elseif ( isset($_GET['debug']) && $_GET['debug'] == '2' ) {
// must be true for WP_DEBUG_DISPLAY to work
define('WP_DEBUG', true);
// force the display of errors
define('WP_DEBUG_DISPLAY', true);
} elseif ( isset($_GET['debug']) && $_GET['debug'] == '3' ) {
// must be true for WP_DEBUG_LOG to work
define('WP_DEBUG', true);
// log errors to debug.log in the wp-content directory
define('WP_DEBUG_LOG', true);
}
// remove extra CSS that 'Recent Comments' widget injects
function remove_recent_comments_style() {
global $wp_widget_factory;
remove_action('wp_head', array(
$wp_widget_factory->widgets['WP_Widget_Recent_Comments'],
'recent_comments_style'
));
}
add_action('widgets_init', 'remove_recent_comments_style');
/* Dynamic Titles **/
// This sets your <title> depending on what page you're on, for better formatting and for SEO
// You need to set the variable $longd to some custom text at the beginning of the function
function dynamictitles() {
$longd = __('Enter your longdescription here.', 'texdomainstring');
if ( is_single() ) {
wp_title('');
echo ' | '.get_bloginfo('name');
} else if ( is_page() || is_paged() ) {
bloginfo('name');
wp_title('|');
} else if ( is_author() ) {
bloginfo('name');
wp_title(' | '.__('Author', 'texdomainstring'));
} else if ( is_category() ) {
bloginfo('name');
wp_title(' | '.__('Archive for', 'texdomainstring'));
} else if ( is_tag() ) {
echo get_bloginfo('name').' | '.__('Tag archive for', 'texdomainstring');
wp_title('');
} else if ( is_archive() ) {
echo get_bloginfo('name').' | '.__('Archive for', 'texdomainstring');
wp_title('');
} else if ( is_search() ) {
echo get_bloginfo('name').' | '.__('Search Results', 'texdomainstring');
} else if ( is_404() ) {
echo get_bloginfo('name').' | '.__('404 Error (Page Not Found)', 'texdomainstring');
} else if ( is_home() ) {
echo get_bloginfo('name').' | '.get_bloginfo('description');
} else {
echo get_bloginfo('name').' | '.($blog_longd);
}
}
// customize admin footer text
function custom_admin_footer() {
echo 'add your custom footer text and html here';
}
add_filter('admin_footer_text', 'custom_admin_footer');
/**
* ADD WP CODEX SEARCH FORM TO DASHBOARD HEADER
*/
function wp_codex_search_form() {
echo '<form target="_blank" method="get" action="http://wordpress.org/search/do-search.php" class="alignright" style="margin: 11px 5px 0;">
<input type="text" onblur="this.value=(this.value==\'\') ? \'Search the Codex\' : this.value;" onfocus="this.value=(this.value==\'Search the Codex\') ? \'\' : this.value;" maxlength="150" value="Search the Codex" name="search" class="text"> <input type="submit" value="Go" class="button" />
</form>';
}
if( current_user_can( 'manage_plugins' )) {
// The number 11 needs to be a 10 for this to work!
add_filter( 'in_admin_header', 'wp_codex_search_form', 11 );
}
add_shortcode('query', 'shortcode_query');
function shortcode_query($atts, $content){
extract(shortcode_atts(array( // a few default values
'posts_per_page' => '10',
'caller_get_posts' => 1,
'post__not_in' => get_option('sticky_posts'),
), $atts));
global $post;
$posts = new WP_Query($atts);
$output = '';
if ($posts->have_posts())
while ($posts->have_posts()):
$posts->the_post();
// these arguments will be available from inside $content
$parameters = array(
'PERMALINK' => get_permalink(),
'TITLE' => get_the_title(),
'CONTENT' => get_the_content(),
'COMMENT_COUNT' => $post->comment_count,
'CATEGORIES' => get_the_category_list(', '),
// add here more...
);
$finds = $replaces = array();
foreach($parameters as $find => $replace):
$finds[] = '{'.$find.'}';
$replaces[] = $replace;
endforeach;
$output .= str_replace($finds, $replaces, $content);
endwhile;
else
return; // no posts found
wp_reset_query();
return html_entity_decode($output);
}
// Set Editor default to html/wysiwg
function my_default_editor() {
$r = 'tinymce'; // html or tinymce
return $r;
}
add_filter( 'wp_default_editor', 'my_default_editor' );
// Enable oEmbed in Text/HTML Widgets
add_filter( 'widget_text', array( $wp_embed, 'run_shortcode' ), 8 );
add_filter( 'widget_text', array( $wp_embed, 'autoembed'), 8 );
// Remove auto-linking
remove_filter('comment_text', 'make_clickable', 9);
// Prevents WordPress from testing ssl capability on domain.com/xmlrpc.php?rsd
remove_filter('atom_service_url','atom_service_url_filter');
//Extending Auto Logout Period
function keep_me_logged_in_for_1_year( $expirein ) {
return 31556926; // 1 year in seconds
}
// Replace WP Admin Logo
function new_admin_logo() {
echo '<style type="text/css">#header-logo { background-image: url('.get_bloginfo('template_directory').'/images/admin_logo.png) !important; }</style>';
}
add_action('admin_head', 'new_admin_logo');
// Custom Favicon WP-Admin
function admin_favicon() {
echo '<link rel="shortcut icon" type="image/x-icon" href="' . get_bloginfo('template_directory') . '/images/favicon.ico" />';
}
// custom Dashboard css
/* Change WordPress dashboard CSS */
function custom_admin_styles() {
echo '<style type="text/css">#wphead{background:#069}</style>';
}
add_action('admin_head', 'custom_admin_styles');
// Add auto-update/plugin-installer on you localhost
define ('FS_METHOD', 'direct');
// Wordpress Security Fixes
//REMOVE VERSION STRING FROM HEADER
remove_action('wp_head', 'wp_generator');
//HIDE LOGIN ERROR MESSAGES (Wrong Password, No Such User etc.)
add_filter('login_errors',create_function('$a', "return null;"));
// Remove admin name in comments class
// Source: http://www.wprecipes.com/wordpress-hack-remove-admin-name-in-comments-class
function remove_comment_author_class( $classes ) {
foreach( $classes as $key => $class ) {
if(strstr($class, "comment-author-")) {
unset( $classes[$key] );
}
}
return $classes;
}
add_filter( 'comment_class' , 'remove_comment_author_class' );
// List all constants for information and debugging
if ( is_user_logged_in() ) {
print('<pre>');
print_r( @get_defined_constants() );
print('</pre>');
}
// Add Next Page
add_filter('mce_buttons','wysiwyg_editor');
function wysiwyg_editor($mce_buttons) {
$pos = array_search('wp_more',$mce_buttons,true);
if ($pos !== false) {
$tmp_buttons = array_slice($mce_buttons, 0, $pos+1);
$tmp_buttons[] = 'wp_page';
$mce_buttons = array_merge($tmp_buttons, array_slice($mce_buttons, $pos+1));
}
return $mce_buttons;
}
// Change defualt author slug
// Change URL Slug from Author to Sellers
function new_author_base() {
global $wp_rewrite;
$author_slug = 'sellers';
$wp_rewrite->author_base = $author_slug;
}
add_action('init', 'new_author_base');
// Load Scripts conditionally
function has_my_shortcode($posts) {
if ( empty($posts) )
return $posts;
$found = false;
foreach ($posts as $post) {
if ( stripos($post->post_content, '[my_shortcode') )
$found = true;
break;
}
if ($found){
$urljs = get_bloginfo( 'template_directory' ).IMP_JS;
wp_register_script('my_script', $urljs.'myscript.js' );
wp_print_scripts('my_script');
}
return $posts;
}
add_action('the_posts', 'has_my_shortcode');
add_action( 'admin_head', 'admin_favicon' );
add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year' );
class WP_Widget_Recent_Comments extends WP_Widget {
function WP_Widget_Recent_Comments() {
$widget_ops = array('classname' => 'widget_recent_comments', 'description' => __( 'The most recent comments' ) );
$this->WP_Widget('recent-comments', __('Recent Comments'), $widget_ops);
$this->alt_option_name = 'widget_recent_comments';
if ( is_active_widget(false, false, $this->id_base) )
add_action( 'wp_head', array(&$this, 'recent_comments_style') );
add_action( 'comment_post', array(&$this, 'flush_widget_cache') );
add_action( 'transition_comment_status', array(&$this, 'flush_widget_cache') );
}
// Resize Large Image on Upload
/**resize on upload to the largest size in media setting */
function replace_uploaded_image($image_data) {
// if there is no large image : return
if (!isset($image_data['sizes']['large'])) return $image_data;
// path to the uploaded image and the large image
$upload_dir = wp_upload_dir();
$uploaded_image_location = $upload_dir['basedir'] . '/' .$image_data['file'];
$large_image_location = $upload_dir['path'] . '/'.$image_data['sizes']['large']['file'];
// delete the uploaded image
unlink($uploaded_image_location);
// rename the large image
rename($large_image_location,$uploaded_image_location);
// update image metadata and return them
$image_data['width'] = $image_data['sizes']['large']['width'];
$image_data['height'] = $image_data['sizes']['large']['height'];
unset($image_data['sizes']['large']);
return $image_data;
}
add_filter('wp_generate_attachment_metadata','replace_uploaded_image');
// Replace defualt gravatr
function custom_gravatar($avatar_defaults) {
$logo = get_bloginfo('template_directory') . '/images/icons/gravatar_logo.jpg'; //Change to whatever path you like.
$avatar_defaults[$logo] = get_bloginfo('name');
return $avatar_defaults;
}//END FUNCTION
add_filter( 'avatar_defaults', 'custom_gravatar' );
<?php
if ( !defined('SAVEQUERIES') && isset($_GET['debug']) && $_GET['debug'] == 'sql' )
define('SAVEQUERIES', true);
if ( !function_exists('dump') ) :
/**
* dump()
*
* @param mixed $in
* @return mixed $in
**/
function dump($in = null) {
echo '<pre style="margin-left: 0px; margin-right: 0px; padding: 10px; border: solid 1px black; background-color: ghostwhite; color: black; text-align: left;">';
foreach ( func_get_args() as $var ) {
echo "\n";
if ( is_string($var) ) {
echo "$var\n";
} else {
var_dump($var);
}
}
echo '</pre>' . "\n";
return $in;
} # dump()
endif;
/**
* add_stop()
*
* @param mixed $in
* @param string $where
* @return mixed $in
**/
function add_stop($in = null, $where = null) {
global $sem_stops;
global $wp_object_cache;
$queries = get_num_queries();
$milliseconds = timer_stop() * 1000;
$out = "$queries queries - {$milliseconds}ms";
if ( function_exists('memory_get_usage') ) {
$memory = number_format(memory_get_usage() / ( 1024 * 1024 ), 1);
$out .= " - {$memory}MB";
}
$out .= " - $wp_object_cache->cache_hits cache hits / " . ( $wp_object_cache->cache_hits + $wp_object_cache->cache_misses );
if ( $where ) {
$sem_stops[$where] = $out;
} else {
dump($out);
}
return $in;
} # add_stop()
/**
* dump_stops()
*
* @param mixed $in
* @return mixed $in
**/
function dump_stops($in = null) {
if ( $_POST )
return $in;
global $sem_stops;
global $wp_object_cache;
$stops = '';
foreach ( $sem_stops as $where => $stop )
$stops .= "$where: $stop\n";
dump("\n" . trim($stops) . "\n");
if ( defined('SAVEQUERIES') && $_GET['debug'] == 'sql' ) {
global $wpdb;
foreach ( $wpdb->queries as $key => $data ) {
$query = rtrim($data[0]);
$duration = number_format($data[1] * 1000, 1) . 'ms';
$loc = trim($data[2]);
$loc = preg_replace("/(require|include)(_once)?,\s*/ix", '', $loc);
$loc = "\n" . preg_replace("/,\s*/", ",\n", $loc) . "\n";
dump($query, $duration, $loc);
}
}
if ( $_GET['debug'] == 'cache' )
dump($wp_object_cache->cache);
if ( $_GET['debug'] == 'cron' ) {
$crons = get_option('cron');
foreach ( $crons as $time => $_crons ) {
if ( !is_array($_crons) )
continue;
foreach ( $_crons as $event => $_cron ) {
foreach ( $_cron as $details ) {
$date = date('Y-m-d H:m:i', $time);
$schedule = isset($details['schedule']) ? "({$details['schedule']})" : '';
if ( $details['args'] )
dump("$date: $event $schedule", $details['args']);
else
dump("$date: $event $schedule");
}
}
}
}
return $in;
} # dump_stops()
add_action('init', create_function('$in', '
return add_stop($in, "Load");
'), 10000000);
add_action('template_redirect', create_function('$in', '
return add_stop($in, "Query");
'), -10000000);
add_action('wp_footer', create_function('$in', '
return add_stop($in, "Display");
'), 10000000);
add_action('admin_footer', create_function('$in', '
return add_stop($in, "Display");
'), 10000000);
/**
* init_dump()
*
* @return void
**/
function init_dump() {
global $hook_suffix;
if ( !is_admin() || empty($hook_suffix) ) {
add_action('wp_footer', 'dump_stops', 10000000);
add_action('admin_footer', 'dump_stops', 10000000);
} else {
add_action('wp_footer', 'dump_stops', 10000000);
add_action("admin_footer-$hook_suffix", 'dump_stops', 10000000);
}
} # init_dump()
add_action('wp_print_scripts', 'init_dump');
/**
* dump_phpinfo()
*
* @return void
**/
function dump_phpinfo() {
if ( isset($_GET['debug']) && $_GET['debug'] == 'phpinfo' ) {
phpinfo();
die;
}
} # dump_phpinfo()
add_action('init', 'dump_phpinfo');
/**
* dump_http()
*
* @param array $args
* @param string $url
* @return array $args
**/
function dump_http($args, $url) {
dump(preg_replace("|/[0-9a-f]{32}/?$|", '', $url));
return $args;
} # dump_http()
/**
* dump_trace()
*
* @return void
**/
function dump_trace() {
$backtrace = debug_backtrace();
foreach ( $backtrace as $trace )
dump(
'File/Line: ' . $trace['file'] . ', ' . $trace['line'],
'Function / Class: ' . $trace['function'] . ', ' . $trace['class']
);
} # dump_trace()
if ( $_GET['debug'] == 'http' )
add_filter('http_request_args', 'dump_http', 0, 2);
?>
@vbaimas
Copy link

vbaimas commented Aug 1, 2018

Useful code. I noticed that sometimes the following code,

add_filter('login_errors',create_function('$a', "return null;"));

returns a Function create_function() is deprecated

So, in your case I suggest to replace the part of code above with the following

<?php
function no_wordpress_errors(){
    echo '<style type="text/css">
    .login #login_error{
        display:none;
    </style>';
  }
  add_filter( 'login_errors', 'no_wordpress_errors' );
  ?>

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