Skip to content

Internal Shortcode | [Post_Categories]

EkoJr edited this page Feb 24, 2017 · 2 revisions

Description

Adds the WP's built-in taxonomy Categories that is associated with the post.

Usage

`[post_categories delimiter=", " links="true"]

Params

delimiter

(string) (optional) Adds a string to divide multiple categories. Default: ", "

links

(boolean) (optional) Determines whether to add a link to the category's title. Default: "true"

Return

(string) Adds the Post's categories (w/ links if true).

Examples/Sample

Example 1

[post_categories]

Returns

<a href="example.com/category/uncategorized/ >Uncategorized</a>

Source

File: advanced-post-list/includes/class/apl_shortcodes.php

/**
 * Categories Shortcode. 
 * 
 * Desc: Adds Categories associated with Post/Page. 
 * 
 * 1. Set Attribute 'Links' to a Boolean variable. 
 * 2. Get the categories. If none, do Step 4. 
 * 3. For each category there is add the category name, w/ link if true, 
 *    and add a delimiter except for last category.
 * 4. Return string.
 * 
 * @since 0.1.0 
 * @version 0.4.0 - Changed to Class function, and uses WP's built-in
 *                  functions for setting default attributes & do_shortcode().
 * 
 * @param array $atts {
 *      
 *      Shortcode Attributes. 
 *      
 *      @type string $delimiter     Inserts a separator, default is ", ".
 *      @type string $links         Return as an html link if true.
 * }
 * @return string Categories used in post/page.
 */
public function post_categories($atts)
{
    //INIT
    $atts_value = shortcode_atts( array(
        'delimiter' => ', ',
        'links' => 'true'
    ), $atts, 'post_categories');
    $return_str = '';
    
    //STEP 1
    $atts_value['links'] = TRUE;
    if (strtolower($atts_value['links']) == 'false')
    {
        $atts_value['links'] = FALSE;
    }
    
    //STEP 2
    $post_categories = get_the_category($this->_post->ID);
    $array_total = count($post_categories);
    $i = 1;
    if ($post_categories)
    {
        //STEP 3
        foreach ($post_categories as $category)
        {
            if ($atts_value['links'])
            {
                $return_str .= '<a href="' . get_tag_link($category->term_id) . '" >' . $category->name . '</a>';
            }
            else
            {
                $return_str .= $category->name;
            }

            if ($array_total > $i)
            {
                $return_str .= $atts_value['delimiter'];
            }
            $i++;
        }
    }
    
    //STEP 4
    return $return_str;
}

Additional Resources

Clone this wiki locally