2016-07-07 101 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

相关问题