I currently build a custom shortcode to call related posts based on tags. The shortcode is working fine as it is. Now I want to turn the related posts based on tags into categories-related.

I've tried to change the "tag" with "category", but nothing worked out.

Here's the working sample for related posts based on tags:

function seniberpikir_bacajuga( $atts ) {
        'limit' => '4',
    ), $atts));

    global $wpdb, $post, $table_prefix;

    if ($post->ID) {
        $retval = '<div class="bacajuga-konten"><h5 class="bacajuga-title">Baca <span style="color:#0c6;">Juga</span>:</h3><ul class="td-arrow-list">';
        // Get tags
        $tags = wp_get_post_tags($post->ID);
        $tagsarray = array();
        foreach ($tags as $tag) {
            $tagsarray[] = $tag->term_id;
        $tagslist = implode(',', $tagsarray);

        // Do the query
        $q = "SELECT p.*, count(tr.object_id) as count
            FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy ='post_tag' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id  = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID
                AND p.post_status = 'publish'
                AND p.post_date_gmt < NOW()
            GROUP BY tr.object_id
            ORDER BY RAND()
            LIMIT $limit;";

        $related = $wpdb->get_results($q);
        if ( $related ) {
            foreach($related as $r) {
                $retval .= '
    <li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'">'.wptexturize($r->post_title).'</a></li>
        } else {
            $retval .= '
    <li>Tidak ada artikel terkait.</li>';
        $retval .= '</ul></div>';
        return $retval;
add_shortcode('bacajuga', 'seniberpikir_bacajuga');

Now I want to turn this into related posts based on categories and call them using shortcode [bacajuga].

Any help would be much appreciated.

Thanking you guys in advance!

0 Answers