Monday, October 7, 2013

Shorttext functionality in Wordpress

Udate: I found a much eassier way:

In my previous CMS I created a shorttext function that allowed me to insert text or html code anywhere on the page with the shortText function. The content was managed in a seperate admin menu.

I know that I should use widgets for this functionality, but I think my solution is way faster - or I just don't like widgets that much :-)

The code I'm adding to the theme's functions.php file is this:

 // Insert a short text anywhere  
 function shortText($id) {  
      $post = get_post($id);   
      $content = $post->post_content;  
      return apply_filters('the_content', $content);  
 // Insert a short text title anywhere  
 function shortTextTitle($id) {  
      $post = get_post($id);   
      $title = $post->post_title;  
      return apply_filters('the_title', $title);  
 function addShortText($atts, $string) {   
      return shortText($string);  
 function addShortTextTitle($atts, $string) {   
      return shortTextTitle($string);  
 function register_shortcodes() {   
      add_shortcode('shorttext', 'addShortText');   
      add_shortcode('shorttexttitle', 'addShortTextTitle');   
 add_action('init', 'register_shortcodes');  

Basically this crates two functions that you can insert into your code to insert a post title or content based on it's id.

Use it like this:

 //Insert the title of post #11  
 <?php shortTextTitle(11); ?>  
 //Insert the content of post #11  
 <?php shortText(11); ?>  

I also created shortcodes for this functionality, you can insert it into your post with [shorttexttitle]11[/shorttexttitle] and [shorttext]11[/shorttext]. (The number 11 is an example post ID)

To make things even more convenient, I made a custom post type with Custom Content Type Maneger ( named Shorttext to seperate this type of content from pages and posts.