如果 ($image) 和 is_page_template

If ($image) and is_page_template

我想使用现有函数并根据使用的页面模板 (WordPress) 更改它的输出。下面查看是否存在图像,然后先输出文本,然后输出图像,因此图像在视觉上位于右侧。这在所有模板上的行为都相同。

我做了一些研究并尝试了一些东西,但似乎无法破解它。我需要的是说明如果页面模板 'template_left.php' 在内容之前输出 cta-image。同样,如果页面模板是 'template_right.php' 在内容之后输出 cta-image。

感谢您对编辑以下内容的所有帮助和建议。

<?php
function call_to_action_shortcode($attrs, $content = null) {
  $image = reset(rwmb_meta( "avenir_cta_image", 'type=image&size=large' ));

  if ($image) {
    $styles = "<style>
      .cta-image {
        background-image: url('{$image['url']}');
      }
    </style>";
    $output = '<div class="page-cta row">' .
      '<div class="content">' .
        $content .
      '</div>' .
      '<div class="cta-image pull-right"></div>' .
    '</div>';

    return $styles . $output;
  }

}
add_shortcode('call-to-action', 'call_to_action_shortcode');

我认为您正在寻找的 WordPress 功能是 get_page_template_slug($post_id)

以下是如何在您的情况下使用它的示例:

function call_to_action_shortcode($attrs, $content = null) {
  $image = reset(rwmb_meta( "avenir_cta_image", 'type=image&size=large' ));
  if ($image) {
    $template_name = get_page_template_slug(get_the_ID());
       if('template_left.php' === $template_name) {
            // your code for this template goes here
       } else {
            // code for other templates here
       }
    }
  }

  add_shortcode('call-to-action', 'call_to_action_shortcode');

编辑:

根据documentation for get_page_template_slug,在循环中使用时,post_id默认为当前的post,因此您可以省略该参数。短代码通常在 WordPress 循环中调用。如果没有页面模板,此函数将 return 为空,如果不是页面则为 false(对于 posts 和其他自定义 post 类型为 false)。希望这对您有所帮助!