0

Using the WP Types Plugin, I setup a custom post type (slug: portfolio), which has a custom taxonomy (slug: portfolio-category).

The custom taxonomy has three items (slugs: group1, group2, group3) to organize portfolio posts.

On each single portfolio page I am displaying 3 related posts from the same taxonomy term, filtered by slug:

global $post;

$term_list = wp_get_post_terms($post->ID, 'portfolio-category', array("fields" => "names"));

      $wpex_port_query = new WP_Query(
          array(
              'post_type' => 'portfolio',
              'showposts' => '3',
              'orderby' => 'rand',
              'post__not_in' => array($post->ID),
              'no_found_rows' => true,
              'tax_query' => array(
                  array(
                     'taxonomy' => 'portfolio-category',
                     'field'    => 'slug',
                     'terms'    => $term_list,
                    )
                )
            )
        );

This basically works, but I am wondering if there is a better way than creating a global variable $post? What is the recommended way to handle this?

2 Answers 2

0

I am not sure what your issue is precisely, you are not creating $post, just accessing it. It is a very common sight in WordPress.

However from API point of view, is ID of current post is the only thing you need — use get_the_ID() function to get just that, sans dealing with global yourself.

0

You can use get_queried_object_id() if for some reason the global $post doesn't currently contain the main query's post object, though wp_reset_postdata() should fix that if that's the case. As Rarst said, it's not really harmful to access the global $post, it already exists anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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