当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Display content from two different custom post types

问题描述:

I want to loop through two different custom post types to find out what should be displayed. In CPT project I want to now the name of the house, in CPT portfolio I want to know the category. If these two are the same, I want a certain content from the project CPT to be shown.

On this page you're on the single-portfolio.php.

The code below have two errors (at least) the first one is that all the projects house types ($houseType) displays for no reason and the second one is that the content within the second loop doesn't display at all.

So, to try to make this a bit more clear:

I want to display the name and the city of the project which house type name matches the portfolio category (which is the name of the house type)

 $args = array('post_type' => 'project');

$my_query = new WP_Query( $args );

if( $my_query->have_posts()) while ($my_query->have_posts()) : $my_query->the_post();

$houseType = the_field('hustyp');

$argsPort = array(

'post_type' => 'portfolio',

'tax_query' => array(

array(

'taxonomy' => 'portfolio_category',

'field' => 'slug', //can be set to ID

'terms' => $houseType

)));

$port_query = new WP_Query($argsPort);

if( $port_query->have_posts()) while ($port_query->have_posts()) : $port_query->the_post(); ?>

<tr>

<td><?php the_field('brf')?>/<a href="<?php the_permalink(); ?>"><?php the_field('ort')?></a></td>

</tr>

<?php

endwhile;

?>

<?php

endwhile;

I don't know if the best way to go is by creating an own query or something like that.

Any ideas?

UPDATE

Okay, I made some progress and finally realized that the_field displays the field and therefor I should use get_field. But I still don't know how to compare the two different post types to see if it is a match, and after that display only the matches. I'm thinking that creating an array can be a solution, but don't know how to go forward. As you can see in my new code below.

New code:

 $args = array(

'post_type' => array( 'portfolio', 'project' ));

$my_query = new WP_Query( $args );

if( $my_query->have_posts()) {

while ($my_query->have_posts()) : $my_query->the_post();

//Returns All Term Items for "my_taxonomy"

$term_list_portfolio = wp_get_post_terms($post->ID, 'portfolio_category', array("fields" => "all"));

// Just get the category

$category = $term_list[0]->name;

// Get the house type

$houseType = get_field('hustyp');

$result = array($term_list[0]->name, get_field('hustyp'));

print_r($result);

if($category == $houseType) { ?>

<tr>

<td><?php the_field('brf')?><?php the_field('ort') ?>

<?php }

endwhile;

}

网友答案:

Try to reset query <?php wp_reset_query(); ?> before second wp_query reffer

分享给朋友:
您可能感兴趣的文章:
随机阅读: