Получить id поста wordpress php

url_to_postid() │ WP 1.0.0

Получает ID записи (поста, страницы) по переданному УРЛ. Разбирает переданную «постоянную ссылку» и по ней пытается получить ID записи. Функция сначала проверят содержит ли УРЛ ID данные, если не содержит, функция проводит углубленную проверку: пытается найти ID используя правила перезаписи.

Если использовать url_to_postid(), чтобы получить ID вложения (attachment, картинки), нужно чтобы УРЛ был такого формата: example.com/?attachment_id=N , если передать ссылку на картинку, то ID определить не получится. Чтобы определить ID по ссылке, можно использовать такой код:

// получает attachment ID по URL на файл function pippin_get_image_id( $image_url ) < global $wpdb; $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); return $attachment[0]; >

Это не самый быстрый код, т.к. поле guid не содержит индексов в базе данных, поэтому при поиске запрос проверит все поля guid а их может быть очень много . С версии 4.0 появилась специальная функция по которой можно получить ID вложения указав ссылку на вложение: attachment_url_to_postid()

Хуки из функции

Возвращает

Использование

$postid = url_to_postid( $url );

Примеры

#1 Пример использования. Получим ID поста из постоянной ссылки:

$url = "http://example.com/our-company/news/dinner-tcworld-2010.html"; $post_ID = url_to_postid($url); echo "ID поста example_37300" > 
0

#2 Демонстрация работы функции

var_dump( url_to_postid( 'https://wp-kama.ru/function/url_to_postid' ) ); // int(733) var_dump( url_to_postid( '/function/url_to_postid' ) ); // int(733) var_dump( url_to_postid( 'https://wp-kama.ru/id_15476/dopolnitelnye-polya-dlya-wp_nav_menu.html' ) ); // int(15476) var_dump( url_to_postid( '/id_15476/dopolnitelnye-polya-dlya-wp_nav_menu.html' ) ); // int(15476)

Заметки

  • Global. WP_Rewrite. $wp_rewrite WordPress rewrite component.
  • Global. WP. $wp Current WordPress environment instance.

Список изменений

Код url_to_postid() url to postid WP 6.2.2

function url_to_postid( $url ) < global $wp_rewrite; /** * Filters the URL to derive the post ID from. * * @since 2.2.0 * * @param string $url The URL to derive the post ID from. */ $url = apply_filters( 'url_to_postid', $url ); $url_host = parse_url( $url, PHP_URL_HOST ); if ( is_string( $url_host ) ) < $url_host = str_replace( 'www.', '', $url_host ); >else < $url_host = ''; >$home_url_host = parse_url( home_url(), PHP_URL_HOST ); if ( is_string( $home_url_host ) ) < $home_url_host = str_replace( 'www.', '', $home_url_host ); >else < $home_url_host = ''; >// Bail early if the URL does not belong to this site. if ( $url_host && $url_host !== $home_url_host ) < return 0; >// First, check to see if there is a 'p=N' or 'page_id=N' to match against. if ( preg_match( '#[?&](p|page_id|attachment_id)=(\d+)#', $url, $values ) ) < $id = absint( $values[2] ); if ( $id ) < return $id; >> // Get rid of the #anchor. $url_split = explode( '#', $url ); $url = $url_split[0]; // Get rid of URL ?query=string. $url_split = explode( '?', $url ); $url = $url_split[0]; // Set the correct URL scheme. $scheme = parse_url( home_url(), PHP_URL_SCHEME ); $url = set_url_scheme( $url, $scheme ); // Add 'www.' if it is absent and should be there. if ( false !== strpos( home_url(), '://www.' ) && false === strpos( $url, '://www.' ) ) < $url = str_replace( '://', '://www.', $url ); >// Strip 'www.' if it is present and shouldn't be. if ( false === strpos( home_url(), '://www.' ) ) < $url = str_replace( '://www.', '://', $url ); >if ( trim( $url, '/' ) === home_url() && 'page' === get_option( 'show_on_front' ) ) < $page_on_front = get_option( 'page_on_front' ); if ( $page_on_front && get_post( $page_on_front ) instanceof WP_Post ) < return (int) $page_on_front; >> // Check to see if we are using rewrite rules. $rewrite = $wp_rewrite->wp_rewrite_rules(); // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options. if ( empty( $rewrite ) ) < return 0; >// Strip 'index.php/' if we're not using path info permalinks. if ( ! $wp_rewrite->using_index_permalinks() ) < $url = str_replace( $wp_rewrite->index . '/', '', $url ); > if ( false !== strpos( trailingslashit( $url ), home_url( '/' ) ) ) < // Chop off http://domain.com/[path]. $url = str_replace( home_url(), '', $url ); >else < // Chop off /path/to/blog. $home_path = parse_url( home_url( '/' ) ); $home_path = isset( $home_path['path'] ) ? $home_path['path'] : ''; $url = preg_replace( sprintf( '#^%s#', preg_quote( $home_path ) ), '', trailingslashit( $url ) ); >// Trim leading and lagging slashes. $url = trim( $url, '/' ); $request = $url; $post_type_query_vars = array(); foreach ( get_post_types( array(), 'objects' ) as $post_type => $t ) < if ( ! empty( $t->query_var ) ) < $post_type_query_vars[ $t->query_var ] = $post_type; > > // Look for matches. $request_match = $request; foreach ( (array) $rewrite as $match => $query ) < // If the requesting file is the anchor of the match, // prepend it to the path info. if ( ! empty( $url ) && ( $url != $request ) && ( strpos( $match, $url ) === 0 ) ) < $request_match = $url . '/' . $request; >if ( preg_match( "#^$match#", $request_match, $matches ) ) < if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[(4+)\]/', $query, $varmatch ) ) < // This is a verbose page match, let's check to be sure about it. $page = get_page_by_path( $matches[ $varmatch[1] ] ); if ( ! $page ) < continue; >$post_status_obj = get_post_status_object( $page->post_status ); if ( ! $post_status_obj->public && ! $post_status_obj->protected && ! $post_status_obj->private && $post_status_obj->exclude_from_search ) < continue; >> // Got a match. // Trim the query of everything up to the '?'. $query = preg_replace( '!^.+\?!', '', $query ); // Substitute the substring matches into the query. $query = addslashes( WP_MatchesMapRegex::apply( $query, $matches ) ); // Filter out non-public query vars. global $wp; parse_str( $query, $query_vars ); $query = array(); foreach ( (array) $query_vars as $key => $value ) < if ( in_array( (string) $key, $wp->public_query_vars, true ) ) < $query[ $key ] = $value; if ( isset( $post_type_query_vars[ $key ] ) ) < $query['post_type'] = $post_type_query_vars[ $key ]; $query['name'] = $value; >> > // Resolve conflicts between posts with numeric slugs and date archive queries. $query = wp_resolve_numeric_slug_conflicts( $query ); // Do the query. $query = new WP_Query( $query ); if ( ! empty( $query->posts ) && $query->is_singular ) < return $query->post->ID; > else < return 0; >> > return 0; >

Cвязанные функции

URL (УРЛ Ссылка)

  • admin_url()
  • attachment_url_to_postid()
  • build_query()
  • comment_link()
  • content_url()
  • get_comments_link()
  • get_comments_pagenum_link()
  • get_edit_post_link()
  • get_edit_term_link()
  • get_home_url()
  • get_next_comments_link()
  • get_next_posts_page_link()
  • get_page_link()
  • get_post_embed_url()
  • get_post_permalink()
  • get_post_type_archive_link()
  • get_previous_posts_page_link()
  • get_privacy_policy_url()
  • get_rest_url()
  • get_search_link()
  • get_stylesheet_directory_uri()
  • get_stylesheet_uri()
  • get_theme_root_uri()
  • get_year_link()
  • home_url()
  • includes_url()
  • network_admin_url()
  • network_home_url()
  • plugin_dir_url()
  • plugins_url()
  • site_url()
  • strip_fragment_from_url()
  • the_post_thumbnail_url()
  • wc_get_cart_url()
  • wp_extract_urls()
  • wp_get_attachment_image_url()
  • wp_get_upload_dir()
  • wp_make_link_relative()
  • wp_parse_url()
  • wp_registration_url()
  • wp_upload_dir()
  • wp_validate_redirect()

Остальное

  • comments_open()
  • get_extended()
  • get_lastpostdate()
  • get_lastpostmodified()
  • get_post_embed_html()
  • get_post_parent()
  • get_post_stati()
  • get_post_status_object()
  • get_post_statuses()
  • get_post_timestamp()
  • has_post_parent()
  • is_sticky()
  • pings_open()
  • post_exists()
  • sanitize_post()
  • the_shortlink()
  • wp_embed_register_handler()
  • WP_Embed::delete_oembed_caches()
  • wp_get_canonical_url()
  • wp_get_shortlink()
  • wp_oembed_add_provider()
  • wp_transition_post_status()

Источник

get_the_ID() │ WP 2.1.0

ID поста в цикле можно получить еще через $post->ID , так зачастую проще - нет лишних обращений к функциям.

Возвращает

Использование

Примеры

#1 Выведем на экран произвольное поле поста с использованием функции get_the_ID():

$post_id = get_the_ID(); echo get_post_meta( $post_id, 'meta_key', 1); // или можно так: echo get_post_meta( get_the_ID(), 'meta_key', 1);

#2 Получим ID записи

Обычно ID поста внутри цикла можно получить через $post->ID , но в некоторых случаях может пригодится получать его так:

$post_id = get_the_ID(); // $post_id будет содержать ID текущего в цикле поста

Список изменений

Код get_the_ID() get the ID WP 6.2.2

function get_the_ID() < // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid $post = get_post(); return ! empty( $post ) ? $post->ID : false; >

Cвязанные функции

loop (Цикл WP)

  • get_the_author()
  • get_the_author_link()
  • get_the_content()
  • get_the_excerpt()
  • get_the_tag_list()
  • get_the_tags()
  • setup_postdata()
  • the_author()
  • the_content()
  • the_date()
  • the_excerpt()
  • the_ID()
  • the_permalink()
  • the_post()
  • the_tags()
  • the_time()

Записи: посты, страницы, .

  • edit_post_link()
  • get_delete_post_link()
  • get_edit_post_link()
  • get_permalink()
  • get_post_field()
  • get_post_status()
  • get_post_time()
  • get_sample_permalink()
  • get_the_date()
  • get_the_modified_date()
  • get_the_modified_time()
  • get_the_permalink()
  • get_the_time()
  • get_the_title()
  • get_the_title_rss()
  • has_excerpt()
  • post_password_required()
  • register_post_status()
  • single_post_title()
  • the_excerpt_rss()
  • the_modified_date()
  • the_title()
  • the_title_attribute()

Источник

Читайте также:  Redirect 301 всех index php
Оцените статью