[英]Object doesnt have the same properties inside a function PHP
I've never worked with PHP before.我以前从未使用过 PHP。 I have the code below, which works fine.
我有下面的代码,它工作正常。
$taxonomy = 'person';
// get the term IDs assigned to post.
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
$separator = '';
if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) {
$term_ids = implode( ',' , $post_terms );
$terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids );
$terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator );
echo $terms;
}
I tried to put this in a function so I can pass it an argument and call it.我试图把它放在一个函数中,这样我就可以传递一个参数并调用它。
function get_custom_tax($taxonomy) {
// get the term IDs assigned to post.
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
$separator = '';
if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) {
$term_ids = implode( ',' , $post_terms );
$terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids );
$terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator );
echo $terms;
}
}
$taxonomy = 'person';
get_custom_tax($taxonomy);
But for some reason this doesn't work... Stack tells me im trying to get the property ID
of a non-object (I guess for $post->ID
)但由于某种原因,这不起作用......堆栈告诉我我正在尝试获取非对象的属性
ID
(我猜是$post->ID
)
Whats going on here?这里发生了什么?
Looks like it was a score issue.好像是分数问题。
Changing my function to pass $post
outside the function did the trick更改我的函数以在函数外部传递
$post
就成功了
function get_custom_tax($taxonomy, $post) {
// get the term IDs assigned to post.
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
$separator = '';
if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) {
$term_ids = implode( ',' , $post_terms );
$terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids );
$terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator );
echo $terms;
}
}
$taxonomy = 'person';
get_custom_tax($taxonomy, $post);
Your function is missing post object.. you can declare as global or pass as a params您的函数缺少 post 对象.. 您可以声明为全局或作为参数传递
function get_custom_tax($taxonomy) {
global $post;
// get the term IDs assigned to post.
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
$separator = '';
if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) {
$term_ids = implode( ',' , $post_terms );
$terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids );
$terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator );
echo $terms;
}
}
$taxonomy = 'person';
get_custom_tax($taxonomy);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.