Skip to content

Instantly share code, notes, and snippets.

@markkap
Last active June 8, 2016 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markkap/9571cb838024571ff2e4bbe00b46d333 to your computer and use it in GitHub Desktop.
Save markkap/9571cb838024571ff2e4bbe00b46d333 to your computer and use it in GitHub Desktop.
How to use the cpw_excerpt filter to add additional excerpt field to be used by the category posts widget
<?php
/*
Plugin Name: Unique excerpt for Category Posts Widget
Plugin URI: http://mkrdip.me/category-posts-widget
Description: Adds a meta box for all posts in which the user can edit the excerpt that will be displayed at the category posts widget
*/
/**
* Register meta box(es).
*/
function cpw_excerp_register_meta_boxes() {
add_meta_box( 'cpw_excerpt_meta_box', 'Excerpt for Category Posts Widget', 'cpw_excerpt_metabox', 'post' );
}
add_action( 'add_meta_boxes', 'cpw_excerp_register_meta_boxes' );
/**
* Meta box display callback.
*
* @param WP_Post $post Current post object.
*/
function cpw_excerpt_metabox( $post ) {
$content = get_post_meta($post->ID, 'cpw_excerpt',true);
// seems like wpautop needs to be set to make the editor wrap text in a <p>
// element as the core excerpt does
wp_editor($content,'cpw_excerpt',array( 'media_buttons' => false, 'wpautop' => false ));
}
/**
* Save meta box content.
*
* @param int $post_id Post ID
*/
function cpw_excerpt_save_meta_box( $post_id ) {
if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ))
return;
if (isset($_POST['cpw_excerpt']))
update_post_meta($post_id,'cpw_excerpt',$_POST['cpw_excerpt']);
}
add_action( 'save_post', 'cpw_excerpt_save_meta_box' );
/**
* Do the actual excerpt filtering. If we have an explicit excerpt set, use it, otherwise use whatever is already calculated
*
* @param string $excerpt The current excerpt
* @param WP_Widget $widget the widget object from which it is possible to get the information of its type an dID number
* @param int $length the configured request length for an excerpt. A zero is passed if no value is actually configured
*
* @return The excerpt configured for the current post if exists, otherwise the current except
*/
function cpw_excerpt_filter($excerpt,$widget,$length) {
$t = get_post_meta(get_the_ID(),'cpw_excerpt',true);
if (!empty($t))
$excerpt = $t;
return $excerpt;
}
add_filter('cpw_excerpt','cpw_excerpt_filter',10,3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment