dpowt82802 2016-02-12 18:01
浏览 30
已采纳

如果($ image)和is_page_template

I'd like to take an existing function and alter it's output depending on the page template used (WordPress). The below looks to see if an image is present, then outputs it with the text first then the image after, so the image is on the right hand side visually. This behaves the same on all templates.

I've done some research and tried a few things but can't seem to crack it. What I need is something that says if the page template is 'template_left.php' output the cta-image before the content. Likewise, if the page template is 'template_right.php' output the cta-image after the contnent.

All help and advice to edit the below gratefully received.

<?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');
  • 写回答

1条回答 默认 最新

  • dongyouzhi7218 2016-02-12 18:38
    关注

    I think the WordPress function you are looking for is get_page_template_slug($post_id)

    Here is an example of how to use it in your situation:

    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');
    

    Edit:

    According to the documentation for get_page_template_slug, when used in the loop, the post_id defaults to the current post, so you probably can omit the parameter. Shortcodes are usually called while in the WordPress loop. This function will return empty if there is no page template, or false if it's not a page (so false for posts and other custom post types). Hope this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?