[Resolved] PHP in pages/posts

Home Forums Support PHP in pages/posts

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #549109
    Tom

    Tom –

    I’ve seen that you’re a fan of Code Snippets, but that only works for code that should work as if it were in a functions.php file. Do you know of a way (plugin, black magic, etc) which will allow php in pages/posts that works well within GeneratePress?

    Basically I want to create a way to calculate years since a date. Many of my clients have statements on their sites like “A family owned business for 25 years”. The idea is to automate updating this date.

    The code (if it worked within a page) would look something like this for a business which started Feb 11, 1981.

    <!DOCTYPE html>
    <html>
    <body>
    
    We have been in business for <?php $bizstart=new DateTime("1981-02-11");$today=new DateTime();$interval=$today->diff($bizstart);echo $interval->format('%y '); ?>years.
    
    </body>
    </html>

    Any thoughts?

    Thanks!

    (other) Tom

    #549581
    Leo
    Staff
    Customer Support

    Hi there,

    I believe this is the answer you are looking for: https://generatepress.com/forums/topic/php-in-post/#post-509911

    Let me know 🙂

    #549842
    Tom

    Thanks Leo. I messed around with making my own shortcode last night, but I think I got the syntax wrong. It kept spacing things out strangely. I’ll read the docs and give it another whirl tonight. Good to know I’m on the right track. Will update progress, thanks!

    #550009
    Leo
    Staff
    Customer Support

    No problem 🙂 We will be here.

    #550080
    Tom

    Resolved! Thanks for keeping me on track.

    Turns out my issue was that I was echoing the result rather than returning it (once added to my child functions.php). Late night and I just wasn’t thinking clearly.

    return $interval->format('%y ');

    NOT

    echo $interval->format('%y ');

    #550315
    Leo
    Staff
    Customer Support

    Awesome.

    Glad you figured out 🙂

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.