admin管理员组

文章数量:1122846

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.

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.

Share Improve this question asked May 30, 2014 at 4:27 TallboyTallboy 2278 silver badges17 bronze badges 3
  • You can query posts based on the permalink slug using name parameter. – Abhik Commented May 30, 2014 at 5:39
  • can you show me an example which accepts input as an array of slugs? like ['hello-world', 'post-2', 'welcome-post'], I'm not sure what you mean – Tallboy Commented May 30, 2014 at 15:14
  • It doesn't accept any array, you need to pass a valid slug to it to query for that post. codex.wordpress.org/Class_Reference/… – Abhik Commented May 31, 2014 at 17:26
Add a comment  | 

1 Answer 1

Reset to default 0

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;
}

本文标签: wp queryHow to get list of posts from permalinks