• 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 - 16 through 30 (of 34 total)
  • Moderator bcworkz

    (@bcworkz)

    Thanks, that’s helpful. Maybe we should take that div out of the shortcode. My idea of having a div to manipulate is fine for the category link alone, but it apparently does not play well with others. Just do this for the return line:
    return implode( $html, ', ');

    The output is then just plain HTML. You should be able to apply editor styling as though the output were plain text. You may as well remove all of the sa-cat-links CSS I had you add as well.

    FWIW, we could have included the other shortcodes in the category shortcode. It’s feasible to do shortcodes within shortcodes by running the output through do_shortcode() before returning it. If you still have trouble with the above scheme we can try this. It’s better to try a simpler solution before getting fancy with coding.

    Thread Starter semperaye

    (@semperaye)

    Hi!

    Well it looks like we finally got it working! The only issue I had was that I couldn’t style to hyperlink. I had to use custom css.

    .fl-module-content a, .fl-module-content a:hover, .fl-module-content a:focus {
        color: #ffffff;
        text-decoration: none;
    }

    I’m not sure if this custom css is actually best though, because I think it’s targeting all of my Beaver Builder content links…. Is there a way to target just the sa_posts_cats shortcode with css?

    Thank you for all your assistance!

    Moderator bcworkz

    (@bcworkz)

    Sure, we can add a class attribute to the shortcode output. We can reuse the sa-cat-links class from the removed div, assuming the related old CSS has been removed. Updated $html[] line:
    $html[] = "<a class=\"sa-cat-links\" href=\"$url\">{$cat->name}</a>";

    Then the new CSS to style those links:

    a.sa-cat-links {
      color: #ffffff'
    }
    Moderator bcworkz

    (@bcworkz)

    FYI, I’ll be offline for a few days. If you get no response to a new post here, I’m not ignoring you, I’ll answer as soon as I’m able.

    Thread Starter semperaye

    (@semperaye)

    Sorry for my ignorance to all of this, but where in the html do I place the "<a class=\"sa-cat-links\" href=\"$url\">{$cat->name}</a>"; I’m assuming I don’t need the $html{}=?

    <h1 style="text-align: center;"><span style="color: #ffffff;"><strong>[field title]</strong></span></h1>
    <p style="text-align: center;"><span style="color: #ffffff;">[sa_post_cats]<span style="font-size: 16px; color: #ffffff;"> •  [field author]  •  [field date]  •  <a style="color: #ffffff;" href="#comments">[comment_no] Comments</a></span></span></p>

    I tried a few things but I must be doing it wrong 😛

    Moderator bcworkz

    (@bcworkz)

    No worries. The issue is it does not go in HTML, rather it replaces a line in the shortcode handler, where ever you had placed the current handler, probably functions.php. Here’s the entire handler code with the updated line:

    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 class=\"sa-cat-links\" href=\"$url\">{$cat->name}</a>";
      }
      return implode( $html, ', ');
    }

    As PHP code, you do indeed need the $html[] = part 🙂

    Then you can style the resulting links with CSS similar to

    a.sa-cat-links {
      color: #ffffff;
    }

    (there was a typo in my previous CSS example, fixed here)

    I appreciate your patience while I was away and all through this process.

    Thread Starter semperaye

    (@semperaye)

    Hmmm this seems to have caused an error 500. I’m going to look into this and get back to ya, ty!

    /wp-content/plugins/code-snippets/php/snippet-ops.php(353) : eval()’d code on line 10

    Thread Starter semperaye

    (@semperaye)

    Update: Ok so the only way to get my site back up was to disable the php snippets plugin, this means I’ll lose all my snippets…. I should have backed them up 🙁 Using an older version of the plugin files didn’t work… IDK what to do now.

    Namecheap told me “they are unable to find the specified code, that was pasted and 500 error happened after that, within my hosting account’s files.” I can only give them a copy of the php code. I’m trying to have them restore the site back a few days, because the only image I have is from months ago (my bad).

    Thread Starter semperaye

    (@semperaye)

    I’ve got it back up. They had a server image from the 9th, they don’t normally restore for customers but they did for me thank god. I’m going to focus on getting the site back to how it was (the custom css seems to be bugged) then back it up before I try this again.

    Moderator bcworkz

    (@bcworkz)

    Oh noes! Did I do that? I think I did 🙁 That’s an extreme, unusual result though. The problem was a repeat of the same earlier error where the function docs were in error about defaults. I copied the code from an earlier post, changed that one line, forgetting about the entire bad documentation issue. I am so sorry, I feel terrible.

    The usual result is non-fatal, but code like that is not usually placed in a PHP snippets plugin. Anyway, the corrected line is
    $cats = wp_get_post_categories( get_the_ID(),['fields'=>'all',]);

    If you are using shortcodes to execute PHP to generate output, you don’t really need a PHP snippets plugin. The shortode declaration code such as what I posted (with correction) can be placed in a theme’s functions.php file. If you have a decent collection of shortcodes, for the sake of organization, you can create your own plugin to contain all of your shortcode declarations. It’s actually fairly easy, making a new .php file with a particular comment at the top and shortcode declarations below. Upload the file to plugins folder. It’ll the show up on the plugins screen where it can be activated.

    Here’s the contents of a complete plugin file. You can add other shortcode declarations here as well.

    <?php
    /*
    Plugin Name: sa-custom
    Description: Custom code for semperaye's shortcodes 
    Author: semperaye
    Version: 1.00
    License: GPL
    */
    
    add_shortcode('sa_post_cats', 'sa_show_cats');
    function sa_show_cats() {
      $cats = wp_get_post_categories( get_the_ID(), ['fields'=>'all',]);
      $html = array();
      foreach ( $cats as $cat ) {
        $url = site_url("/category/{$cat->slug}/");
        $html[] = "<a class=\"sa-cat-links\" href=\"$url\">{$cat->name}</a>";
      }
      return implode( $html, ', ');
    }

    This does require that you be able to upload a file to your server. Most people use FTP, but your hosting control panel should have a file manager app that will do the job. Placed in a plugin, errors like we experienced will not crash the site, but if it did, you can remove the erroneous plugin yourself through FTP or the file manager.

    • This reply was modified 7 years, 9 months ago by bcworkz. Reason: changed shortcode name to sa_post_cats
    Thread Starter semperaye

    (@semperaye)

    Hello again! Thank you for your continued support with this 🙂 I’ll certainly look into a custom site plugin at some point. In regard to the newly corrected code, I’m getting the following error:

    “The snippet has been deactivated due to an error on line 4:

    syntax error, unexpected ‘$html’ (T_VARIABLE)”

    I’m certainly not going to try anything here in case I break something, I’ll wait for your reply 😛 Thanx!

    Moderator bcworkz

    (@bcworkz)

    I just double checked my code from my last post and it worked fine, except for use as a stand alone plugin file, I neglected to include the initial <?php of the file. I’ve since corrected the above code so when you decide to try it as a plugin it’s complete. This would not cause the error you are seeing.

    We often see that sort of error because of an issue on the line above the one mentioned. Most frequently, it’s a missing semi-colon ; at the end of the line. Please double check your version against mine above and be sure it matches perfectly, in particular the line with wp_get_post_categories().

    I don’t think this next thought applies to you, but on some servers that are running old versions of PHP, the ['fields'=>'all',] syntax is invalid and needs to be changed to array('fields'=>'all',). Since you had your host restore from backup, there’s a remote chance this could be an issue, but the “unexpected ‘$html’ error makes the missing semi-colon or other minor syntax blunder much more likely.

    I must say that I’m rather concerned about how my mistake regarding the default arguments for wp_get_post_categories() being in placed within the PHP snippets plugin caused the entire site to crash. When placed as normal code outside of a snippets plugin, nothing awful happens. The code itself doesn’t work but all else does. Some PHP warnings are logged in the error file, and maybe output to the browser, but all else still works. I understand why you like to use such a plugin, and it’s too soon to make major changes now, but some time in the future, you would be well served to learn how to do without snippets by using shortcodes added to the plugin I started.

    Thread Starter semperaye

    (@semperaye)

    Now I have another error 500 🙁 Sigh. lol…

    I’ve contacted plugin support.

    Moderator bcworkz

    (@bcworkz)

    Sorry to here that. I’m sure this time my code is OK. Tested on my site, but I don’t have a PHP snippets plugin.

    It looks like your site is back up, at least the test-post page is working. There’s a mis-match in shortcode names between post content and my code, due to my copying of an old version and updating only part of it in an effort to give you the entire thing in one place. [post_cats] vs. [sa_post_cats] Coordination required, either change the shortcode in post content or the name in the add_shortcode() call.

    Thread Starter semperaye

    (@semperaye)

    Hi. Thank you for looking into this for me. I tried your suggestion but that didn’t help. Error 500 again 🙁

Viewing 15 replies - 16 through 30 (of 34 total)

The topic ‘Help Creating a Post Category Shortcode’ is closed to new replies.