0

I am trying to fix a PHP error for adding extra fields to WordPress categories. But it gives this error:

Trying to get property of non-object in D:\MAMP\htdocs\client\wp-content\themes\custom_t\extra_category_fields.php on line 7


Here is my code:

<?php
add_action('edit_category_form_fields', 'extra_category_fields');
add_action ( 'category_add_form_fields', 'extra_category_fields');//adds 
same fields to add new cat
//add extra fields to category edit form callback function
function extra_category_fields($tag) {    //check for existing featured ID
$t_id = $tag->term_id;
$cat_meta = get_option( "category_$t_id");

The error is on line 7 which has this code: $t_id = $tag->term_id;

I shall appreciate if someone gives me a solution to this php error.

P.S. I do not consider myself an expert in PHP. I already checked this article: Reference - What does this error mean in PHP but I still could not understand a direct solution.

Thank you!

S.P
  • 1
  • 2
  • Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – ficuscr Sep 14 '17 at 20:14
  • The error is raised because $tag is not an object, so you need to see where the function is being called from to determine why it is passing a non-object into it (likely because it is empty). – i-man Sep 14 '17 at 20:43

2 Answers2

0

It seems that the variable $tag is not of type object so you can't use the -> operator on it.

Here is an easy way to see what $tag is.

echo(var_dump($tag))

https://www.w3resource.com/php/function-reference/var_dump.php

Explains what it does. It should dump all the info for that variable onto your screen.

0

It seems like the "category_add_form_fields" hook will give you as parameter a string, that is the slug of your category. Please see this : https://github.com/WordPress/WordPress/blob/4981452aba3a9804dd5a4f869e124e38853cb7cc/wp-admin/edit-tags.php#L473

The "edit_category_form_fields" hook will return you the object you want. Also this hook seems to be deprecated and would be recommend to use "category_edit_form_fields" and this has for the first parameter an object.

So you will need to check if $tag is an object or a string like this :

if( ! is_object( $tag ) ){

    $tag = get_category_by_slug( $tag );

}

Hope this helps.

George
  • 126
  • 1
  • 2