我有问题。我希望在帖子发布时获得精选图片网址。
它在我更新帖子时起作用,但在第一次发布时却不起作用,因为此时元数据似乎不会存储在数据库中。即使我使用' wp_insert_post'而不是' save_post'它不起作用。
在我的functions.php中,我用以下内容检查新的/更新的帖子:
add_action( 'save_post', 'my_function' );
当帖子更新后,我使用以下方式阅读精选图片网址
$image_url = get_post_meta( get_post_meta( $post_id, "_thumbnail_id", true ), "_wp_attached_file", true );
你能帮助我吗?
答案 0 :(得分:1)
答案 1 :(得分:0)
save_post
动作挂钩运行,因此应该这样做,它适用于发布后和更新后。代码中注释了几个有用的链接。
// http://codex.wordpress.org/Plugin_API/Action_Reference/save_post
add_action( 'save_post', function ( $post_id ) {
if ( wp_is_post_revision( $post_id ) ) return;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// save_post action is executed on all post actions like publish, trash, auto-draft, etc.
// http://codex.wordpress.org/Post_Status_Transitions
if ( get_post_status( $post_id ) == 'publish' ) {
// http://codex.wordpress.org/Function_Reference/get_post_thumbnail_id
$thumb_id = get_post_thumbnail_id( $post_id );
// http://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src
$thumb_url = wp_get_attachment_image_src( $thumb_id, 'full' );
$thumb_url = $thumb_url ? $thumb_url[0] : false;
}
});