0

How can i get post id from taxonomy term name?

Taxonomy is : post_tag post_type is : videos and i have the term name to use to get posts

i tried

$args = query_posts(array( 
    'post_type' => 'videos',
         array(
            'taxonomy' => 'post_tag',
            'terms' => $term_name,
            'field' => 'name'
        )
    )
);
codewario
  • 19,553
  • 20
  • 90
  • 159
Shakavkav
  • 151
  • 1
  • 2
  • 11

1 Answers1

0

Here are a few issues with your current code:

  1. Regarding your usage of query_posts, "This function isn't meant to be used by plugins or themes" (source). Use WP_Query or get_posts, instead.
  2. You are assigning your query_posts data to a variable named $args, but it will actually return posts - not arguments - so that's confusing (bad practice).

Here is a solution using get_posts:

$args = array(
  'post_type' => 'videos',

  'tax_query' => array(
    array( // note: tax_query contains an array of arrays. this is not a typo.
      'taxonomy' => 'post_tag',
      'field' => 'slug',
      'terms' => $term_name,
    ),
  ),
);

// Collect an array of posts which are given the "post_tag" which includes $term_name
$posts = get_posts( $args );

if ( $posts ) {
  // Display the first post ID:
  echo $posts[0]->ID;

  // Display all posts with "ID: Title" format
  foreach( $posts as $the_post ) {
    echo $the_post->ID . ': ' . $the_post->post_title . '<br>';
  }
}
Radley Sustaire
  • 3,382
  • 9
  • 37
  • 48