How to get list of posts from permalinks?

I am using an API which tracks metrics on parts of my site. The only useful bit it saves though is the URL (permalink).

What is the most efficient way to query up all the posts that match those permalinks, given the fact that I don't have access to the ID's to use post__in with WP_Query.

Topic loop wp-query permalinks query Wordpress

Category Web


There are several ways to achieve this, depending on the permalink structure of your posts. Assuming the post slug is part of the permalink structure, you can get the post slug from the post URL and fetch the corresponding post by using WP_Query with the name-parameter. Let's assume the structure of the URLs is http://example.com/{post_slug}/. We can fetch the slug by using parse_url and query the posts with that slug:

$url = 'http://example.com/my-post/';

$path = parse_url( $url, PHP_URL_PATH ); // Get URL path from URL
$slug = trim( $path, '/' ); // Trim slashes

$posts_query = new WP_Query( array(
    'name' => $slug
) );

if ( $posts_query->have_posts() ) {
    $postid = $posts_query->posts[0]->ID;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.