【发布时间】:2020-04-20 09:32:25
【问题描述】:
我想从 slug 获取页面 ID。我使用了函数
$page = get_page_by_path("page-slug", OBJECT, 'page');
但它返回媒体附件而不是页面。我只想要页面而不是任何其他帖子类型。
【问题讨论】:
我想从 slug 获取页面 ID。我使用了函数
$page = get_page_by_path("page-slug", OBJECT, 'page');
但它返回媒体附件而不是页面。我只想要页面而不是任何其他帖子类型。
【问题讨论】:
试试这个功能
function get_id_by_slug($page_slug) {
// $page_slug = "parent-page"; in case of parent page
// $page_slug = "parent-page/sub-page"; in case of inner page
$page = get_page_by_path($page_slug);
if ($page) {
return $page->ID;
} else {
return null;
}
}
【讨论】:
为避免获取附件,请将仅包含“页面”的数组作为第三个参数传递,如下所示:
$page = get_page_by_path( "page-slug", OBJECT, array( 'page' ) );
我在https://developer.wordpress.org/reference/functions/get_page_by_path/#comment-3046看到这个
【讨论】:
给你! 引用自:https://gist.github.com/matheuseduardo/11f258d0895dec5885c8
/**
* Retrieve a page given its slug.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $page_slug Page slug
* @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
* Default OBJECT.
* @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
* @return WP_Post|null WP_Post on success or null on failure
*/
function get_page_by_slug( $page_slug, $output = OBJECT, $post_type = 'page' ) {
global $wpdb;
if ( is_array( $post_type ) ) {
$post_type = esc_sql( $post_type );
$post_type_in_string = "'" . implode( "','", $post_type ) . "'";
$sql = $wpdb->prepare( "
SELECT ID
FROM $wpdb->posts
WHERE post_name = %s
AND post_type IN ($post_type_in_string)
", $page_slug );
} else {
$sql = $wpdb->prepare( "
SELECT ID
FROM $wpdb->posts
WHERE post_name = %s
AND post_type = %s
", $page_slug, $post_type );
}
$page = $wpdb->get_var( $sql );
if ( $page )
return get_post( $page, $output );
return null;
}
现在get_post 函数将返回一个数组对象。所以你可以从参数中选择:
WP_Post Object
(
[ID] =>
[post_author] =>
[post_date] =>
[post_date_gmt] =>
[post_content] =>
[post_title] =>
[post_excerpt] =>
[post_status] =>
[comment_status] =>
[ping_status] =>
[post_password] =>
[post_name] =>
[to_ping] =>
[pinged] =>
[post_modified] =>
[post_modified_gmt] =>
[post_content_filtered] =>
[post_parent] =>
[guid] =>
[menu_order] =>
[post_type] =>
[post_mime_type] =>
[comment_count] =>
[filter] =>
)
因此,您可以使用模板文件中的函数从 slug 中仅检索 ID:
$post_obj = get_page_by_slug('this-is-my-slug', OBJECT, 'post') // <-- change the posttype
$post_id = $post_obj->ID;
echo $post_id; //id
echo $post_obj->ID; // id
// Or other things:
echo $post_obj->post_title; //Post Title
echo $post_obj->post_content; // Post Content
或者想要备用输出?使用 ARRAY_A。
$post_obj = get_page_by_slug('this-is-my-slug', ARRAY_A, 'post' );
$post_id= $post_obj['ID'];
echo $post_id; //id
echo $post_obj['ID']; // id
// Or other things:
echo $post_obj['post_title']; //Post Title
echo $post_obj['post_content']; // Post Content
【讨论】: