Support » Developing with WordPress » Help Creating a Post Category Shortcode

  • Resolved semperaye

    (@semperaye)


    Hi. I found a function online to create a shortcode to display the comment count of particular posts (see code below), but I am in need of a shortcode to display the post category. Does someone have a code similar to this one that will work for the purpose of displaying a particular post’s category?

    Thanks!

    function comments_shortcode($atts) {
    	extract( shortcode_atts( array(
    		'id' => ''
    	), $atts ) );
    	$num = 0;
    	$post_id = $id;
    	$queried_post = get_post($post_id);
    	$cc = $queried_post->comment_count;
    		if( $cc == $num || $cc > 1 ) : $cc = $cc.' Comments';
    		else : $cc = $cc.' Comment';
    		endif;
    	$permalink = get_permalink($post_id);
    	return '<a href="'. $permalink . '">' . $cc . '</a>';
    } add_shortcode('comments', 'comments_shortcode');

    [comments id=”23″ ]

Viewing 15 replies - 1 through 15 (of 34 total)
  • Moderator bcworkz

    (@bcworkz)

    You can use the same concept as the comment count code, but call wp_get_post_categories(), passing $post_id. This function can return different values, depending on the $fields argument. You can get it to only return category term names, or entire WP_Term objects.

    From the returned list, create your desired output string to return. A partial, basic example:

    $cats = wp_get_post_categories( $post_id, ['fields'=>'names']);
    return 'Filed under: ' . implode( $cats, ', ');

    If you want to link to category term archives, you’ll need to elaborate by getting entire term objects and generating the HTML links from term slugs.

    Thread Starter semperaye

    (@semperaye)

    Hi bcworkz,

    Thank you for the reply! Here is what I came up with… IDK if I am close or not:

      add_shortcode( 'category_type', 'categories' );
        function categories(){
    
            $cats = wp_get_post_categories( $post_id, ['fields'=>'names']);
    return 'Filed under: ' . implode( $cats, ', ');
    }

    [category_type]

    It returns “Filed Under:”
    Maybe I’m missing something?

    Thread Starter semperaye

    (@semperaye)

    Note: In my original post I used the wrong code (IDK where I got that other one from haha). It’s actually the following thats working for my comment count:

      add_shortcode( 'comment_no', 'commno' );
        function commno(){
    
            $number= get_comments_number(get_the_ID());
    
            return $number;
    }

    I just tried to edit it with the code you provided, but in reality IDK what I’m doing 😛

    Moderator bcworkz

    (@bcworkz)

    Heh, gotta start somewhere 🙂 The critical distinction is where the post ID is coming from. If get_the_ID() is working for you, then something like this is a start (untested):

    add_shortcode('post_cats', 'sa_show_cats');
    function sa_show_cats(){
      $cats = wp_get_post_categories( get_the_ID(), ['fields'=>'names']);
      return 'Filed under: ' . implode( $cats, ', ');
    }
    Thread Starter semperaye

    (@semperaye)

    Hi bcworkz,

    That code worked! I don’t suppose there is a way to filter out the text “filed under:”? Right now the code outputs “Filed Under: Uncategorized”

    Thank you for this. None of the shortcode plugins could do this!

    My ultimate goal is to have the category clickable to pull up all posts in that category.

    Moderator bcworkz

    (@bcworkz)

    Yeah, sure, just remove it from code:
    return implode( $cats, ', ');

    When you code your own shortcode handler, just about anything is possible 🙂

    Making the categories clickable is certainly possible, but the code gets a little more involved. Something like this, again untested:

    add_shortcode('post_cats', 'sa_show_cats');
    function sa_show_cats() {
      $cats = wp_get_post_categories( get_the_ID());
      $html = array();
      foreach ( $cats as $cat ) {
        $url = site_url("/category/{$cat->slug}/");
        $html[] = "<a href=\"$url\">{$cat->name}</a>";
      }
      return '<div class="cat-links">' . implode( $html, ', ') . '</div>';
    }

    In this example, I’ve wrapped the cat links in a div so they are easier to style with CSS. For example:

    .cat-links a {
      color: green;
    }
    Thread Starter semperaye

    (@semperaye)

    Hello again bcworkz,

    Thank you for taking time to help me with this. I was able to remove the “filed under:” text, thank you 🙂 Unfortunately the 2nd code to make it clickable didn’t work, it just created a file icon in place of the category text and merged everything to the left.

    Moderator bcworkz

    (@bcworkz)

    Huh, that sounds rather odd. I just tested my code and found the docs on the default arguments for wp_get_post_categories() is incorrect. Please change the $cats line to:
    $cats = wp_get_post_categories( get_the_ID(),['fields'=>'all',]);
    Works on my site at least.

    That might not change the positioning issue though, that may be due to a name collision of the class attribute. In the return line, change the class value “cat-links” to something unlikely to already be used in your CSS, perhaps “sa-cat-links” or even “kslsfhjw” (intentional gibberish). If that doesn’t help, we’ll need to add some CSS rules to get the positioning the way you want.

    If it comes down to adding CSS rules, it will be very helpful if you can provide a link to a live page containing the shortcode output.

    Thread Starter semperaye

    (@semperaye)

    Cool it works…but ya the positioning issue is still there, and the picture of the file icon to the left of the text. Additionally it’s changing the rest of the text css next to it black 😛 I added the sa_ but it didn’t change anything.

    Please see this test post:
    https://www.seosemper.com/test-post/

    I never realized this was so complicated, but I guess thats why none of the shortcode plugins for WP had the clickable categories as a feature.

    Thank you for all the help!

    Moderator bcworkz

    (@bcworkz)

    Well, the CSS to affect the category link can be something like this:

    .sa-cat-links a {
    	margin-left: 28%;
    	color: #fff;
    }

    Add that to the Additional CSS panel of the customizer. Add or edit as desired. There should be no folder icon since you added the “sa-“, if you are still seeing it, flush you browser cache.

    As far as affecting other post meta after it, it is because the shortcode output is ending up in the middle of some span styling tags, which invalidates the span’s styling applied to other post meta. This is a common issue when shortcodes are inserted into post content when using the visual tab. If you switch to the text tab, you’ll see that it’s amongst span and p tags. If you move the shortcode to above all these styling spans and the initial p tag, it will not affect other text and the CSS that is applied like above will be more consistently applied.

    Thread Starter semperaye

    (@semperaye)

    bcworkz,

    Hello again 🙂 Thank you for all this information, especially in explaining the span issue, I think I figure that part out. However, the css didn’t work to fix the positioning of the categories text 🙁 I tried to fool around with it but couldn’t get it to work.

    Moderator bcworkz

    (@bcworkz)

    The CSS from my previous post is being applied in my view. The category link is white and has a 28% left margin. If you aren’t seeing that, flush your browser cache. What else are you trying to do that is not working?

    Thread Starter semperaye

    (@semperaye)

    Hello again 🙂

    This is what I’m seeing in incognito with cache flushed:

    https://imgur.com/a/VhRCORA

    I’m trying to make one line, centered.

    Moderator bcworkz

    (@bcworkz)

    OK then. Please remove the margin-left: 28%; line from the previous CSS I gave you. To get it all on one line, add this rule to the CSS:

    .sa-cat-links {
        display: inline;
    }

    I’m not sure why the line won’t center. There’s some subtle HTML error where I’m not seeing the source, but it could be the cause. You’re not going to be hardcoding the rest of the post meta line like it is now, right? Is your plan to eventually cause the shortcode to output the entire line? It would be very helpful if the entire line were contained in the sa-cat-links div. It’s infeasible to tell disparate elements to each center themselves, the entire thing needs to be told to center itself.

    Could we for now include the other post meta in the shortcode output as hardcoded placeholder text? The dynamic content can replace it later. It’ll be easier to get everything centered if it’s all in one div. So to do this, remove the other post meta from content, along with related elements with style attributes. The only thing after the title should be the shortcode. Change the return line of the shortcode handler function to this:
    return '<div class="cat-links">' . implode( $html, ', ') . ' • Derek • June 12, 2018 • <a href="#comments">0 Comments</a></div>';

    Then replace the display inline CSS rule I just gave you with this:

    .sa-cat-links {
      text-align: center;
      font-size: 16px;
      color: #fff;
      margin: 0 auto;
    }

    Retain the rule with selector .sa-cat-links a that colors links (where the margin-left rule was removed).

    Thread Starter semperaye

    (@semperaye)

    Hi the text is all one one line now, but I am not able to make the entire thing white & centred. I’m using other shortcodes so I don’t think the above is possible. Here is what I’m looking at inside the text editor:

    <h1 style="text-align: center;"><strong>[field title]</strong></h1>
    <p style="text-align: center;">[sa_post_cats] <span style="font-size: 16px;">•  [field author]  •  [field date]  •  <a href="#comments">[comment_no] Comments</a></span></p>
Viewing 15 replies - 1 through 15 (of 34 total)
  • The topic ‘Help Creating a Post Category Shortcode’ is closed to new replies.