I have the following function to check if the page exists in WordPress by using the path:
private function page_exists( $path ) {
$post_types = apply_filters( 'get_page_by_path_post_types', [ 'page', 'post' ] );
foreach ( $post_types as $pt ) {
if( get_page_by_path( $path, OBJECT, $pt ) !== null ) {
return true;
}
}
return false;
}
The problem is that in multisite the function fails. I searched around but I couldn’t find a Multisite function similar to get_page_by_path
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
get_page_by_path() will only search in the current site.
If you need to find a page anywhere in your Multisite network, you can do something like this.
function network_page_exists( $path ) {
$args = array(
// Max sites to retrieve.
// If you have a large network, increase this.
'number' => 100,
);
$sites = get_sites( $args );
$found = false;
foreach ( $sites as $site ) {
if ( ! $found ) {
switch_to_blog( $site->blog_id );
// Uses your page_exists() function in the sites
// till we find the post, or till we run out of sites.
$found = page_exists( $path );
restore_current_blog();
}
}
return $found;
}
Note: switch_to_blog() can slow your site down if you’ve got a large network. You might want to look into how you can cache your results (perhaps using an option). Since that’s pretty dependent on your specific situation, it’s not addressed in this answer.
References
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0