2013-01-14 46 views
0

我有一個寬框自定義帖子類型的元框。我試圖用get_post_meta放置一些CSS的頭。一切都在工作,但元值沒有經過。這裏是我的功能:WordPress的get_post_meta不工作在一個函數

function mo_carousel_css(){ 
    global $post; 
    $width = get_post_meta($post->ID, 'mo_carousel_width', true); 
    ?> 
    <style type="text/css"> 
     .jcarousel-container-horizontal{ 
     width:<?php echo $width; ?>px; 
     } 
    </style> 
    <?php 
    } 

我檢查了數據庫和元鍵/值被妥善保存分別mo_carousel_width500。我認爲global $post;將是修復,但沒有運氣。

通過訪問$object後端的元框中的值可以很好地檢索到,但似乎也不起作用。這是代碼所創造的價值形式:

/* Display the post meta box. */ 
function mo_carousel_meta_box($object, $box) { ?> 

    <?php wp_nonce_field(basename(__FILE__), 'mo_carousel_nonce'); ?> 
    <p> 
     <span>Carousel Size</span> 
     </br> 
     <input type="text" name="mo-carousel-width" id="mo-carousel-width" value="<?php echo esc_attr(get_post_meta($object->ID, 'mo_carousel_width', true)); ?>" size="10" /> 
+0

你把這段代碼放在哪裏?當你期望輸出時,你在哪裏使用了該功能? –

+0

在插件中。我道歉。我可能應該提到這一點。而且,即時通過使用'add_action('wp_head','mo_carousel_css');'將此函數添加到wp_head;'。 CSS使它成爲頭,但價值不是。 –

+0

恩......你這樣做是正確的。我見過類似的代碼工作。試試'global $ wp_query; echo $ wp_query-> post-> ID'。它訪問相同的變量,但它可能值得一試。我不確定$ post是否設置在循環之前。 –

回答

1

我通過研究簡碼API寫到這,我認爲它應該工作,但我還沒有嘗試過。

function mo_carousel_css() { 
    global $post; 
    preg_match('/' . get_shortcode_regex() . '/s', $post->post_content, $m); 
    if (is_array($m) && $m[2] == 'shortcode') { 
       $shortcode_args = shortcode_parse_atts($m[3]); 
     $width = get_post_meta($shortcode_args['idatt'], 'mo_carousel_width', true); 
     <style type="text/css"> 
      .jcarousel-container-horizontal{ width:<?php echo $width; ?>px; } 
     </style> 
    } 
} 

基本上它所做的就是檢查短代碼是否被用在當前文章中。如果正在使用短代碼,請從中檢索屬性並使用id屬性獲取後期元數據。

如果你的簡碼是[displayCustomPost id=24]那麼你將有displayCustomPostidattid更換shortcode

+0

這工作就像一個魅力。非常感謝你爲我挖掘它。 –

相關問題