【问题标题】:Proper way to make function calls in WordPress在 WordPress 中进行函数调用的正确方法
【发布时间】:2016-07-07 15:31:32
【问题描述】:

在 wordpress 页面上进行函数调用的最佳做法是什么?

例如,如果您想在主页上调用my_special_function();,那么放置函数调用的正确位置是哪里(即home-page.php/template-parts/content-page.php 等)。

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

仅供参考,我使用的是下划线主题。

我见过一些关于短代码的 cmets。与仅在该页面上调用函数相比,插入短代码的以下 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();

【问题讨论】:

  • 取决于主题实现。一些主题仅带有index.php,其他主题带有home-page.php。您的主题根目录中的 php 文件是什么?此外。现代主题带有页面构建器,很难说它可以在哪里发挥作用。
  • 另一种想法,如果您不熟悉运行函数的正确位置是创建自己的短代码,然后您可以将短代码放置在您的内容中而不是主题中。跨度>
  • @MerianosNikos 感谢您的回复。我使用下划线启动主题,到目前为止,我只是将函数调用放在我想要调用的任何页面的“内容区域”div 中。我只是想知道这是否是实现这一目标的最佳方法,或者是否有更合适的方法。我对短代码不是很熟悉,但我会看一下文档。
  • 你完全没问题。WordPress真的很简单,所以你应该采取严格的方式,停止思考更复杂的解决方案;)
  • @MerianosNikos 哈哈,好吧,我想我会继续做我正在做的事情,只是想确保将来不会有任何问题:)

标签: php wordpress custom-wordpress-pages


【解决方案1】:

不要编辑主题核心文件。 正确的方法是在子主题目录中使用functions.php文件。

你可以在这个文件中添加你的函数并使用 wordpress 钩子创建 shortocde 喜欢

my_special_function(){

//Your content goes here.

echo "This is proper way";

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

并在现场任何地方使用以下短指令。

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

【讨论】:

  • 直接在php中调用函数即可,无需使用do_shortcode函数。
  • @kunruh 我通常只是直接在页面模板中调用该函数,但我一直在寻找应该如何完成的最佳实践方法。
  • @MoxDev 如果您要在自己制作的 php 模板中使用该函数,最佳做法是直接调用该函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 2020-08-15
  • 2021-03-23
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多