asr asr - 4 years ago 112
PHP Question

show correct category name and fix post title permalink wordpress

I use this code to show different posts in different divs.

I have 2 problems:

  1. I can't show the correct category name to current post.

    • The same category name is applied to 2 post when I use:


  2. Clicking on the post title redirect me to home page instead post's page!

    <div class="modulex">
    $args = array('numberposts' => '1', 'post_status' => 'publish', 'offset' => '2');
    $recent_posts = wp_get_recent_posts($args);

    foreach ($recent_posts as $recent) {?>

    <div><?php echo get_the_post_thumbnail($recent['ID'],'small', array('class'=>'img-fluid')); ?></div>
    <div class="spanlike"><h6><a href="<?php get_permalink($recent["ID"]) ?>"><?php echo $recent["post_title"] ?></a></h6></div>

    <?php } ?>

Answer Source
  1. The problem with this is that get_category_link requires a category ID as argument, not post ID. To get around this, you'll have to perform several steps:

    • retrieve a list of categories for your post
    • decide which category to use from the list (assuming you only have one category per post, just use the first/only one)
    • get the link for this category

    I would suggest using a custom function for this. Example below.

  2. Here I think your problem is that get_permalink returns rather than echos. You could use the permalink instead:

    <div class="spanlike"><h6><a href="<?php the_permalink($recent["ID"]) ?>"><?php echo $recent["post_title"] ?></a></h6></div>

Example function for retrieving category link from post ID:

function get_cat_link_from_postID($postID) {
  $categories = get_the_category($postID);
  $catID = $categories[0]->term_id;
  return get_category_link($catID);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download