0

I have two scripts to display related posts that fit my terms, but I don't know how to call them, please help me. I found this code here.

Related Posts 1:

function get_pew_related_data($args, $post_id, $related_id) {
    global $post, $wpdb;
    $post_id = intval( $post_id );
    if( !$post_id && $post->ID ) {
        $post_id = $post->ID;
    }

    if( !$post_id ) {
        return false;
    }

    $defaults = array(
        'taxonomy' => 'topics',
        'post_type' => array('post'),
        'max' => 5
    );
    $options = wp_parse_args( $args, $defaults );

    $transient_name = 'pew-related-' . $options['taxonomy'] . '-' . $post_id;

    if( isset($_GET['flush-related-links']) && is_user_logged_in() ) {
        echo '<p>Related links flushed! (' . $transient_name . ')</p>';
        delete_transient( $transient_name );
    }

    $output = get_transient( $transient_name );
    if( $output !== false && !is_preview() ) {
        //echo $transient_name . ' read!';
        return $output;
    } 

    $args = array(
        'fields' => 'ids',
        'orderby' => 'count',
        'order' => 'ASC'
    );
    $orig_terms_set = wp_get_object_terms( $post_id, $options['taxonomy'], $args );

    //Make sure each returned term id to be an integer.
    $orig_terms_set = array_map('intval', $orig_terms_set);

    //Store a copy that we'll be reducing by one item for each iteration. 
    $terms_to_iterate = $orig_terms_set;

    $post_args = array(
        'fields' => 'ids',
        'post_type' => $options['post_type'],
        'post__not_in' => array($post_id),
        'posts_per_page' => 50
    );
    $output = array();
    while( count( $terms_to_iterate ) > 1 ) {

        $post_args['tax_query'] = array(
            array(
                'taxonomy' => $options['taxonomy'],
                'field' => 'id',
                'terms' => $terms_to_iterate,
                'operator' => 'AND'
            )
        );

        $posts = get_posts( $post_args );

        /*
        echo '<br>';
        echo '<br>';
        echo $wpdb->last_query;
        echo '<br>';
        echo 'Terms: ' . implode(', ', $terms_to_iterate);
        echo '<br>';
        echo 'Posts: ';
        echo '<br>';
        print_r( $posts );
        echo '<br>';
        echo '<br>';
        echo '<br>';
        */

        foreach( $posts as $id ) {
            $id = intval( $id );
            if( !in_array( $id, $output) ) {
                $output[] = $id;
            }
        }
        array_pop( $terms_to_iterate );
    }

    $post_args['posts_per_page'] = 10;
    $post_args['tax_query'] = array(
        array(
            'taxonomy' => $options['taxonomy'],
            'field' => 'id',
            'terms' => $orig_terms_set
        )
    );

    $posts = get_posts( $post_args );

    foreach( $posts as $count => $id ) {
        $id = intval( $id );
        if( !in_array( $id, $output) ) {
            $output[] = $id;
        }
        if( count($output) > $options['max'] ) {
            //We have enough related post IDs now, stop the loop.
            break;
        }
    }

    if( !is_preview() ) {
        //echo $transient_name . ' set!';
        set_transient( $transient_name, $output, 24 * HOUR_IN_SECONDS );
    }

    return $output;
}

function pew_related( $args = array(), $post_id = '', $related_id = '' ) {
    $post_ids = get_pew_related_data( $args, $post_id, $related_id );

    if( !$post_ids ) {
        return false;
    }

    $defaults = array(
        'post__in' => $post_ids,
        'orderby' => 'post__in',
        'post_type' => array('post'),
        'posts_per_page' => min( array(count($post_ids), 10)),
        'related_title' => 'Related Posts'
    );
    $options = wp_parse_args( $args, $defaults );

    $related_posts = new WP_Query( $options );
    if( $related_posts->have_posts() ):
    ?>
    <h5><?=$options['related_title']?></h5>
    <div id="related-material" class="promo">
        <?php while ( $related_posts->have_posts() ):
            $related_posts->the_post();
        ?>
            <a class="post" href="<?=the_permalink();?>">
                <div class="meta">
                    <?php
                    $post_project = wp_get_object_terms($related_posts->post->ID, 'projects');
                    $project = 'Pew Research Center';
                    $project_slug = '';
                    if( isset($post_project[0]) ) {
                        $project = $post_project[0]->name;
                        $project_slug =  $post_project[0]->slug;
                    } elseif( $related_posts->post->post_type == 'fact-tank' ) {
                        $project = 'Fact Tank';
                        $project_slug = 'fact-tank';
                    }
                    ?>
                    <span class="project <?=$project_slug;?> right-seperator"><?=$project;?></span>
                    <span class="date"><?php the_time('M j, Y'); ?></span>
                </div>
                <h2><?=the_title();?></h2>
            </a>
        <?php endwhile;
            wp_reset_postdata();

         ?> 
    </ol>
    </div>
    <?php
    endif;

}

Related Posts 2:

function exe_get_related_posts_by_common_terms( $post_id, $number_posts = 0, $taxonomy = 'post_tag', $post_type = 'post' ) {
    global $wpdb;

    $post_id = (int) $post_id;
    $number_posts = (int) $number_posts;

    $limit = $number_posts > 0 ? ' LIMIT ' . $number_posts : '';

    $related_posts_records = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT tr.object_id, count( tr.term_taxonomy_id ) AS common_tax_count
             FROM {$wpdb->term_relationships} AS tr
             INNER JOIN {$wpdb->term_relationships} AS tr2 ON tr.term_taxonomy_id = tr2.term_taxonomy_id
             INNER JOIN {$wpdb->term_taxonomy} as tt ON tt.term_taxonomy_id = tr2.term_taxonomy_id
             INNER JOIN {$wpdb->posts} as p ON p.ID = tr.object_id
             WHERE
                tr2.object_id = %d
                AND tt.taxonomy = %s
                AND p.post_type = %s
             GROUP BY tr.object_id
             HAVING tr.object_id != %d
             ORDER BY common_tax_count DESC" . $limit,
            $post_id, $taxonomy, $post_type, $post_id
        )
    );

    if ( count( $related_posts_records ) === 0 )
        return false;

    $related_posts = array();

    foreach( $related_posts_records as $record )
        $related_posts[] = array(
            'post_id' => (int) $record->object_id,
            'common_tax_count' => $record->common_tax_count
        );

    return $related_posts;
}
1

I think you have two options on how to use the functions you've found. The first one is to add one of the functions to your single post template file.

pew_related( 
  array(), // add custom parameter key=>value pairs, if needed
  get_the_ID(), 
  '' // not sure what is the purpose of the third parameter 
); 

or

$related_posts = exe_get_related_posts_by_common_terms( get_the_ID(), 3, 'post_tag', 'post' );
if ( $related_posts ) {
  // foreach loop the $related_posts array for desired html output
}

The second option is to hook one of functions to suitable action or filter. For example,

// functions.php
add_filter( 'the_content', function($content){
  if ( ! is_singular( 'post' ) ) {
    return $content;
  }
  ob_start(); // push html output to buffer
  pew_related( 
    array(), // add custom parameter key=>value pairs, if needed
    get_the_ID(), 
    '' // not sure what is the purpose of the third parameter 
  ); 
  $related_html = ob_get_clean(); // get buffer content
  return $related_html ? $content . $related_html : $content; // concat html to post content
} );
| improve this answer | |
  • Hi @Antti Can you tell me the script is complete with html? – Renomu Reza Nov 19 '19 at 6:06
  • @RenomuReza pew_related() looks like it spits out some html, but for the second one you'll need to write your own html. But in any case, If I were you, I wouldn't just copy-paste the codes as is, but instead I'd tweak and modify them to fit my exact setup. – Antti Koskinen Nov 19 '19 at 7:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.