1

この方法を使用して投稿のすべての画像を取得しようとしています:

$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => $post->ID
);  

$attachments = get_posts( $args );
    if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
            $images[] = wp_get_attachment_image_src( $attachment->ID, ATTACHMENT_IMAGE_SIZE );
        }
        return $images;
    }

残念ながら、これにより、現在の投稿に関連付けられている画像だけでなく、これまでにアップロードされたすべての画像が取得されます。* get_children *を使用してこの投稿を見つけましたが、どちらも機能しません。何か案は?

ps:投稿が作成/更新されたときにコードを実行しています

4

2 に答える 2

4

あなたが試すことができます

<?php 
        $attachments = get_posts( array(
            'post_type' => 'attachment',
            'posts_per_page' => -1,
            'post_parent' => $post->ID,             
        ) );

        if ( $attachments ) {
            foreach ( $attachments as $attachment ) {
                $class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
                $thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
                echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
            }

        }

?>

詳細はこちらをご覧ください

$post->IDが空でないことを確認してください。それでも機能しない場合は、ページ/投稿コンテンツから画像を抽出してみてください。詳細はこちら

于 2012-09-01T20:08:29.970 に答える
1

投稿/ページが作成/更新された後に起動するフックを追加して試してみて、以下に示すfunctions.phpようにその関数内にコードをラップします

add_action( 'save_post', 'after_post_save' );
function after_post_save( $post_id ) {
    if ( 'post' == get_post_type($post_id) ) // check if this is a post
    {
        $args = array(
            'post_type' => 'attachment',
            'numberposts' => -1,
            'post_status' => null,
            'post_parent' => $post_id
        );

        $attachments = get_posts( $args );
        if ( $attachments ) {
            foreach ( $attachments as $attachment ) {
                $images[] = wp_get_attachment_image_src( $attachment->ID, ATTACHMENT_IMAGE_SIZE );
            }
            return $images; // End of function and nothing happens
        }
    }
}

覚えておいてください、基本的には$images、画像で何かをしない限り、関数の最後に配列を返すことによって何もしません。

注:このwp_get_attachment_image_src関数は、次を含む配列を返します

[0] => url // the src of image
[1] => width // the width
[2] => height // the height

したがって、$images配列には次のようなものが含まれます

array(
    [0] => array([0] => url, [1] => width, [2] => height), // first image
    [1] => array([0] => url, [1] => width, 2] => height) // second image
);
于 2012-09-01T20:31:33.000 に答える