Skip to content

Instantly share code, notes, and snippets.

@sscovil
Created June 14, 2013 03:55
Show Gist options
  • Save sscovil/5779351 to your computer and use it in GitHub Desktop.
Save sscovil/5779351 to your computer and use it in GitHub Desktop.
Add shortcode [keywords] to a post, to list all keywords found in the content of a post. Keywords can be added to the post in which the shortcode is added by creating custom field(s) named 'keyword'. Keywords can be defined using the shortcode attribute 'words' (ex: [keywords words=apples,oranges] ). Post ID can be specified using the shortcode …
<?php
/**
* Plugin Name: Post Keywords Shortcode
* Plugin URI: https://gist.github.com/sscovil/5779312
* Description: Searches a post for keywords and displays them if found.
* Version: 0.1
* Author: Shaun Scovil
* Author URI: http://shaunscovil.com
* License: GPL2
*/
function post_keywords_shortcode_06132013( $atts ) {
global $post;
$post_id = ( isset( $atts['id'] ) ) ? $atts['id'] : $post->ID;
$content = get_the_title( $post_id ) . get_the_content_by_id( $post_id );
$content = preg_replace( '/[keyword*]/', '', $content );
$content = apply_filters( 'the_content', $content );
$keywords = ( isset( $atts['words'] ) ) ? explode( ',', $atts['words'] ) : get_post_meta( $post_id, 'keyword' );
$output = '';
$prefix = 'Keywords: ';
foreach( $keywords as $keyword ) {
if ( false !== stripos( $content, $keyword ) ) {
$output .= $prefix . $keyword;
$prefix = ', ';
}
}
return $output;
}
add_shortcode( 'keywords', 'post_keywords_shortcode_06132013' );
if ( function_exists( 'get_the_content_by_id' ) ) {
function get_the_content_by_id( $post_id ) {
global $post;
if ( $post->ID == $post_id )
return get_the_content();
$findpost = get_post( $post_id );
return $findpost->post_content;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment