If ($image) and 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');

Upvotes: 0

Views: 112

Answers (1)

Linnea Huxford
Linnea Huxford

Reputation: 430

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!

Upvotes: 1

Related Questions