在Wordpress模板中的任何其他代码之前添加PHP代码,以每篇文章为基础


Add PHP code before any other code in Wordpress template, on a per post basis

我正试图找出如何在模板中添加一些PHP代码,然后再添加其他代码(第1行)。

我想在帖子中使用自定义字段来完成这项工作。我正在尝试wordpress挂钩,但似乎只能插入HTML/JS,并且只能在实际的header.php中插入,而不能在它之前插入

有没有一个我应该使用的特定钩子,还有,有没有可能以这种方式将PHP添加到模板中?

如果您需要访问post的自定义字段,您可能需要挂接到wp钩子,该钩子在创建post对象并且条件函数可用之后,但在触发get_header之前触发。在你的functions.php文件中有这样的东西:

<?php
function my_function(){
  global $post;
  if( is_single() ){
    $my_meta = get_post_meta( $post->ID, 'my key', true ); // Assumes your custom meta returns a single value
    if( 'value expected' == $my_meta ){
      // My PHP code to run goes here
    }
  }
}
add_action( 'wp', 'my_function' );