【问题标题】:Where do i add custom PHP code in Wordpress custom template?在 Wordpress 自定义模板中在哪里添加自定义 PHP 代码?
【发布时间】:2014-08-01 18:40:59
【问题描述】:

大家好!根据我的阅读,将 PHP 代码添加到 wordpress 页面的最佳方法是通过自定义模板。所以我从主题中取出 page.php 并使用 html 代码对其进行自定义,没有任何问题。问题出在 PHP 代码上。无论我在哪里添加它,它都不起作用。

我的问题是在哪里添加用于表单验证的自定义 PHP 代码?

页面如下所示:

/*
Template Name: example
*/

<?php
get_header();
if ($tempera_frontpage=="Enable" && is_front_page()): get_template_part( 'frontpage' );
else :
?>

<section id="container" class="<?php echo tempera_get_layout_class(); ?>">
<div id="content" role="main">
<?php cryout_before_content_hook(); ?>
<?php get_template_part( 'content/content', 'page'); ?>

I added the HTML code here:  

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> " >
.....
</form>

<?php
endif;
get_footer();
?>

【问题讨论】:

    标签: php wordpress forms templates


    【解决方案1】:

    根据this,您将在 HTML 之前添加它,靠近代码顶部。

    【讨论】:

      【解决方案2】:

      基本上它是 PHP 并且应该可以工作,如果你想在同一个模板文件中验证表单,使用一个空的 action 属性:

      <form method="post" action="">
      .....
      </form>
      

      并确保不要在表单元素名称属性上使用 WordPress 保留字,例如 name

      在文件的顶部,您可以像任何其他 PHP 文件一样验证和验证表单发送的所有请求。

      <?php
      if (!empty($_POST)) {
        //validate or do something here
      }
      get_header();
      if ($tempera_frontpage=="Enable" && is_front_page()): get_template_part( 'frontpage' );
      else :
      ?>
      

      希望这个解决方案能帮到你。

      【讨论】:

      • 非常感谢!这是一个简单的解决方案,并且有效。还有一个问题,有没有办法合并原始操作代码?从我读到它对表单验证很重要
      • 您仍然可以将当前 url 添加到操作中,例如:&lt;form action="&lt;?php echo $_SERVER[REQUEST_URI]; ?&gt;"&gt; 或在此处寻找使用完整 url 的方法:stackoverflow.com/questions/6768793/get-the-full-url-in-php
      【解决方案3】:

      我认为您应该修改 content-page.php 模板。注意页面模板调用它:

      <?php get_template_part( 'content/content', 'page'); ?>
      

      在内容模板中,您应该会看到类似

      <?php the_content(); ?>
      

      如果您在下一行添加表单 html,它将在同一个 div 中,类似于

      <div class="entry-content>
      </div>
      

      这样,新内容将与其他内容位于同一个容器中,并具有相同的样式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-23
        相关资源
        最近更新 更多