Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

php - How to set a link based off a post_parent being set - WordPress

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...