您必须编写自定义代码才能获取附件id和post\\u parent byname/ slug 或filename(如果在上载文件期间未更改)。
将以下代码放入主题functions.php 文件
if( ! ( function_exists( \'wp_get_attachment_by_post_name\' ) ) ) {
function wp_get_attachment_by_post_name( $post_name ) {
$args = array(
\'posts_per_page\' => 1,
\'post_type\' => \'attachment\',
\'name\' => trim( $post_name ),
);
$get_attachment = new WP_Query( $args );
if ( ! $get_attachment || ! isset( $get_attachment->posts, $get_attachment->posts[0] ) ) {
return false;
}
return $get_attachment->posts[0];
}
}
然后,您可以在需要的地方调用函数,如下所示:--
$attachment = wp_get_attachment_by_post_name( $post_name );
// Replace post_name by the name/slug of the attachment
// It will give you an object, which you can render like below to get the ID and post_parent
if ( $attachment ) {
echo $attachment->ID; // Gives the id of the attachment
echo $attachment->post_parent; // Gives the post_parent id
echo $attachment->post_title; // Gives the attachment title.
}