I have the following issue:

I am creating a custom-meta-box for the user to add custom fields in a friendly way.
I want to generate a drop-down box with all posts that fall under category 10.
I have created a loop inside the functions file for retrieving the posts I want and to create a dropdown select list.

So when I go to admin -> posts and select a post to edit, I get the following issue:
the last post will load no matter which one I select.

Here is the code used inside the functions file and then called when generating the html code for the custom meta-box:

function get_project_ids($proj_cat = 10) {

$output="";

$catt = get_categories('parent=".$proj_cat."&hide_empty=0');

    foreach ($catt as $c) :

        $output .= '<optgroup label="'.$c->name.'">';
        $d = get_categories('parent=".$c->cat_ID."&hide_empty=0');

            foreach ($d as $e) :
            $output .= '<optgroup label="'.$e->name.'">';

                $args = array( 'nopaging' => true, 'cat' => $e->cat_ID );
                $project_query = new WP_Query( $args );

                    while ( $wp_query->have_posts() ) : $wp_query->the_post();
                        $project_id = (get_post_meta($post->ID, 'project_code', true) != "")?get_post_meta($post->ID, 'project_code', true):"";
                        $output .= '<option value="'.$post->ID.'">'.$project_id.'-'.get_the_title().'</option>';    
                    endwhile; 

                wp_reset_postdata();
                $wp_query = null;
                $wp_query = $original_query;

            $output .= '</optgroup> <!-- END level-b -->';
        endforeach;

        $output .= '</optgroup> <!-- END level-a -->';
    endforeach;

return $output;

4 Answers
4

I am not sure about the issue, but my advice would be to try and refactor this to use get_posts() and template tags that can work without $post global variable. Basically do not touch globals at all.

Loops in front-end are almost civilized nowadays, but internals of admin are still very wild. 🙂

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *