0

I am trying to create a title from page variables using this.

<?php if $page_title = $page_title ?: $page_name'  - Blah.com'; { ?>
<?php } else { ?>
<?php echo $page_title . " - Blah.com" ; ?>
<?php } ?>

When added to page, all I get is a blank page once I open it in a browser. Not sure if I am doing this right.

I want it to use the page_title variable and some text after it but if page_title is empty I want it to use the page_name instead. Can this be done with shorter code?

Thanks for any help

1
  • if statements require parenthesis around their expressions and you are using one equals for the expression which will assign, not compare the variable and most likely return true (if the value assigned is truthy). I guess a comparison there will always return true though because a variable is always equal to itself. Looks like you are confusing an if statement and a ternary. if(something is true){ /*do this*/} else {/*else do this*/} vs a ternary (something is true) ? /*do this*/ : /*else do this*/; Commented Feb 28, 2017 at 23:18

1 Answer 1

1

I think this is what you want:

<?php
  echo (isset($page_title)) ? $page_name . ' - Blah.com' : $page_title . ' - Blah.com' ;
?>

PHP ternary operator syntax is as follows:

$variable = condition ? if true : if false
Sign up to request clarification or add additional context in comments.

2 Comments

i had to switch it around but worked perfectly. echo (empty($page_title)) ? $page_name . ' - Blah.com' : $page_title . ' - Blah.com' ;
That was a typo on my part. I updated the answer accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.