代码之家  ›  专栏  ›  技术社区  ›  Jeaf Gilbert

如何从permalink(漂亮的url)获取post id?

  •  35
  • Jeaf Gilbert  · 技术社区  · 14 年前

    如何从permalink(漂亮的url)获取post id?

    6 回复  |  直到 14 年前
        1
  •  54
  •   Argalatyr Rodrigo    10 年前

    你应该没事的 url_to_postid() see documentation ]位于rewrite.php中。我去年在我的一个插件里用过,很有魅力。

        2
  •  9
  •   deweydb topchef    13 年前

    This url_to_postid() 只适用于普通岗位。

        3
  •  9
  •   mems    12 年前

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

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

    根据给定的路径检索页。

    在哪里? $page_path

    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');
    
        4
  •  2
  •   Hariprasad jasmine sharma    11 年前

    url_to_postid() 截至 3.7.0 #19744 , #25659 ).

        5
  •  0
  •   jovaniwayne    11 年前

    你也可以试试这个:

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

        6
  •  0
  •   Sulthan Allaudeen    10 年前

    请使用

      $postid = url_to_postid( $url );
    

    检索附件的ID。

    example.com/?attachment_id=N 并且不会使用完整的URL从完整的URL获取id。

        7
  •  0
  •   khandaniel    6 年前

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