2012-02-05 114 views
1

我有一個函數在帖子中自動創建一個自定義字段。我有這個位於我的functions.php。在函數中包含w_thumbnail_src?

Image是自定義字段的名稱,HERE是值。我怎樣才能把功能w_thumbnail_src作爲變量?

add_action('wp_insert_post', 'mk_set_default_custom_fields'); 
    function mk_set_default_custom_fields($post_id) 

    { 
     if ($_GET['post_type'] != 'post') { 
      add_post_meta($post_id, 'Image','HERE', true); 
     } 
     return true; 
    } 

,讓我補充一點,w_thumbnail_src是看起來像這樣

function w_thumbnail_src() { 
    if (has_post_thumbnail()) { 
     $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'emphasis'); 
     echo $thumb[0]; // thumbnail url 
    } 
} 
+0

我不是很清楚你在問什麼? 'add_post_meta($ post_id,'Image',w_thumbnail_src(),true);'你是什麼意思? – drew010 2012-02-05 20:27:47

+0

多數民衆贊成的想法,但我已經嘗試過,它不工作。它只是返回一個空的值字段。我需要縮略圖網址在那裏出現 – Demilio 2012-02-05 21:19:59

回答

1

我認爲你需要改變同一個文件中的函數:
add_post_meta($post_id, 'Image','HERE', true);
到:
add_post_meta($post_id, 'Image', w_thumbnail_src(), true);

並通過將其更改爲以下來修復w_thumbnail_src()函數:

function w_thumbnail_src() { 
    if (has_post_thumbnail()) { 
     $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'emphasis'); 
     return $thumb[0]; // thumbnail url 
    } else { 
     return ''; // or a default thumbnail url 
    } 
} 
+0

謝謝你的嘗試,但它沒有奏效,但我已經發布了答案,你好嗨。謝謝!! – Demilio 2012-02-05 22:10:03

0

這是將縮略圖url添加到名爲Image的自定義字段的最終代碼。

function w_thumbnail_src() { 
    if (has_post_thumbnail()) { 
     $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'emphasis'); 
     return $thumb[0]; // thumbnail url 
    } else { 
     return ''; // or a default thumbnail url 
    } 
} 


add_action('publish_page', 'add_custom_field_automatically', 'w_thumbnail_src'); 
add_action('publish_post', 'add_custom_field_automatically'); 
function add_custom_field_automatically($post_id) { 
global $wpdb; 
if(!wp_is_post_revision($post_id)) { 
add_post_meta($post_id, 'Image', w_thumbnail_src(), true); 
} 
}