2015-09-10 23 views
0

我在我的網站的每個頁面上都有一個Book Now按鈕。我想知道哪個按鈕被選中,並且不希望將25個以上的塊添加到網站以手動添加該類。如果我可以使按鈕具有唯一性(根據頁面URL添加其他課程),我可以使用Google Analytics(分析)。但我不是一個編碼員,儘管我熟悉PHP和jQuery。Drupal - 根據URL向現有按鈕添加課程

+0

歡迎來到StackOverflow Michael!請查看http://stackoverflow.com/help/how-to-ask獲取製作一個好問題的提示。在你的情況下,請包括你試過的代碼。 – eebbesen

回答

0

Hye Michael,在閱讀完您的問題後,我已經在我的本地測試drupal網站上測試了您的場景。實現它真的很容易。這是您需要放入您創建的塊的一段PHP代碼。

<?php 
$url = current_path(); 
$class_from_url = explode("/", $url); 
echo "<a href=[link_to_whatever] class='". $class_from_url[0] ."'>[Link Title]</a>"; 
?> 

確保你的「PHP過濾器」模塊已啓用,這將使你從塊體在「文本格式」中選擇PHP代碼。

+0

將PHP代碼放入內容實體(節點,塊等)是一種不好的做法,由於各種原因而不鼓勵。有關更多詳細信息,請參閱http://drupal.stackexchange.com/questions/2509/what-are-the-downsides-of-using-custom-php-code-in-blocks-nodes-views-args。 –

+0

我知道這是一個不好的做法,但不限制:)。另一方面,如果我們看看這個要求,這也是一個不好的做法。如果頁面網址中包含特殊字符會怎麼樣?他們也會去那個主播班。 –

0

對於Drupal 7,完成目標的最佳方法是將theme_button()函數複製到主題的template.php文件中,並添加一些自定義代碼來檢查URL並添加該類。

YOURTHEME_button($vars) { 
    $element = $variables ['element']; 
    $element ['#attributes']['type'] = 'submit'; 
    element_set_attributes($element, array('id', 'name', 'value')); 

    $element ['#attributes']['class'][] = 'form-' . $element ['#button_type']; 
    if (!empty($element ['#attributes']['disabled'])) { 
    $element ['#attributes']['class'][] = 'form-button-disabled'; 
    } 

    // Check URL to determine what button class to add 
    $button_class = null; 
    $current_path = base_path() . request_path(); 
    switch ($current_path) { 
    '/form1': 
     $button_class = 'button-for-form1'; 
     break; 
    '/form2': 
     $button_class = 'button-for-form2'; 
     break; 
    } 
    if ($button_class !== null) { 
    $element ['#attributes']['class'][] = $button_class; 
    } 

    return '<input' . drupal_attributes($element ['#attributes']) . ' />'; 
} 

注意,此方法將增加該類只爲您明確指定的URL,而忽略可能被納入作爲URL的一部分的任何用戶提供的參數。