2016-02-12 13 views
0

我想採取一個現有的功能,並根據使用的頁面模板(WordPress)改變它的輸出。下面看看是否存在一個圖像,然後輸出它與文本先後圖像,因此圖像在右側視覺。這在所有模板上表現相同。

我已經做了一些研究,並嘗試了一些東西,但似乎無法破解它。我需要的是說,如果頁面模板是'template_left.php'在內容之前輸出cta-image。同樣,如果頁面模板是'template_right.php',則會在contnent之後輸出cta-image。

所有幫助和建議,以編輯下面感激地收到。

<?php 
function call_to_action_shortcode($attrs, $content = null) { 
    $image = reset(rwmb_meta("avenir_cta_image", 'type=image&size=large')); 

    if ($image) { 
    $styles = "<style> 
     .cta-image { 
     background-image: url('{$image['url']}'); 
     } 
    </style>"; 
    $output = '<div class="page-cta row">' . 
     '<div class="content">' . 
     $content . 
     '</div>' . 
     '<div class="cta-image pull-right"></div>' . 
    '</div>'; 

    return $styles . $output; 
    } 

} 
add_shortcode('call-to-action', 'call_to_action_shortcode'); 

回答

1

我認爲WordPress的功能,你正在尋找的是get_page_template_slug($post_id)

下面是如何在您的情況使用它的一個例子:

function call_to_action_shortcode($attrs, $content = null) { 
    $image = reset(rwmb_meta("avenir_cta_image", 'type=image&size=large')); 
    if ($image) { 
    $template_name = get_page_template_slug(get_the_ID()); 
     if('template_left.php' === $template_name) { 
      // your code for this template goes here 
     } else { 
      // code for other templates here 
     } 
    } 
    } 

    add_shortcode('call-to-action', 'call_to_action_shortcode'); 

編輯:

根據documentation for get_page_template_slug,當在循環中使用時,post_id默認爲當前帖子,所以你的概率bly可以省略參數。短代碼通常在WordPress循環中調用。如果沒有頁面模板,此函數將返回空值;如果不是頁面,則返回false(對於帖子和其他自定義帖子類型,則爲false)。希望這可以幫助!

相關問題