0

I get error when i use get_page_by_path() with WP_Query in a php class. I use after_switch_theme and switch_theme in that class. And while the theme is activated then everything is fine as expected. But the problem is, while i switching theme then browser show me an error.

Catchable fatal error: Object of class WP_Query could not be converted to string in C:\wamp\www\wordpress-theme-test\wp-includes\post.php on line 4470

I try to figure out the error `

public function theme_deactivation() {
    $pages = array( 'member-login', 'member-account', 'member-register', 'member-password-lost', 'member-password-reset' );

    foreach ( $pages as $slug ) {
        $query = new WP_Query( 'pagename=' . $slug );

        $page = get_page_by_path( $query );
        wp_delete_post( $page->ID, true );
    }
}

And I think, the main problem is get_page_by_path(). It's first and required parameter is $page_path (string) and WP_Query is an object. And error say WP_Query could not be converted to string (for get_page_by_path())

Is there any way to solve the problem??? Thanks.

1

It doesn't make any sense to try and pass a query result to get_page_by_path(). The point of WP_Query is to query for a selection of posts based on given criteria, while get_page_by_path() is for retrieving a single specific post based on its path. There's no reason you'd need to use them together.

If you want to delete posts based on their slug, then you don't need a query at all:

$pages = array( 'member-login', 'member-account', 'member-register', 'member-password-lost', 'member-password-reset' );

foreach ( $pages as $slug ) {
    $page = get_page_by_path( $slug );

    if ( $page ) {
        wp_delete_post( $page->ID, true );
    }
}
|improve this answer|||||
  • Thanks for your answer. Let me explain why i need to query posts. I need to query posts before delete, if those posts are exist then delete those posts. – Zahid Hossain Jun 8 '19 at 12:59
  • You don't need to query to do that, just check if get_page_by_path() returns a result. I'll update my answer. – Jacob Peattie Jun 8 '19 at 13:08
  • Thank you so much Jacob. – Zahid Hossain Jun 8 '19 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.