Useful WordPress functions

Since I spend a lot of time searching for useful functions I’ll try to store them here with some comments and explanations so in the future I have them all in one place… This are not mandatory functions, and I keep them all in child theme folder in a file functions.php … these way I don’t mess with original theme functions.php so I can still update my original theme.

Cleaning up the mess

So first of all I’ll start with functions that will clean up a mess a little bit and remove some unused things from header. Since functions are inside child theme I’ll add “if” in case that function already exists in original themes functions.php.

<?php
// Remove meta generator (WP version) from site and feed
 
if ( ! function_exists( 'mywp_remove_version' ) ) {
 
function mywp_remove_version() {
	return '';
}
add_filter('the_generator', 'mywp_remove_version');
}
// Clean header from unneeded links
if ( ! function_exists( 'mywp_head_cleanup' ) ) {
 
function mywp_head_cleanup() { 
 
	/* Remove Post and Comment Feeds */
	remove_action('wp_head', 'feed_links', 2); 
 
	/* Remove Category feeds */
	remove_action('wp_head', 'feed_links_extra', 3); 
 
	/* Disable link to Really Simple Discovery service */
	remove_action('wp_head', 'rsd_link'); 
 
	/* Remove link to the Windows Live Writer manifest file.*/
	remove_action('wp_head', 'wlwmanifest_link');
 
	/* Remove Index link */
	remove_action( 'wp_head', 'index_rel_link' );
 
	/* Remove Prev link */
	remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 );
 
	/* Remove Start link */
	remove_action( 'wp_head', 'start_post_rel_link', 10, 0 );
 
	/* Remove Relation links for the posts adjacent to the current post. */
	remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
 
	/* Remove Shortlink  */
	remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
 
global $wp_widget_factory;
	remove_action('wp_head', array($wp_widget_factory-&gt;widgets['WP_Widget_Recent_Comments'], 'recent_comments_style'));
add_filter('use_default_gallery_style', '__return_null');
}
add_action('init', 'mywp_head_cleanup');
}
// Remove style and script versions from source code URL's
if ( ! function_exists( 'mywp_remove_version_script_style' ) ) {
 
function mywp_remove_version_script_style( $target_url ) {
 
	/* check if "ver=" argument exists in the url or not */	
	if(strpos( $target_url, 'ver=' )) {
	$target_url = remove_query_arg( 'ver', $target_url );
	}
 
return $target_url;
}
 
/* Priority set to 20000. Higher numbers correspond with later execution. Hook into the style loader and remove version info.*/
add_filter('style_loader_src', 'mywp_remove_version_script_style', 20000);
 
/* Hook into the script loader and remove the version info. */
add_filter('script_loader_src', 'mywp_remove_version_script_style', 20000);
}

In some cases you don’t want WordPress read more link to open page at the middle of the content (‘Continue reading’ acts like an anchor), to disable this option enter:

// Remove default option for more link that jumps at the midle of the page
if ( ! function_exists( 'mysticky_remove_more_jump_link' ) ) {
 
function mysticky_remove_more_jump_link($link) 
	{ 
	$offset = strpos($link, '#more-');
 
		if ($offset) {
			$end = strpos($link, '"',$offset);
		}
		if ($end) {
			$link = substr_replace($link, '', $offset, $end-$offset);
		}
		return $link;
	}
	add_filter('the_content_more_link', 'mysticky_remove_more_jump_link');
}

Add Extra Functionality

So now we can start with changing and adding some functionality as a custom excerpt text lenght and read more text link. Add extra widget area, enable shortcodes in widgets etc…

// Custom excerpt lenght (20words)
if ( ! function_exists( 'mywp_custom_excerpt_length' ) ) {
 
function mywp_custom_excerpt_length( $length ) {
	return 20;
}
add_filter( 'excerpt_length', 'mywp_custom_excerpt_length', 999 );
 
}
 
// Custom read more text
if ( ! function_exists( 'mywp_new_excerpt_more' ) ) {
 
function mywp_new_excerpt_more( $more ) {
	return ' <a class="read-more" href="'. get_permalink( get_the_ID() ) . '">' . __('Read More', 'your-text-domain') . '</a>';
}
add_filter( 'excerpt_more', 'mywp_new_excerpt_more' );
 
}

Function which will let us have multiple excerpt size lenghts for different content

if ( ! function_exists( 'excerpt' ) ) {
function excerpt($limit) {
      $excerpt = explode(' ', get_the_excerpt(), $limit);
      if (count($excerpt)>=$limit) {
        array_pop($excerpt);
        $excerpt = implode(" ",$excerpt).'...';
      } else {
        $excerpt = implode(" ",$excerpt);
      } 
      $excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
      return $excerpt;
    }
}

Than in your page template instead of “the_excerpt()”; use “echo excerpt(20);” or any number of words desired…

Same thing for content:

if ( ! function_exists( 'content' ) ) {
function content($limit) {
      $content = explode(' ', get_the_content(), $limit);
      if (count($content)>=$limit) {
        array_pop($content);
        $content = implode(" ",$content).'...';
      } else {
        $content = implode(" ",$content);
      } 
      $content = preg_replace('/\[.+\]/','', $content);
      $content = apply_filters('the_content', $content); 
      $content = str_replace(']]>', ']]&gt;', $content);
      return $content;
    }
}

To show it: “echo content(25);”

Shortcodes are quite powerful and favorite solution for lots of wp blogs. By default WordPress disables shortcodes inside widgets and category description fields… To enable it add filters:

// widgets activate shortcodes (do_shortcode)
add_filter( 'widget_text', 'shortcode_unautop' );
add_filter( 'widget_text', 'do_shortcode' );
 
// category description do_shortcode
remove_filter('pre_term_description', 'wp_filter_kses');
add_filter( 'category_description', 'do_shortcode' );

WordPress category description field is by default just a text box. Sometimes it’s enough but sometimes you would like some more text edit capabilities. Easiest way to do it is to add default TinyMCE editor to category description field with this functions:

/* Category Description tinyMce editor */
add_filter('edit_category_form_fields', 'edit_cat_description');
 
if ( ! function_exists( 'edit_cat_description' ) ) {
 
function edit_cat_description($category) {
define('description1', '');
 
    $tag_extra_fields = get_option(description1);?>
	<table class="form-table">
	<tr class="form-field">
	<th scope="row" valign="top"><label for="description"><?php _ex('Description', 'Taxonomy Description'); ?></label></th>
	<td>
	<?php 	$settings = array('wpautop' => true, 'media_buttons' => true, 'quicktags' => true, 'textarea_rows' => '15', 'textarea_name' => 'description' );
	wp_editor(html_entity_decode($category->description , ENT_QUOTES, 'UTF-8'), 'description1', $settings); ?>
	<br />
	<span class="description"><?php _e('The description is not prominent by default, however some themes may show it.'); ?></span>
	</td>
	</tr>
	</table><?php  }
 
add_action( 'admin_print_styles', 'category_tinymce_css' );
}
 
 
if ( ! function_exists( 'category_tinymce_css' ) ) {
 
function category_tinymce_css() { ?>	<style type="text/css">
	.quicktags-toolbar input{float:left !important; width:auto !important;}
	</style><?php }
 
add_action('admin_head', 'taxonomy_tinycme_hide_description');
}
 
 
if ( ! function_exists( 'taxonomy_tinycme_hide_description' ) ) {
 
function taxonomy_tinycme_hide_description() {
global $pagenow; //echo $pagenow;exit;
//only hide on detail not yet on overview page.
	if( ($pagenow == 'edit-tags.php?action=edit' || isset($_GET['action']) )) :		
 
	?>
	<script type="text/javascript">
	jQuery(function($) {
		$('#description, textarea#tag-description').closest('.form-field').hide();
	});
	</script><?php endif;
}
}

Custom widget position is quite usefull in WordPress, to add extra widgets functionality to any theme add this function (change ‘twentythirteen’ to ‘your_text_domain’)

// Add Header and two Extra Widget Areas
if ( ! function_exists( 'custom_sidebar' ) ) {
 
// Register Sidebar
function custom_sidebar() {
 
	$args = array(
		'id'            => 'sidebarheader',
		'name'          => __( 'Header Widget', 'twentythirteen' ),
		'description'   => __( 'Header widget area for my child theme.', 'twentythirteen' ),
		'class'         => 'sidebarheader',
		'before_title'  => '<h2 class="widgettitle">',
		'after_title'   => '</h2>',
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
	);
	register_sidebar( $args );
 
 
	$args = array(
		'id'            => 'sidebarextra',
		'name'          => __( 'Extra Widget', 'twentythirteen' ),
		'description'   => __( 'Extra widget area for my child theme.', 'twentythirteen' ),
		'class'         => 'sidebarextra',
		'before_title'  => '<h2 class="widgettitle">',
		'after_title'   => '</h2>',
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
	);
	register_sidebar( $args );
 
	 $args = array(
		'id'            => 'sidebarextra2',
		'name'          => __( 'Extra Widget 2', 'twentythirteen' ),
		'description'   => __( 'Extra widget area for my child theme.', 'twentythirteen' ),
		'class'         => 'sidebarextra2',
		'before_title'  => '<h2 class="widgettitle">',
		'after_title'   => '</h2>',
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
	);
	register_sidebar( $args );
 
}
 
// Hook into the 'widgets_init' action
add_action( 'widgets_init', 'custom_sidebar' );
 
}

Now wherever you want to show this widgets (header.php, page.php…) add code like this (one at a time)

<?php 
  if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Header Widget') ) : ?>
<?php endif; ?>
 
<?php 
  if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Extra Widget') ) : ?>
<?php endif; ?>
 
<?php 
  if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Extra Widget 2') ) : ?>
<?php endif; ?>

That’s all for now, I’ll try to keep this updated and add some new functions in the future…