0

I'm trying to check if a page exists, if it is published, and display a list item with the link to the page if it is. Here's my code:

  <?php
    $page = get_page_by_path('/privacy-policy/', OBJECT, 'page');

    if ( get_post_status($page->post_status) == 'publish' ):
  ?>
  <li>
    <a href="<?php echo get_page_link( get_page_by_title('Privacy Policy') ); ?>">Privacy Policy</a>
  </li>
  <?php
    endif;

    $page = get_page_by_path('/terms-of-use/', OBJECT, 'page');

    if ( get_post_status($page->post_status) == 'publish' ):
  ?>
  <li>
    <a href="<?php echo get_page_link( get_page_by_title('Terms of Use') ); ?>">Terms of Use</a>
  </li>
  <?php
    endif;

    $page = get_page_by_path('/sitemap/', OBJECT, 'page');

    if ( get_post_status($page->post_status) == 'publish' ):
  ?>
  <li>
    <a href="<?php echo get_page_link( get_page_by_title('Sitemap') ); ?>">Sitemap</a>
  </li>
  <?php endif; ?>

It hides the first link because there's a sample Privacy Policy page that isn't published but it displays the other two with a link to the sample post. I haven't created the dummy page for the last two yet.

3
  • FYI the get_page_by_title() function has been deprecated.
    – Caleb
    Jun 13, 2023 at 13:44
  • 1
    Yeah. I found out. I changed it to get_page_by_path. Then, I finally discovered that the more proper way to do what I want to happen is to register a new menu in the functions.php of my theme. So, I'm going that way. I'm new to WordPress. Jun 13, 2023 at 21:25
  • Please mark my answer as accepted, as it is the answer to your question, even though not your solution.
    – Caleb
    Jun 13, 2023 at 22:44

1 Answer 1

0

If the page doesn't exist, then get_page_by_title() returns null, which when passed into get_page_link() still returns a URL, which could conceivably redirect to the sample post. Check the value of get_page_by_title() is valid before using.

Your Answer

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

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