• I have the following code in a custom plugin, since it’s code I will want to be able to call in all theme templates:

    function spoiler_statement() {
      if (get_post_meta( $post->ID, 'spoiler_statement', true)) {
        echo '<br /><b>Spoilers:</b> <div class="spoilers">' . get_post_meta( $post->ID, 'spoiler_statement', true) . '</div>';
      }
    }

    When I insert <?php spoiler_statement(); ?> into my template to call the function, nothing happens.

    When I insert the meat of my function into my template, it works exactly as expected:

    if (get_post_meta( $post->ID, 'spoiler_statement', true)) {
        echo '<br /><b>Spoilers:</b> <div class="spoilers">' . get_post_meta( $post->ID, 'spoiler_statement', true) . '</div>';
      }

    I’m at a loss for my next step. I need to create too many functions. The entirety of my content is stored in taxonomies and custom fields. I really don’t want to have to continue to add and update 500+ lines of code to my theme templates any time I change my theme.

Viewing 1 replies (of 1 total)
  • What’s probably happening is that you have to explicitly make the global $post variable available to your function:

    function spoiler_statement() {
      global $post;
    
      if (get_post_meta( $post->ID, 'spoiler_statement', true)) {
        echo '<br /><b>Spoilers:</b> <div class="spoilers">' . get_post_meta( $post->ID, 'spoiler_statement', true) . '</div>';
      }
    }
Viewing 1 replies (of 1 total)

The topic ‘Moving template code to function in a plugin prevents code from running’ is closed to new replies.