Use Block widgets to display related posts by tag

Posted in: Newspaper
Post count: 4

Hi,

I want to use the block widgets (e.g. [tagDiv] Block 4) in the sidebar to display related posts. I want to filter the related posts by tag.

So e.g. on a page, which has the tag “tag1” the block widget should only show other posts which also have the tag “tag1”.

On pages with “tag2” the widget should only show posts which also have the tag “tag2”, etc.

The question is: how can I do this, when tags are dynamically created as the site grows and we do not want to have different sidebars for each tag?

Thanks for your help!

Post count: 6600

Hi,

You can do it by adding the block from single.php file before the sidebar using the do_shortcode() function like this: http://screencast.com/t/0diGnANrnc

This way you will display first in the sidebar a “Related Posts” section by current posts first tag, it will display the posts that have the tag which is first on current post tags, it’s using block 5. You can customize the block from page builder and you can find the shortcode if you switch to classic mode.

Here you have the code from my example: http://pastebin.com/pZNUHNTL
You can do the same in case the sidebar is on the left side.

Result: http://screencast.com/t/xaqyue8Wc
Let me know if it works.

Thanks

Post count: 4

Hi Lucian,

very cool! Worked for me! I extended it a little bit, that it can use more than one tag and does not appear at all, if there is none:


$post_tags = get_the_tags();
$tags_filter = '';
		
if ($post_tags)
{
  for($i=0;$i<count(array_values($post_tags));$i++)
  {
    $tags_filter .= array_values($post_tags)[$i]->slug.',';
  }
			
  $tags_filter = substr($tags_filter,0,-1);
  echo do_shortcode('[td_block4 tag_slug=' . '"' . $tags_filter . '"' . ' limit="5" custom_title="'Related Posts'"]');
}

Thanks for your help!

BR, Claudio

Viewing 3 posts - 1 through 3 (of 3 total)
The forum ‘Newspaper’ is closed to new topics and replies.