Support » Fixing WordPress » Display two posts when it should display one post

  • Resolved dfwgreg

    (@dfwgreg)


    Hi everyone,
    I have a section on my website that displays announcements and I’m having problems properly displaying it.

    So far, I have two posts in the custom_post called brknews. Those posts can be viewed by a metabox that adds a custom field called ‘breaking’ and ‘on’.

    When they are turned off, it does not add any custom field.

    This is the code:

    <?php $the_query = new WP_Query( 'post_type=brknews' ); ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <?php if (post_custom('breaking')) { ?>
    <?php the_title();?>
    <?php } else; { ?>
    none
    <?php } ?>
    <?php?>
    <?php endwhile; ?>
    <?php wp_reset_query(); ?>

    The problem is I want it to display none but it display none twice, exactly the number of posts that are in the ‘brknews’ section.

    How do I fix the problem to show none one time, regardless on the number of posts?

    Thanks,
    Gregory S.

Viewing 7 replies - 1 through 7 (of 7 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    Try it with this (not tested):

    if (get_post_meta($post->ID, 'breaking', true) == 'on') {
    the_title();
    } else {
    echo 'none';
    }

    Nope, still shows two none

    Moderator keesiemeijer

    (@keesiemeijer)

    Is it because both posts in “brknews” don’t have the custom field “breaking”?

    Try it with this in stead of a normal loop (also not tested):

    <?php
    $breaking_posts = get_posts('post_type=brknews');
    $breaking_post_titles = array();
    if(!empty($breaking_posts)) {
    	foreach ( $breaking_posts as $breaking_post  ) {
    		setup_postdata($breaking_post);
    		if (get_post_meta($breaking_post->ID, 'breaking', true) == 'on') {
    			$breaking_post_titles[] = $breaking_post->post_title;
    		}
    	}
    }
    
    if(!empty($breaking_post_titles)){
    	foreach ( $breaking_post_titles as $breaking_post_title ) {
    		echo $breaking_post_title;
    	}
    } else {
     echo 'none';
    }
    ?>

    try this:

    <?php
    $the_query = new WP_Query( 'post_type=brknews' );
    $_count = 0;
    while ( $the_query->have_posts() ) : $the_query->the_post();
    if (post_custom('breaking')) {
    the_title();
    ++$_count;
    }
    endwhile;
    if ( ! $_count ) {
    echo 'None';
    }
    wp_reset_query();
    ?>

    Both worked! Thanks!

    One more question. How do I change post custom to a taxonomy?

    Thanks everyone for the help,
    Gregory S.

    Nevermind. Got it to work!

    <?php	$the_query = new WP_Query( array( 'brknewsitem' => 'activate','post_type'=>'brknews' ) ); $_count = 0; while ( $the_query->have_posts() ) : $the_query->the_post(); { ?>

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Display two posts when it should display one post’ is closed to new replies.