如何从永久链接获取帖子ID(漂亮的网址)?

时间:2010-11-02 05:12:04

标签: wordpress permalinks

如何从永久链接获取帖子ID(漂亮的网址)?

7 个答案:

答案 0 :(得分:50)

你应该可以使用位于rewrite.php中的url_to_postid() [see documentation]。去年我在我的插件中使用它,就像一个魅力。

答案 1 :(得分:9)

This适用于常规帖子类型和自定义帖子类型。 url_to_postid()仅适用于常规帖子。

答案 2 :(得分:8)

我有一个专门的(和记录的)功能:

get_page_by_path( $page_path, $output, $post_type );
  

检索给定其路径的页面。

$page_path

的位置
  

[...]相当于'pagename'查询,如:'index.php?pagename = parent-page / sub-page'。

请参阅Function Reference/get page by path

示例:

// Assume 'my_permalink' is a post.
// But all types are supported: post, page, attachment, custom post type, etc.
// See http://codex.wordpress.org/Post_Types
get_page_by_path('my_permalink', OBJECT, 'post');

答案 3 :(得分:1)

截至url_to_postid()

3.7.0:此功能现在支持自定义帖子类型(请参阅Trac票证#19744#25659)。

答案 4 :(得分:0)

你也可以尝试这个:

$post = get_page_by_path('cat',OBJECT,'animal'); 

猫是你正在寻找的那个=永久链接;动物是自定义帖子类型,

答案 5 :(得分:0)

请使用

  $postid = url_to_postid( $url );

以检索附件的ID。

要求提供的网址格式为example.com/?attachment_id=N,并且无法使用完整网址从完整网址获取ID。

答案 6 :(得分:0)

我有一个多站点WP,因此一旦出于某些原因在某些博客url_to_postid()中工作时浏览博客,而在其他相同类型的博客中,get_page_by_path()则不会魅力。所以我是这样做的,虽然可能并不完美:

$parsed_url = wp_parse_url( $url ); // Parse URL
$slug = substr($parsed_url['path'], 1 ); // Trim slash in the beginning

$post_id = url_to_postid( $slug ); // Attempt to get post ID

if ( ! $post_id ) { // If it didn't work try to get it manually from DB
    $post_query_result = 
        $wpdb->get_row("SELECT ID FROM {$wpdb->prefix}posts WHERE post_name = '{$slug}'");
    $analog_id = (int) $post_query_result->ID;
}
相关问题