wp_copy_parent_attachment_properties()


WordPressのwp_copy_parent_attachment_properties()関数は、親投稿の添付ファイルのプロパティを子投稿にコピーするために使用されます。この関数は、特にメディアファイルのメタデータを一貫して維持する場合に役立ちます。

構文

wp_copy_parent_attachment_properties( int $child_id, int $parent_id );

引数の説明:

  • $child_id(int) — 子投稿のID。
  • $parent_id(int) — 親投稿のID。

例1: 基本的な使用法

親投稿の添付ファイルのプロパティを子投稿にコピーします。

wp_copy_parent_attachment_properties( get_the_ID(), wp_get_post_parent_id( get_the_ID() ) );

例2: 特定の投稿IDを使用

特定の親投稿と子投稿のIDを指定してプロパティをコピーします。

wp_copy_parent_attachment_properties( 456, 123 );

例3: カスタムクエリで使用

カスタムクエリで取得した投稿に対してプロパティをコピーします。

$child_post = get_post( 789 ); wp_copy_parent_attachment_properties( $child_post->ID, $child_post->post_parent );

例4: ループ内での使用

ループ内で各子投稿のプロパティを親投稿からコピーします。

if ( have_posts() ) { while ( have_posts() ) { the_post(); wp_copy_parent_attachment_properties( get_the_ID(), wp_get_post_parent_id( get_the_ID() ) ); } }

例5: メディアファイルの一括更新

特定の親投稿に紐づくすべての子投稿のメディアプロパティを更新します。

$children = get_children( array( 'post_parent' => 123 ) ); foreach ( $children as $child ) { wp_copy_parent_attachment_properties( $child->ID, 123 ); }

例6: プラグイン内での使用

プラグイン内でこの関数を使用して、メディアプロパティを自動的に同期します。

add_action( 'save_post', function( $post_id ) { if ( wp_is_post_revision( $post_id ) ) return; wp_copy_parent_attachment_properties( $post_id, wp_get_post_parent_id( $post_id ) ); } );

例7: カスタムフィールドとの連携

カスタムフィールドを使用して親投稿を指定し、プロパティをコピーします。

$parent_id = get_post_meta( get_the_ID(), 'custom_parent_id', true ); if ( $parent_id ) { wp_copy_parent_attachment_properties( get_the_ID(), $parent_id ); }

例8: エラーハンドリング

関数の実行結果をチェックして、エラーハンドリングを行います。

$result = wp_copy_parent_attachment_properties( get_the_ID(), wp_get_post_parent_id( get_the_ID() ) ); if ( is_wp_error( $result ) ) { error_log( $result->get_error_message() ); }

注意点

  • この関数は、親投稿と子投稿の両方が存在する場合にのみ動作します。
  • メディアファイルのプロパティが正しくコピーされるためには、適切な権限が必要です。

関連機能: