PHP help with using variable inside code

221 Views Asked by At

I have this line of code: <?php global $bp; query_posts( 'author=$bp->displayed_user->id' ); if (have_posts()) : ?> but it doesn't work as expected. Probably because it's not grabbing the $bp->displayed_user->id part correctly. How do I do it?

Thanks

3

There are 3 best solutions below

2
On BEST ANSWER

It isn't working because it's treating the 'author=$bp->displayed_user->id' as a string rather than inlining the contents of the variable. (This is the main difference between using single and double quotes. Have a read of the PHP strings manual page for more information.)

To fix this, try either:

query_posts('author=' . $bp->displayed_user->id);

or

query_posts("author={$bp->displayed_user->id}");

That said, I'd personally recommend the first approach, as it's more explicit what's going on.

2
On
<?php global $bp; query_posts( 'author=' . $bp->displayed_user->id ); if (have_posts()) : ?>

In single quoted strings variables will not be expanded. See documentation here: http://php.net/manual/en/language.types.string.php

1
On

Using single quotes makes PHP do not fetch the variable value. Instead of using single quotes you can use double quotes:

<?php 
    global $bp; 
    query_posts( "author={$bp->displayed_user->id}" ); if (have_posts()) : 
?>

Or this way (I thik that is better):

<?php 
    global $bp; 
    query_posts( 'author=' . $bp->displayed_user->id ); if (have_posts()) :  
?>