在WordPress中更改媒体元数据

时间:2016-12-08 05:15:20

标签: php wordpress

我需要更改媒体项的元数据值(例如,'标题'值)。这可以通过媒体页面手动完成,但我需要通过一个函数来完成。

我正在使用此代码,该代码能够读取元数据,但无法将新值更改/写入“标题”。字段。

几个' print_r'这样你就可以看到

之前和之后的值
function ml_change_media_data() {
    // assumes that the 'caption' for the picture contains text (via media edit screen)
    // set up the test media ID number and other items
    global $post;
    $post_id = 620; // hardcoded for now; change for your testing
    $caption_new = "this is new caption";

    // read the current media meta data
        $data = wp_get_attachment_metadata($post_id, $unfiltered);
// this shows that the existing 'caption' is an empty array element
echo "data before change <pre>";print_r($data);echo "</pre><hr>";

    // this function gets the actual caption element (matches what we see in edit screen)
    $pix_meta = wp_prepare_attachment_for_js( $post_id);
    // shows the real caption value
echo "pix_meta via prepare function <pre>";print_r($pix_meta);echo "</pre><hr>";

    // change the caption element  to the $caption_new value
    $pix_meta[caption] = $caption_new;
echo "pix_meta after changing caption element <pre>";print_r($pix_meta);echo "</pre><hr>";

    // write the media meta data
    wp_update_attachment_metadata( $post_id, $pix_meta );   

    // read the metadata again
    $pix_meta_now = wp_prepare_attachment_for_js( $post_id);

    // this next should show the new caption value, but the caption has NOT changed 
echo "pix_meta_now after change - did it change ? <pre>";print_r($pix_meta_now);echo "</pre><hr>";
    die();
    return;
}

查看“媒体”页面中的媒体项目,标题未更改。

请注意&#39; wp_get_attachment_metadata&#39; function返回一个包含&#39;标题&#39;的数组。元素,但该元素是空白的;它与媒体屏幕上显示的标题不匹配。

以下是&#39; wp_get_attachment_metadata&#39;从在媒体屏幕中显示标题文本的媒体项返回。

 [image_meta] => Array
        (
            [aperture] => 0
            [credit] => 
            [camera] => 
            [caption] => 
            [created_timestamp] => 0
            [copyright] => 
            [focal_length] => 0
            [iso] => 0
            [shutter_speed] => 0
            [title] => 
            [orientation] => 0
        [keywords] => Array
                (
                )
        )

所以我使用&#39; wp_prepare_attachment_for_js&#39;功能返回实际的标题&#39;值:

 [caption] => the current caption

所以我的问题是如何到标题&#39;媒体项目的元素?

...谢谢瑞克...

0 个答案:

没有答案