Custom Loop in Page Admin Causing Other Fields to Fail

I created a custom loop in the page admin section to manage a custom post type called “widgets” for that page.

$ps_widget_list = get_post_meta( $post_id, 'ps_widget_list', true ); //first get the list of current widgets

$active_widget_array = explode( ', ', $ps_widget_list ); //then separate those widgets into an array of active widgets

// this array is for the UI. It will build a list of all the widgets
// then based on the array of active widgets, will separate them into
// two different arrays to be used later
$widgets_array = array( 

    'active' => array(),
    'inactive' => array()

);

//get all the widgets
$args = array(

    'post_type' => 'ps_widgets',
    'posts_per_page' => '-1'

);

$the_query = new WP_Query( $args );

while ( $the_query->have_posts() ) : $the_query->the_post(); // loop through the widgets

    $widget_id = get_the_ID();

    // if the widget's id is in the array of active widgets
    // mark it as active, if not mark as inactive and store to the array
    $key = ( in_array( $widget_id, $active_widget_array) ) ? 'active' : 'inactive';

    $widgets_array[ $key ][ $widget_id ] = array(

        'id' => $widget_id,
        'title' => get_the_title( $widget_id )

    );

endwhile;
wp_reset_postdata();

The issue arises when I try to add an SEO title, description, or keywords in an an SEO plugin. I tried this on both Yoast and All in One. After disabling different sections of code, I narrowed the issue to this loop. I also tried namespacing the variables too, but no luck. I assume its an issue with the loop being called, any suggestions?

Related posts

Leave a Reply

2 comments

  1. I also encountered side effects with using WP_Query in wordpress admin.

    I used two Wp_Query in a custom metabox, which worked well but i later discovered two strange problems:

    • the slug of the post was automatically set even for the new post
    • featured image was automatically set like the slug and new set featured image wasn’t saved

    After several hours of debugging, I came up with a solution using wp_reset_query();
    However this didn’t completely solved the problem.Still, the featured image wasn’t saving.
    What the ** was wrong?

    Then I came up with this solution. Use native PHP code and Don't mess with WP template tags ie,

    $your_loop= new WP_Query($args);
    

    Instead of

     if( $your_loop->have_posts()){
         while ($your_loop->have_posts()) {
    
            //the_title();
            ...
            //WP loop template tags
         }
     }
    

    use following:

     if( count($your_loop->posts) > 0) {
         foreach( $your_loop->posts as $item_post) {
    
            //$item_post->post_title
            // see other available using print_r($item_post)
            //
         }
     }