2016-07-07 104 views
1

在wordpress頁面上進行函數調用的最佳做法是什麼?在WordPress中進行函數調用的正確方法

例如,如果您想在主頁上撥打my_special_function();,那麼在哪裏放置函數調用(即home-page.php,/template-parts/content-page.php等)。

<?php if(function_exists(my_special_function)) { 
    my_special_function(); 
} ?> 

僅供參考使用Underscores主題。

我見過關於短代碼的一些評論。像下面的插入短代碼的WP頁面模板是不是隻調用該頁面上的函數的最佳做法?

所以,如果我想要的功能,在頁面模板被稱爲下面我就只需要插入簡碼的地方我希望它在該頁面模板或者根本只是調用函數足以或最佳實踐

<?php 
/** 
* Template Name: Home Page 
* 
* The template for displaying the home page. 
* 
* @link https://codex.wordpress.org/Template_Hierarchy 
* 
* @package Rollins_Ridge 
*/ 

get_header(); ?> 

    <div id="primary" class="content-area"> 
     <main id="main" class="site-main" role="main"> 

       // insert Shortcode 
       <?php echo do_shortcode('[special_function_shortcode]') ;?> 

       // or just call the function 
       my_special_function(); 

       // or something else im not aware of 
       code here; 

      <?php 
      while (have_posts()) : the_post(); 

       get_template_part('template-parts/content', 'page'); 

       // If comments are open or we have at least one comment, load up the comment template. 
       if (comments_open() || get_comments_number()) : 
        comments_template(); 
       endif; 

      endwhile; // End of the loop ?> 
     </main><!-- #main --> 
    </div><!-- #primary --> 
<?php 
get_footer(); 
+0

取決於主題的實施。有些主題只有'index.php',其他主題則來自'home-page.php'。主題根目錄中的php文件是什麼?此外。現代主題與頁面建立者一起出現,更難以說明它可以發揮作用的地方。 –

+0

另一個想法是,如果您不熟悉運行函數的正確位置是創建自己的簡碼,那麼您可以將簡碼放在您的內容中而不是主題中。 –

+0

@MerianosNikos感謝您的回覆。我使用Underscores starter主題,到目前爲止,我只是把函數調用放在我想打電話的任何頁面的「content-area」div中。我只是想知道這是否是實現這一目標的最佳方式,或者是否有更合適的方法。我對短代碼不是很熟悉,但我會看看這些文檔。 – MoxDev

回答

1

不要編輯主題核心文件。 正確的方法是在子主題目錄中使用functions.php文件。

,你可以在這個文件中添加的功能和使用WordPress鉤 像

my_special_function(){ 

//Your content goes here. 

echo "This is proper way"; 

} 
add_shortcode('special_function_shortcode','my_special_function'); 

和使用的網站的任何地方下shortocde創建shortocde。

in wordpress page use [special_function_shortcode] 
and in php use 
<?php echo do_shortcode('[special_function_shortcode]') ;?> 
+0

你可以直接在php中調用函數,不需要使用do_shortcode函數。 – kunruh

+0

@kunruh我通常只是直接在頁面模板中調用函數,但我正在尋找一種最佳實踐方式來完成它。 – MoxDev

+0

@MoxDev如果你打算在你自己製作的php模板中使用這個函數,最好的做法是直接調用這個函數。 – kunruh

相關問題