How to set a link based off a post_parent being se

2019-09-21 20:11发布

问题:

I'm learning as I go here and wanted to reach out for a better understanding of how to handle an if statement within WordPress regarding the Parent being set or not.

What I'm trying to do:

I'm attempting to set the URL for an element based off the Parent being set for a page within the "Page Attributes" section. As it currently stands, if a Parent is set for the page, it will update the href value based off the homepage of the parent. However, if no parent is set, it is populating the page URL as the parent.

What I want it to do:

If no parent is set, echo home_url(). This will have it default to the homepage URL if no Parent is set.

Original version:

<?php $permalink = get_permalink($post->post_parent); ?>

Newer version (that needs TLC to work):

PHP:
<?php 
    if ($post->post_parent) {
        $permalink = echo get_permalink($post->post_parent);
    } else {
        $permalink = home_url();
    }
?>

HTML:
<a href="<?php echo $permalink; ?>">Example</a>

Currently, it's not working for the else statement. If I attempt to echo any type of text for the else statement, it appends it to the vainty URL set for the page I'm actively viewing.

What I need the function to do:

<?php
    if (a page/post has a parent set within the page attribute) {
        $permalink = echo get_permalink($post->post_parent);
    } else (if a page/post does not have a parent set within the page attribute) {
        $permalink = echo home_url();
    }
?>

Any help would be greatly appreciated! Thanks!

回答1:

on your PHP:

<?php 
    the_post(); 
    if(count(get_pages('child_of='.$post->ID))!=0){ 
        if($post->post_parent!=0) { 
            $permalink = get_permalink( end( get_ancestors( get_the_ID(), 'page' ))); 
        } else if ($post->ID==0) { 
            $permalink = home_url(); 
        } else { 
            $permalink = get_permalink(); 
        } 
    } else { 
        $permalink = home_url(); 
    }
?>

you should remove echo after equals = if you don't want the page to mess up.

then you will be able to get the value you want on your variable $permalink.

P.S. there might be a cleaner way to do this but for now, here it is.

UPDATE: pls check discussion logs to how we arrived with the answer.