0

I have a page template that is including another file via require_once. I want this included file to have access to the $post object but it can't find it.

So I ran something like this to see what's happening

page.php

<?php
    $post_title = $post->post_title;
    echo "Post:<br/>"; var_dump($post_title);

    require_once('inc/external.php');
?>

inc/external.php

<?php
    global $post_title;
    echo "External post:<br/>"; var_dump($post_title, true); echo "<br/><br/>";
?>

Not only does external.php not see $post_title, but it prints out of order:

Output:

External post: 
NULL

Post:
Title of the Post

Why would the echo/var_dump in the included file run before the original? I feel like this is linked to the fact that the variable can't be read in the included file.

  • have you tried global $post; inside either PHP file? external.php should inherit the variable scope, too, so you can create local variables in page.php and have them visible in external.php. – montrealist Apr 7 '16 at 20:35
  • There is a global $post; in page.php, just added that to external.php with no effect (note that I'm not actually querying the $post variable in external.php). – Esaevian Apr 7 '16 at 20:41
0

Must be something with your setup. Following works for me (inside child theme - should work for any theme though):

single.php:

global $post;
$bla = $post->post_title;
error_log('post title is: ' . $bla);
include('included.php');

included.php:

error_log('i am included file: ' . $bla);

Output in debug.log:

post title is:  Hello test
i am included file: Hello test

Both files are inside the same directory.

  • Hm. Only difference that I can see is that the included file is in a directory one level down from the parent (edited main post to reflect this). This still shouldn't be messing with the order of output. Going to try with two different pages. – Esaevian Apr 7 '16 at 20:52
  • but does using include instead of require_once affect the result for you? – majick Apr 8 '16 at 12:12
  • Nope - no difference. – montrealist Apr 8 '16 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.