David Ogilo

menu search

Adding stickies to custom post types in WordPress

For some odd reason, there isn’t an option to add stickies to custom post types in WordPress. In this article, I’ll show you how easy is it to add this with some PHP/JS code.

THE SCRIPT

The code below adds the option to make a custom post a sticky or not. If the sticky checkbox isn’t in the DOM, then it adds it in.

( function( $ ){
	var isSticky = false;
 
	$.each( document.scripts, function(){
		var src = $( this ).attr( 'src' );
 
		if ( src && src.match( /sticky\.js/i ) && src.match( /sticky=1/i ) ){
			isSticky = true;
			return;
		}
	});
 
	if ( !$( '#sticky-span' ).length ){
		var checked = ( isSticky )? 'checked="checked"' : '';
		var html = '<span id="sticky-span"><input id="sticky" name="sticky" type="checkbox" value="sticky" tabindex="4" ' + checked + ' /> ' + '<label class="selectit" for="sticky">Stick this post to the front page</label> ';
 
		$( 'label[for=visibility-radio-public] + br' ).after( html );
	}
})( jQuery );

It’s best to save the JavaScript file as sticky.js as the script above and code below relies on it.

LOAD THE SCRIPT

The first thing is to either create a plugin or add the following PHP code to your existing plugin and replace the path to sticky.js

add_action( 'admin_print_styles-post-new.php', 'adminScripts' );
add_action( 'admin_print_styles-post.php', 'adminScripts' );
 
function adminScripts()
{
	global $post;
 
	$sticky = false;
	$jsFile = 'path/to/sticky.js';
 
	if ( ( !empty( $post ) && $post->post_type == 'post' ) || ( !empty( $_GET['post_type'] ) && $_GET['post_type'] == 'post' ) ) return;
 
	if ( !empty( $post ) && is_sticky( $post->ID ) )
		$sticky = true;
 
	if ( current_user_can( 'edit_others_posts' ) )
		wp_enqueue_script( 'sticky', $jsFile . '?sticky=' . (int)$sticky, array( 'jquery'), '1.0', true );
}

That’s it! All we’re doing here is telling WordPress to check if the post is a sticky and load the sticky JavaScript file in the post admin interface.

CAUTION

Adding custom post types as stickies will enable them to be added to the top of a get_posts() result (returning non-custom post types) if ignore_sticky_posts is set to false. To get around this, you’ll need to filter by post type

Tags: , ,

Old school browser detected!

Your browser is out of date, which means you can't use any of the site's required features. You can either upgrade your browser or switch to either Mozilla Firefox or Google Chrome