0

Need to pull custom post type's titles and id's inside functions.php Following code is working fine if used in page template. But doesn't return anything inside a functions.php

<select name="feat_pop" value="<?php echo $feat_pop; ?>">
    <option value="none">None</option>
    <?php
        global $post;
        $popargs = array(                        
                            'posts_per_page' => -1, 
            'post_type' => 'popups'
        );
            $newpop = new WP_Query( $popargs );
        if ( have_posts() ) while ($newpop->have_posts()) : $newpop->the_post();
    ?>
            <option value=""><?php the_title();?></option>
    <?php
        endwhile; 
        wp_reset_postdata();
    ?>
</select>

The only error in error logs- "Got error 'PHP message: PHP Parse error: syntax error, unexpected end of file" But there is nothing at specified line.

Bileberda
  • 17
  • 5

1 Answers1

1

It looks like you're conflating the methods for the have_posts of your code. You should be running that method on your WP_Query(). You also shouldn't need to instantiate the global $post variable here. Lastly, you don't appear to actually be pulling the ID into your output anywhere? I assume you want it as the value - Try this:

<select name="feat_pop" value="<?php echo $feat_pop; ?>">
    <option value="none">None</option>
    <?php
        $popargs = array(                        
            'posts_per_page' => -1, 
            'post_type'      => 'popups'
        );

        $newpop = new WP_Query( $popargs );

        if( $newpop->have_posts() ){
            while( $newpop->have_posts() ){
                $newpop->the_post();                    
                echo '<option value="'. get_the_ID() .'">'. get_the_title() .'</option>';
            }
        }

        wp_reset_postdata();
    ?>
</select>
Xhynk
  • 12,250
  • 8
  • 29
  • 61
  • The `if` statement is not necessary `if( $newpop->have_posts() )` before `while( $newpop->have_posts() ){` if `$newpop->have_posts()` is false the loop doesn't execute (either way). – ArtisticPhoenix Dec 28 '18 at 23:07
  • It's not strictly necessary, no - but it's arguably standard practice for WP Queries to more easily catch scenarios that can return no posts to allow you to more easily display a message like "No posts found :(" that to the end user in an `else` statement – Xhynk Dec 28 '18 at 23:22
  • True, well time for me to book it home... – ArtisticPhoenix Dec 28 '18 at 23:25