Last active
July 13, 2020 17:52
-
-
Save CodeProKid/fce20ce672232fe73035 to your computer and use it in GitHub Desktop.
Add sticky functionality to CPT's
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'admin_init', 'cpt_sticky_add_meta_box' ); | |
add_filter( 'the_posts', 'cpt_sticky_at_top' ); | |
add_filter( 'post_limits', 'fix_post_count', 10, 2 ); | |
function cpt_sticky_meta() { ?> | |
<input id="super-sticky" name="sticky" type="checkbox" value="sticky" <?php checked( is_sticky() ); ?> /> <label for="super-sticky" class="selectit"><?php _e( 'Stick this to the top' ) ?></label><?php | |
} | |
function cpt_sticky_add_meta_box() { | |
if( ! current_user_can( 'edit_others_posts' ) ) | |
return; | |
$sticky_post_types = array( 'news', 'press_release'); //Replace this with your cpt names | |
foreach( $sticky_post_types as $post_type ) | |
add_meta_box( 'cpt_sticky_meta', __( 'Sticky' ), 'cpt_sticky_meta', $post_type, 'side', 'default' ); | |
} | |
function cpt_sticky_at_top( $posts ) { | |
// apply it on the archives only | |
if ( is_main_query() && !is_single() ) { | |
global $wp_query; | |
$sticky_posts = get_option( 'sticky_posts' ); | |
$num_posts = count( $posts ); | |
$sticky_offset = 0; | |
// Find the sticky posts | |
for ($i = 0; $i < $num_posts; $i++) { | |
// Put sticky posts at the top of the posts array | |
if ( in_array( $posts[$i]->ID, $sticky_posts ) ) { | |
$sticky_post = $posts[$i]; | |
// Remove sticky from current position | |
array_splice( $posts, $i, 1 ); | |
// Move to front, after other stickies | |
array_splice( $posts, $sticky_offset, 0, array($sticky_post) ); | |
$sticky_offset++; | |
// Remove post from sticky posts array | |
$offset = array_search($sticky_post->ID, $sticky_posts); | |
unset( $sticky_posts[$offset] ); | |
} | |
} | |
} | |
return $posts; | |
} | |
function fix_post_count( $limit, $query ) { | |
if ( !is_admin() && !is_single() ) { | |
$sticky_posts = get_option( 'sticky_posts' ); | |
$i = 0; | |
foreach( $sticky_posts as $post ) { | |
$postObj = get_post($post); | |
if ( isset( $query->query_vars['post_type'] ) ) { | |
if ( $query->query_vars['post_type'] == $postObj->post_type ) { | |
$i++; | |
} | |
} | |
} | |
$oldLimit = $query->query_vars['posts_per_page']; | |
$newLimit = ($oldLimit + $i); | |
return 'LIMIT 0, ' . $newLimit; | |
} | |
return $limit; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment