自定义帖子类型错误

时间:2014-07-28 08:26:32

标签: php wordpress

我正在使用这段代码在wordpress中以自定义帖子类型提取汽车和汽车细节。

<h1>Cars for Sale</h1>
<?php $args = array( 'post_type' => 'carlistings', 'posts_per_page' => 10 ); ?>
<ul id="carsforsale">
    <?php $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post(); ?>
            <?php $cardetails = get_post_meta( $post->ID, 'cardetails', true );
            foreach( $cardetails as $cardetails ) { ?> <!-- Line # 13 -->
        <li class="pop"><span>
            <span class="thumb"><a href="<?php the_permalink(); ?>"><?php if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } ?></a></span>
            <span class="title"><h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3></span>
            <strong>Make</strong> <?php echo $cardetails['make'] ?><br />
            <strong>Model</strong> <?php echo $cardetails['model'] ?><br />
            <strong>Year</strong> <?php echo $cardetails['year'] ?><br />
            <strong>Color:</strong> <?php echo $cardetails['color'] ?><br />
            <strong>Price:</strong> <?php echo $cardetails['price'] ?><br />
        </span></li>
<?php } ?>
<?php wp_reset_query(); ?>

我遇到的问题是,在3次进入后我收到此错误消息

  

警告:在第13行的/home/styleaut/public_html/wp-content/themes/styleautosales/page-30.php中为foreach()提供的参数无效

第13行落在代码的这一部分:

foreach( $cardetails as $cardetails ) {

3 个答案:

答案 0 :(得分:1)

在foreach之前添加if语句,如下所示:

<h1>Cars for Sale</h1>
<?php $args = array( 'post_type' => 'carlistings', 'posts_per_page' => 10 ); ?>
<ul id="carsforsale">
    <?php $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post(); ?>
            <?php $cardetails = get_post_meta( $post->ID, 'cardetails', true );
            if($cardetails) {
            foreach( $cardetails as $cardetails ) { ?>
        <li class="pop"><span>
            <span class="thumb"><a href="<?php the_permalink(); ?>"><?php if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } ?></a></span>
            <span class="title"><h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3></span>
            <strong>Make</strong> <?php echo $cardetails['make'] ?><br />
            <strong>Model</strong> <?php echo $cardetails['model'] ?><br />
            <strong>Year</strong> <?php echo $cardetails['year'] ?><br />
            <strong>Color:</strong> <?php echo $cardetails['color'] ?><br />
            <strong>Price:</strong> <?php echo $cardetails['price'] ?><br />
        </span></li>
<?php } // end foreach
} // end if ?>
<?php wp_reset_query(); ?>

答案 1 :(得分:0)

我认为您的问题就是您拨打get_post_meta的方式。通过将last参数设置为true,它将返回post meta的第一行中的值,该值始终为字符串。尝试调用不带该参数的函数。

答案 2 :(得分:-1)

更改

foreach( $cardetails as $cardetails ) {

foreach( $cardetails as $value ) {

并且您需要将foreach主体中的所有$ cardetails变量用法更改为$ value,f.e。:

$cardetails['make']

需要更改为:

$value['make']

$cardetails['model'] to $value['model']

依旧......