WordPress.org

Ready to get started?Download WordPress

Forums

Change code to pull in related posts by tags help (3 posts)

  1. Tommy White
    Member
    Posted 2 years ago #

    I have a snippet of code that I have been trying to learn how it functions so that I can modify it to pull in related posts by tags instead of categories. I am hoping someone can teach me what to do.

    function get_related_posts($postdata)
    {
    	$postCatArr = wp_get_post_categories( $postdata->ID );
    	$post_array = array();
    	for($c=0;$c<count($postCatArr);$c++)
    	{
    		$category_posts=get_posts('category='.$postCatArr[$c]);
    		foreach($category_posts as $post)
    		{
    			if($post->ID !=  $postdata->ID)
    			{
    				$post_array[$post->ID] = $post;
    			}
    		}
    	}
    if($post_array)
    {
    ?>

    I looked up most of the functions but some I didn't understand what the code is telling WP what to do, like: if($post->ID != $postdata->ID) and for($c=0;$c<count($postCatArr);$c++).

    Can anyone shed some light on what I need done so that I can learn to make modifications easier?

    Thank you!

  2. alchymyth
    The Sweeper & Moderator
    Posted 2 years ago #

    instead
    wp_get_post_categories( $postdata->ID );
    try and use
    wp_get_post_terms( $postdata->ID, 'post_tag' );
    http://codex.wordpress.org/Function_Reference/wp_get_post_terms

    instead
    get_posts('category='.$postCatArr[$c]);
    try and use
    get_posts('tag_id='.$postCatArr[$c]->term_id);
    http://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters
    use tag_id

    ---
    this section
    if($post->ID != $postdata->ID)
    is there to avoid to duplicate the current post
    http://php.net/manual/en/language.operators.logical.php

    this section
    for($c=0;$c<count($postCatArr);$c++)
    is an ordinary php 'for' loop
    http://php.net/manual/en/control-structures.for.php

  3. Tommy White
    Member
    Posted 2 years ago #

    Thank you for the explanations and information!

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.