Object doesnt have the same properties inside a function PHP - php

I've never worked with PHP before. 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)
Whats going on here?

Looks like it was a score issue.
Changing my function to pass $post outside the function did the trick
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
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);

Related

Get product category and tag terms as meta keyword in WooCommerce

I have been using below code for using Tags & categories as META Keywords for my wordpress posts.
function wcs_add_meta_keywords() {
global $post;
if ( is_single() ) {
$cats = get_the_category( $post->ID );
$tags = get_the_tags( $post->ID );
$keywords = '';
foreach ( $cats as $cat ) {
$keywords .= $cat->cat_name . ", ";
}
foreach ( $tags as $tag ) {
$keywords .= $tag->name . ", ";
}
echo '<meta name="keywords" content="' . $keywords . '" />' . "\n";
}}add_action( 'wp_head', 'wcs_add_meta_keywords' , 2 );
and below code for using Product description as META description.
function wcs_add_meta_description_tag() {
global $post;
if ( is_single() ) {
$meta = strip_tags( $post->post_content );
$meta = strip_shortcodes( $post->post_content );
$meta = str_replace( array("\n", "\r", "\t"), ' ', $meta );
$meta = mb_substr( $meta, 0, 125, 'utf8' );
echo '<meta name="description" content="' . $meta . '" />' . "\n";
}}add_action( 'wp_head', 'wcs_add_meta_description_tag' , 2 );
But now i want to achieve the same for my products in woocommerce. I have learnt and came to know that woocommerce use taxonomies instead so i tried using get_terms() and product_tag, product_cat in place of get_the_category and get_the_tag. But it does not work.
Can anyone help with the correct usage of the variables for the both codes.
thanks in advance
For WordPress and WooCommerce term taxonomies on single post (or custom post), you can better use wp_get_post_terms(), which allows the "fields" argument to target term "names", so the code will be more compact and efficient:
For both WooCommerce and Wordpress you will use:
add_action( 'wp_head', 'wcs_add_meta_keywords' , 2 );
function wcs_add_meta_keywords() {
// For WordPress single posts with categories and tags
if ( is_single() && ! is_product() ) {
$cats = (array) wp_get_post_terms( get_the_id(), 'category', array('fields' => 'names') );
$tags = (array) wp_get_post_terms( get_the_id(), 'post_tag', array('fields' => 'names') );
}
// For WooCommerce single product (product categories and product tags)
elseif ( is_product() ) {
$cats = (array) wp_get_post_terms( get_the_id(), 'product_cat', array('fields' => 'names') );
$tags = (array) wp_get_post_terms( get_the_id(), 'product_tag', array('fields' => 'names') );
}
if ( ! empty( $cats ) || ! empty( $tags ) ){
echo '<meta name="keywords" content="' . implode( ', ', array_merge( $cats, $tags ) ) . '" />' . "\n";
}
}
For WooCommerce only use:
add_action( 'wp_head', 'wcs_add_meta_keywords', 2);
function wcs_add_meta_keywords() {
if ( is_product() ) {
$product_cats = (array) wp_get_post_terms( get_the_id(), 'product_cat', array('fields' => 'names') );
$product_tags = (array) wp_get_post_terms( get_the_id(), 'product_tag', array('fields' => 'names') );
}
if ( ! empty( $product_cats ) || ! empty( $product_tags ) ){
echo '<meta name="keywords" content="' . implode( ', ', array_merge( $product_cats, $product_tags ) ) . '" />' . "\n";
}
}
Code goes in functions.php file of your active child theme (active theme). Tested and works.

Return term_id's recursively

I have this code:
public function get_taxonomy_hierarchy( $taxonomy, $parent = 0 )
{
$taxonomy = is_array( $taxonomy ) ? array_shift( $taxonomy ) : $taxonomy;
$terms = get_terms( $taxonomy, [ 'parent' => $parent ] );
$children = [];
foreach ( $terms as $term ) {
$term->url = get_term_link( $term->term_id);
$term->children = $this->get_taxonomy_hierarchy( $taxonomy, $term->term_id );
$children[ ] = $term->id;
}
return $children;
}
My problem is that this function only returns direct descendants id's and ignores others. What am I missing here?
It looks to me like you need to push the term_ids to the children array, rather than just declaring $children[ ] = $term->id;
public function get_taxonomy_hierarchy( $taxonomy, $parent = 0 )
{
$taxonomy = is_array( $taxonomy ) ? array_shift( $taxonomy ) : $taxonomy;
$terms = get_terms( $taxonomy, [ 'parent' => $parent ] );
$children = [];
foreach ( $terms as $term ) {
$term->url = get_term_link( $term->term_id);
$term->children = $this->get_taxonomy_hierarchy( $taxonomy, $term->term_id );
array_push($children, $term->term_id);
}
return $children;
}
Also, shouldn't it be $term->term_id; in line 9 of your code?

Exclude certain taxonomy from function

I need a help with a WordPress code.
On this page https://developer.wordpress.org/reference/functions/get_the_terms/ I got a code that returns my taxonomies and their terms.
But I'd like a certain taxonomy called "Ad Type" to be excluded from this list.
I managed to exclude some terms from "Ad Type" using this code...
// An array of IDs to ignore / exclude
$ excluded_ids = array (1, 2, 3, 4);
foreach ($ terms as $ term) {
// Only proceed if the term_id is NOT in the $ excluded_ids array
if (! in_array ($ term-> term_id, $ excluded_ids)) {
$ out. = '<li> <a href="' .get_term_link($term-> slug, $ taxonomy).' '>'. $ term-> name. '</a> </ li>';
}
}
But what I want is that the "Ad Type" taxonomy does not appear at all.
Because with the code above the Title of "Ad Type" is still appearing on the terms list retrieved.
What i want is to totally exlcude this taxonomy from being retrieved on that part of my wordpress template.
Here is the code:
function wpdocs_custom_taxonomies_terms_links() {
// Get post by post ID.
$post = get_post( $post->ID );
// Get post type by post.
$post_type = $post->post_type;
// Get post type taxonomies.
$taxonomies = get_object_taxonomies( $post_type, 'objects' );
$out = array();
foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
// Get the terms related to post.
$terms = get_the_terms( $post->ID, $taxonomy_slug );
if ( ! empty( $terms ) ) {
$out[] = "<h6>" . $taxonomy->label . ":</h6>\n<ul>";
foreach ( $terms as $term ) {
$out[] = sprintf( '<li>%2$s</li> - ',
esc_url( get_term_link( $term->slug, $taxonomy_slug ) ),
esc_html( $term->name )
);
}
$out[] = "</ul>\n";
}
}
return implode( '', $out );
}
And here is how i retrieve it on my template page:
<?php echo wpdocs_custom_taxonomies_terms_links(); ?>
Is there a way to do this?
can anybody help me?
Thanks
I don't know if I am comparing it right but you can check if current taxonomy is not Ad Type only then get terms
foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
if ($taxonomy_slug !== 'ad_type') :
// Get the terms related to post.
$terms = get_the_terms( $post->ID, $taxonomy_slug );
if ( ! empty( $terms ) ) {
$out[] = "<h6>" . $taxonomy->label . ":</h6>\n<ul>";
foreach ( $terms as $term ) {
$out[] = sprintf( '<li>%2$s</li> - ',
esc_url( get_term_link( $term->slug, $taxonomy_slug ) ),
esc_html( $term->name )
);
}
$out[] = "</ul>\n";
}
endif;
}
You can exclude the desired term(s) by adding if ($term->term_id == 30) continue; as shown below, where 30 and 31 are the IDs of excluded terms.
foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
// Get the terms related to post.
$terms = get_the_terms( $post->ID, $taxonomy_slug );
if ( ! empty( $terms ) ) {
$out[] = "<h6>" . $taxonomy->label . ":</h6>\n<ul>";
foreach ( $terms as $term ) {
//Excluded terms, change the IDs as you wish
if ($term->term_id == 30) continue;
if ($term->term_id == 31) continue;
$out[] = sprintf( '<li>%2$s</li> - ',
esc_url( get_term_link( $term->slug, $taxonomy_slug ) ),
esc_html( $term->name )
);
}
$out[] = "</ul>\n";
}
}
return implode( '', $out );
}

Adding a link into wordpress shortcode

i have a shortcode that posts recent blog entries from a certain category on one of my web pages, however i want to display a static link at the end of everypost, is there anyway to do this?
the following code is used to display the posts:
<?php echo do_shortcode('[display-posts category="competitions" posts_per_page="4" include_excerpt="true" image_size="thumbnail" wrapper="ul"]');
Thanks in advance.
<?php
// Create the shortcode
add_shortcode( 'display-posts', 'be_display_posts_shortcode' );
function be_display_posts_shortcode( $atts ) {
// Original Attributes, for filters
$original_atts = $atts;
// Pull in shortcode attributes and set defaults
$atts = shortcode_atts( array(
'title' => '',
'author' => '',
'category' => '',
'date_format' => '(n/j/Y)',
'display_posts_off' => false,
'exclude_current' => false,
'id' => false,
'ignore_sticky_posts' => false,
'image_size' => false,
'include_title' => true,
'include_author' => false,
'include_content' => false,
'include_date' => false,
'include_excerpt' => false,
'meta_key' => '',
'meta_value' => '',
'no_posts_message' => '',
'offset' => 0,
'order' => 'DESC',
'orderby' => 'date',
'post_parent' => false,
'post_status' => 'publish',
'post_type' => 'post',
'posts_per_page' => '10',
'tag' => '',
'tax_operator' => 'IN',
'tax_term' => false,
'taxonomy' => false,
'wrapper' => 'ul',
'wrapper_class' => 'display-posts-listing',
'wrapper_id' => false,
), $atts, 'display-posts' );
// End early if shortcode should be turned off
if( $atts['display_posts_off'] )
return;
$shortcode_title = sanitize_text_field( $atts['title'] );
$author = sanitize_text_field( $atts['author'] );
$category = sanitize_text_field( $atts['category'] );
$date_format = sanitize_text_field( $atts['date_format'] );
$exclude_current = be_display_posts_bool( $atts['exclude_current'] );
$id = $atts['id']; // Sanitized later as an array of integers
$ignore_sticky_posts = be_display_posts_bool( $atts['ignore_sticky_posts'] );
$image_size = sanitize_key( $atts['image_size'] );
$include_title = be_display_posts_bool( $atts['include_title'] );
$include_author = be_display_posts_bool( $atts['include_author'] );
$include_content = be_display_posts_bool( $atts['include_content'] );
$include_date = be_display_posts_bool( $atts['include_date'] );
$include_excerpt = be_display_posts_bool( $atts['include_excerpt'] );
$meta_key = sanitize_text_field( $atts['meta_key'] );
$meta_value = sanitize_text_field( $atts['meta_value'] );
$no_posts_message = sanitize_text_field( $atts['no_posts_message'] );
$offset = intval( $atts['offset'] );
$order = sanitize_key( $atts['order'] );
$orderby = sanitize_key( $atts['orderby'] );
$post_parent = $atts['post_parent']; // Validated later, after check for 'current'
$post_status = $atts['post_status']; // Validated later as one of a few values
$post_type = sanitize_text_field( $atts['post_type'] );
$posts_per_page = intval( $atts['posts_per_page'] );
$tag = sanitize_text_field( $atts['tag'] );
$tax_operator = $atts['tax_operator']; // Validated later as one of a few values
$tax_term = sanitize_text_field( $atts['tax_term'] );
$taxonomy = sanitize_key( $atts['taxonomy'] );
$wrapper = sanitize_text_field( $atts['wrapper'] );
$wrapper_class = sanitize_html_class( $atts['wrapper_class'] );
if( !empty( $wrapper_class ) )
$wrapper_class = ' class="' . $wrapper_class . '"';
$wrapper_id = sanitize_html_class( $atts['wrapper_id'] );
if( !empty( $wrapper_id ) )
$wrapper_id = ' id="' . $wrapper_id . '"';
// Set up initial query for post
$args = array(
'category_name' => $category,
'order' => $order,
'orderby' => $orderby,
'post_type' => explode( ',', $post_type ),
'posts_per_page' => $posts_per_page,
'tag' => $tag,
);
// Ignore Sticky Posts
if( $ignore_sticky_posts )
$args['ignore_sticky_posts'] = true;
// Meta key (for ordering)
if( !empty( $meta_key ) )
$args['meta_key'] = $meta_key;
// Meta value (for simple meta queries)
if( !empty( $meta_value ) )
$args['meta_value'] = $meta_value;
// If Post IDs
if( $id ) {
$posts_in = array_map( 'intval', explode( ',', $id ) );
$args['post__in'] = $posts_in;
}
// If Exclude Current
if( $exclude_current )
$args['post__not_in'] = array( get_the_ID() );
// Post Author
if( !empty( $author ) )
$args['author_name'] = $author;
// Offset
if( !empty( $offset ) )
$args['offset'] = $offset;
// Post Status
$post_status = explode( ', ', $post_status );
$validated = array();
$available = array( 'publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash', 'any' );
foreach ( $post_status as $unvalidated )
if ( in_array( $unvalidated, $available ) )
$validated[] = $unvalidated;
if( !empty( $validated ) )
$args['post_status'] = $validated;
// If taxonomy attributes, create a taxonomy query
if ( !empty( $taxonomy ) && !empty( $tax_term ) ) {
// Term string to array
$tax_term = explode( ', ', $tax_term );
// Validate operator
if( !in_array( $tax_operator, array( 'IN', 'NOT IN', 'AND' ) ) )
$tax_operator = 'IN';
$tax_args = array(
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $tax_term,
'operator' => $tax_operator
)
)
);
// Check for multiple taxonomy queries
$count = 2;
$more_tax_queries = false;
while(
isset( $original_atts['taxonomy_' . $count] ) && !empty( $original_atts['taxonomy_' . $count] ) &&
isset( $original_atts['tax_' . $count . '_term'] ) && !empty( $original_atts['tax_' . $count . '_term'] )
):
// Sanitize values
$more_tax_queries = true;
$taxonomy = sanitize_key( $original_atts['taxonomy_' . $count] );
$terms = explode( ', ', sanitize_text_field( $original_atts['tax_' . $count . '_term'] ) );
$tax_operator = isset( $original_atts['tax_' . $count . '_operator'] ) ? $original_atts['tax_' . $count . '_operator'] : 'IN';
$tax_operator = in_array( $tax_operator, array( 'IN', 'NOT IN', 'AND' ) ) ? $tax_operator : 'IN';
$tax_args['tax_query'][] = array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $terms,
'operator' => $tax_operator
);
$count++;
endwhile;
if( $more_tax_queries ):
$tax_relation = 'AND';
if( isset( $original_atts['tax_relation'] ) && in_array( $original_atts['tax_relation'], array( 'AND', 'OR' ) ) )
$tax_relation = $original_atts['tax_relation'];
$args['tax_query']['relation'] = $tax_relation;
endif;
$args = array_merge( $args, $tax_args );
}
// If post parent attribute, set up parent
if( $post_parent ) {
if( 'current' == $post_parent ) {
global $post;
$post_parent = get_the_ID();
}
$args['post_parent'] = intval( $post_parent );
}
// Set up html elements used to wrap the posts.
// Default is ul/li, but can also be ol/li and div/div
$wrapper_options = array( 'ul', 'ol', 'div' );
if( ! in_array( $wrapper, $wrapper_options ) )
$wrapper = 'ul';
$inner_wrapper = 'div' == $wrapper ? 'div' : 'li';
$listing = new WP_Query( apply_filters( 'display_posts_shortcode_args', $args, $original_atts ) );
if ( ! $listing->have_posts() )
return apply_filters( 'display_posts_shortcode_no_results', wpautop( $no_posts_message ) );
$inner = '';
while ( $listing->have_posts() ): $listing->the_post(); global $post;
$image = $date = $author = $excerpt = $content = '';
if ( $include_title )
$title = '<a class="title" href="' . apply_filters( 'the_permalink', get_permalink() ) . '">' . get_the_title() . '</a>';
if ( $image_size && has_post_thumbnail() )
$image = '<a class="image" href="' . get_permalink() . '">' . get_the_post_thumbnail( get_the_ID(), $image_size ) . '</a> ';
if ( $include_date )
$date = ' <span class="date">' . get_the_date( $date_format ) . '</span>';
if( $include_author )
$author = apply_filters( 'display_posts_shortcode_author', ' <span class="author">by ' . get_the_author() . '</span>' );
if ( $include_excerpt )
$excerpt = ' <span class="excerpt-dash">-</span> <span class="excerpt">' . get_the_excerpt() . '</span>';
if( $include_content ) {
add_filter( 'shortcode_atts_display-posts', 'be_display_posts_off', 10, 3 );
$content = '<div class="content">' . apply_filters( 'the_content', get_the_content() ) . '</div>';
remove_filter( 'shortcode_atts_display-posts', 'be_display_posts_off', 10, 3 );
}
$class = array( 'listing-item' );
$class = sanitize_html_class( apply_filters( 'display_posts_shortcode_post_class', $class, $post, $listing, $original_atts ) );
$output = '<' . $inner_wrapper . ' class="' . implode( ' ', $class ) . '">' . $image . $title . $date . $author . $excerpt . $content . '</' . $inner_wrapper . '>';
// If post is set to private, only show to logged in users
if( 'private' == get_post_status( get_the_ID() ) && !current_user_can( 'read_private_posts' ) )
$output = '';
$inner .= apply_filters( 'display_posts_shortcode_output', $output, $original_atts, $image, $title, $date, $excerpt, $inner_wrapper, $content, $class );
endwhile; wp_reset_postdata();
$open = apply_filters( 'display_posts_shortcode_wrapper_open', '<' . $wrapper . $wrapper_class . $wrapper_id . '>', $original_atts );
$close = apply_filters( 'display_posts_shortcode_wrapper_close', '</' . $wrapper . '>', $original_atts );
$return = $open;
if( $shortcode_title ) {
$title_tag = apply_filters( 'display_posts_shortcode_title_tag', 'h2', $original_atts );
$return .= '<' . $title_tag . ' class="display-posts-title">' . $shortcode_title . '</' . $title_tag . '>' . "\n";
}
$return .= $inner . $close;
return $return;
}
/**
* Turn off display posts shortcode
* If display full post content, any uses of [display-posts] are disabled
*
* #param array $out, returned shortcode values
* #param array $pairs, list of supported attributes and their defaults
* #param array $atts, original shortcode attributes
* #return array $out
*/
function be_display_posts_off( $out, $pairs, $atts ) {
$out['display_posts_off'] = true;
return $out;
}
/**
* Convert string to boolean
* because (bool) "false" == true
*
*/
function be_display_posts_bool( $value ) {
return !empty( $value ) && 'true' == $value ? true : false;
}
You'll want to edit you $output variable which is on line 243 on the code you've given above.
A simple amendment to add a static url will do fine, something like this:
$static_link = 'http://www.test.com/test';
$output = '<' . $inner_wrapper . ' class="' . implode( ' ', $class ) . '">' . $image . $title . $date . $author . $excerpt . $content . 'Read more' . '</' . $inner_wrapper . '>';
Amend this to your requirements, say adding a proper link from the database.
Hope this helps.

Exclude specific categories from category list

Below is my code for the category list displayed on this page
http://www.surefiresearch.com/blog/
I want to remove the categories 'page-seo' and 'page-seo-1'. I am trying 'exclude=cat_id' which has worked for preventing the actual posts from displaying on this page, but it doesn't work for the list of categories.
Can anybody see what I am doing wrong?
Cheers.
$taxonomy = 'category';
// get the term IDs assigned to post.
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
// separator between links
$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 . '&exclude=66,67');
$terms = rtrim( trim( str_replace( '
', $separator, $terms ) ), $separator );
// display post categories
echo $terms;
}
This is what I was looking for, the exclude command has worked
wp_list_categories('orderby=name&show_count=1&exclude=66,67,68,69,70,71&title_li=');

Categories