如何根据设置的 post_parent 设置链接 - WordPress [英] How to set a link based off a post_parent being set - WordPress

查看:76
本文介绍了如何根据设置的 post_parent 设置链接 - WordPress的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习,我希望能更好地了解如何在 WordPress 中处理有关是否设置父级的 if 语句.

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.

我想做什么:

我试图根据为页面属性"部分中的页面设置的父级来设置元素的 URL.按照目前的情况,如果为页面设置了父级,它将根据父级的主页更新 href 值.但是,如果未设置父项,则会将页面 URL 填充为父项.

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.

我想让它做什么:

如果未设置父级,则回显 home_url().如果未设置父级,则默认为主页 URL.

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

原始版本:

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

较新的版本(需要 TLC 才能工作):

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>

目前,它不适用于 else 语句.如果我尝试为 else 语句回显任何类型的文本,它会将其附加到为我正在查看的页面设置的无效 URL 中.

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.

我需要函数做什么:

<?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!

推荐答案

关于您的 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(); 
    }
?>

如果您不希望页面混乱,您应该在 equals = 之后删除 echo.

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

然后您将能够在变量 $permalink 上获得所需的值.

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.

这篇关于如何根据设置的 post_parent 设置链接 - WordPress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆