List custom post type by custom tax term as page title

admin2025-06-05  3

I have a page called "Developments" and I want to list all the Project posts by the custom tax Project Type using the page title as the term.

This doesn't work:

<?php

$title_slug = sanitize_title(wp_title($sep = ''));

$the_query = new WP_Query( array(
    'post_type' => 'project',
    'tax_query' => array(
        array (
            'taxonomy' => 'project_type',
            'field' => 'slug',
            'terms' => $title_slug,
        )
    ),
) );

while ( $the_query->have_posts() ) :
    $the_query->the_post();
    get_template_part( 'template-parts/content', 'post' );
endwhile;
wp_reset_postdata();

?>

It doesn't work with 'terms' => $title either (hence I tried to define a new variable $title_slug).

If I use 'terms' => 'Developments' it works.

Side question: why does $title_slug = sanitize_title(wp_title($sep = '')); print out the title to display? I am trying to define a variable not echo anything. Answered below

EDIT:

Changing to this format works:

...
$options = array(
    'post_type' => 'project',
    'tax_query' => array(
      array (
          'taxonomy' => 'project_theme',
          'field' => 'slug',
          'terms' => $title_slug,
      )
    ),
);

$the_query = new WP_Query( $options );
...

But I still don't understand why the original is failing to list posts.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749082264a316208.html

最新回复(0)