.. Your Daily Design Dosis

10 more Useful WordPress Hacks/Code Snippets

| 2 Comments

One of the main reasons I like to work with WordPress is because it’s an open source Content Management System (CMS) that is easy to customize. With a few lines of code you can get some cool customization and new features with all those filters, actions and hooks.

WordPress comes with standard functions but there are many plugins and code snippets/hacks to give your blog a different look and/or function(s). Today I have collected some new code snippets that focus on extending the functionality of WordPress even further.

Note: These hacks worked at the time they were published, but as new versions of WordPress are released, some may no longer work. Please backup your theme before attempting any hacks so you can restore things if something goes wrong.

In case you liked these wordpress code snippets, make sure to check some more articles loaded with WordPress code snippets!

WordPress function to check if the current post is a custom post type

Introduced in version 3.0, custom post types allows you to hold and display many different types of content. Today’s recipe is super useful for those who frequently work with custom post types: a function to check if the current post is a custom post type.

Simply paste this code into your functions.php file:

function is_custom_post_type() {
	global $wp_query;

	$post_types = get_post_types(array('public'   => true,'_builtin' => false),'names','and');

	foreach ($post_types  as $post_type ) {
		if (get_post_type($post_type->ID) == get_post_type($wp_query->post->ID)) {
			return true;
		} else {
			return false;
		}
	}
}

Once done, you can use the function as shown below. Please note that the function can be used outside the loop:

if (is_custom_post_type()) { //Current post is a custom post type }

Source

Automatically remove short words from the URL

By default, WordPress generate the slug (url) from your post title. It do not remove any words, even shorter ones which don’t add any value to your seo. Here’s a super useful tip to automatically remove short words from your urls.

Paste the code below into your functions.php file. Once you saved the file, WordPress will automatically remove short (less than 3 characters) words from the generated permalink

add_filter('sanitize_title', 'remove_short_words');
function remove_short_words($slug) {
    if (!is_admin()) return $slug;
    $slug = explode('-', $slug);
    foreach ($slug as $k => $word) {
        if (strlen($word) < 3) {
            unset($slug[$k]);
        }
    }
    return implode('-', $slug);
}

Source

Adding a RSS Subscription Link on Category Pages

Lets start with adding a simple RSS subscription link on category pages. First thing you need to do is go inside your theme’s folder and find the file category.php. If you don’t see category.php, but it has an archive.php file, then create a new file called category.php and paste all the code from archive.php in it.

<?php
$category = get_category( get_query_var('cat') );

if ( ! empty( $category ) )

echo '<div><p><a href="' . get_category_feed_link( $category->cat_ID ) . '" title="Subscribe to this category" rel="nofollow">Subscribe</a></p></div>';
?>

Source

Check whether a plugin is active

When developing a WordPress theme or plugin, it can be really useful to be able to know if a specific plugin is activated. Here is a simple way to check wheher a plugin is activated or not.  Just paste the code below in your theme file, wherever you’d like to check out if a plugin is activated or not. Update the code with the plugin directory and name on line 4.

<?php 
   include_once( ABSPATH . 'wp-admin/includes/plugin.php' );

   if(is_plugin_active('plugin-directory/plugin-file.php')) {
      //plugin is activated
   }
?>

Source

Force specific pages to be SSL secure

If SSL is enabled on your webserver, you should definitely use it to protect your blog. Activating SSL on your specific pages on a WordPress blog is definitely easy. Just add the following snippet to the functions.php file of your WordPress theme and specify the post or page ID desired.

function wps_force_ssl( $force_ssl, $post_id = 0, $url = '' ) {
    if ( $post_id == 25 ) {
        return true
    }
    return $force_ssl;
}
add_filter('force_ssl' , 'wps_force_ssl', 10, 3);

Sourc

WordPress shortcode to embed Google trends graphs

Google trends is a service which allow you to track the popularity of specific keywords. Here’s the code to create a WordPress shortcode that will embed a Google trends graph of any comma separated query on your blog. The first step is to create the shortcode. To do so, open your functions.php file and paste the code below in it:

function wps_trend($atts){
        extract( shortcode_atts( array(
                'w' => '500',           // width
                'h' => '330',           // height
                'q' => '',              // query
                'geo' => 'US',          // geolocation
        ), $atts ) );
        //format input
        $h=(int)$h;
        $w=(int)$w;
        $q=esc_attr($q);
        $geo=esc_attr($geo);
         ob_start();
?>
<script type="text/javascript" src="http://www.google.com/trends/embed.js?hl=en-US&q=<?php echo $q;?>&geo=<?php echo $geo;?>&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=<?php echo $w;?>&h=<?php echo $h;?>"></script>
<?php
return ob_get_clean();
}
add_shortcode("trends","wps_trend");

Once you saved your functions.php file, you can now use the shortocode in your posts and pages. Here is an example of usage:

[trends h="450" w="500" q="wpsnipp,wordpress,+wordpress+theme,+wordpress+plugin,+wordpress+snippets" geo="US"]

Source

wordpress-code-snippets

How to setup different admin and theme languages on your WordPress blog

Here is a quick tip to use different languages on your WordPress blog or website. Simply set the desired locale (on line 6) then add the code to your functions.php file.

<?php
     // setup one language for admin and the other for theme
     // must be called before load_theme_textdomain()

     function set_my_locale($locale) {
          $locale = ( is_admin() ) ? "en_US" : "it_IT";
          setlocale(LC_ALL, $local );
          return $locale;
     }
     add_filter( 'locale', 'set_my_locale' );
?>

Source

How to Add Numeric Pagination in Your WordPress Theme

This hack will show you how to add numeric pagination in your WordPress theme. The goal is to replace the default Older and Newer pagination links at the bottom of archive pages with easy to navigate page numbers.

First we will show you how to manually add numeric pagination in your WordPress themes. This will benefit our advanced users, and users who are learning theme development, or want to do this without relying on a third party plugin. Lets get started by adding the following code in your theme’s functions.php file.

function wpbeginner_numeric_posts_nav() {

	if( is_singular() )
		return;

	global $wp_query;

	/** Stop execution if there's only 1 page */
	if( $wp_query->max_num_pages <= 1 )
		return;

	$paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
	$max   = intval( $wp_query->max_num_pages );

	/**	Add current page to the array */
	if ( $paged >= 1 )
		$links[] = $paged;

	/**	Add the pages around the current page to the array */
	if ( $paged >= 3 ) {
		$links[] = $paged - 1;
		$links[] = $paged - 2;
	}

	if ( ( $paged + 2 ) <= $max ) {
		$links[] = $paged + 2;
		$links[] = $paged + 1;
	}

	echo '<div><ul>' . "\n";

	/**	Previous Post Link */
	if ( get_previous_posts_link() )
		printf( '<li>%s</li>' . "\n", get_previous_posts_link() );

	/**	Link to first page, plus ellipses if necessary */
	if ( ! in_array( 1, $links ) ) {
		$class = 1 == $paged ? '' : '';

		printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );

		if ( ! in_array( 2, $links ) )
			echo '<li>…</li>';
	}

	/**	Link to current page, plus 2 pages in either direction if necessary */
	sort( $links );
	foreach ( (array) $links as $link ) {
		$class = $paged == $link ? '' : '';
		printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
	}

	/**	Link to last page, plus ellipses if necessary */
	if ( ! in_array( $max, $links ) ) {
		if ( ! in_array( $max - 1, $links ) )
			echo '<li>…</li>' . "\n";

		$class = $paged == $max ? '' : '';
		printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
	}

	/**	Next Post Link */
	if ( get_next_posts_link() )
		printf( '<li>%s</li>' . "\n", get_next_posts_link() );

	echo '</ul></div>' . "\n";

}

To add this in your templates, you will have to add the following template tag in your theme’s index.php, archive.php, category.php, and any other archive page template.

<?php wpbeginner_numeric_posts_nav(); ?>

Now that we have got our list of numbered pages, we need to style this list.  Here’s an example to add in your theme’s style.css file:

.navigation li a,
.navigation li a:hover,
.navigation li.active a,
.navigation li.disabled {
	color: #fff;
	text-decoration:none;
}

.navigation li {
	display: inline;
}

.navigation li a,
.navigation li a:hover,
.navigation li.active a,
.navigation li.disabled {
	background-color: #6FB7E9;
	border-radius: 3px;
	cursor: pointer;
	padding: 12px;
	padding: 0.75rem;
}

.navigation li a:hover,
.navigation li.active a {
	background-color: #3C8DC5;
}

Source

How to add SVG upload support to your WordPress blog

By default, WordPress uploader do not support the SVG format. As this file format is becoming quite popular theses days, here is a simple recipe to add SVG upload to your WordPress install.

Simply add the code below to functions.php in your WordPress theme. SVG upload will be supported once the file is saved.

add_filter('upload_mimes', 'my_upload_mimes');

function my_upload_mimes($mimes = array()) {
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
}

Source

Limit posts per page on search

By default, WordPress outputs 10 posts per page on the search results page. If you need to change this number, just paste the following code in your functions.php file. Replace the number on line 3 by the desired number of posts to be displayed.

function limit_posts_per_search_page() {
	if ( is_search() )
		set_query_var('posts_per_archive_page', 20); 
}

add_filter('pre_get_posts', 'limit_posts_per_search_page');

Source

 

Author: Jan Rajtoral

Jan Rajtoral AKA Gonzo the Great is the Founder of and Designer at gonzodesign, providing design services across the full spectrum of Brand Identity, Graphic Design, Print and Advertising Design & Website Design.

2 comments

on this article: “10 more Useful WordPress Hacks/Code Snippets”
  1. I was really having trouble adding Numeric Pagination in my wordpress blog but thanks to you this problem has now got resolved. Thanks a ton.

    • Hi Crazely,

      Glad to hear you found the right hack, that’s why I publish these articles, because appr. 80% of the posts with code snippets actually helped me fix some kinda WordPress related issue as well ;-P

      Once in a while I write posts with WordPress hacks, .. stay tuned ;-P Thanks for the comment and glad I could help, Cheers & Ciao!

top