Error when adding custom variable

#811769
  • Resolved Jason Hodge
    Rank Math free

    I have copied the code exactly from your example “return the number of posts in the chosen taxonomy term when used in the taxonomy pages” here: https://rankmath.com/kb/variables-in-seo-title-description/

    It works well most of the time except when an archive is accessed from a different CPT created using Advanced Custom Forms.

    PHP Warning: Undefined property: WP_Post_Type::$count in XXXXX/XXXXXX/functions.php
    The line that errors is: return isset($term) ? $term->count : null;

    The whole code I have is:
    /**
    * Action: 'rank_math/vars/register_extra_replacements' - Allows adding extra variables.
    * Snippet to register variable that will return the number of posts in the current term
    */
    add_action('rank_math/vars/register_extra_replacements', function () {
    rank_math_register_var_replacement(
    'term_count',
    [
    'name' => esc_html__('Term Count', 'rank-math'),
    'description' => esc_html__('Number of posts in the current term', 'rank-math'),
    'variable' => 'term_count',
    'example' => term_count_callback(),
    ],
    'term_count_callback'
    );
    });
    function term_count_callback()
    {
    $term = get_queried_object();
    if(!empty($term)){
    return isset($term) ? $term->count : null;
    }
    }

Viewing 1 replies (of 1 total)
  • Hello,

    I apologize for the error you are encountering when adding the custom variable to your Rank Math setup. The issue seems to be related to accessing the count property of the WP_Post_Type object.

    To address this problem, you can modify your code snippet as follows:

    function term_count_callback()
    {
        $term = get_queried_object();
        if ($term instanceof WP_Term) {
            return $term->count;
        }
        return null;
    }

    By making this adjustment, you ensure that the term object is checked correctly before accessing its count property, which should prevent the PHP warning you mentioned.

    Please update your code with this modification and let me know if it resolves the issue. If you need further assistance, feel free to ask.

    Thank you for bringing this to our attention.

    Sources:
    How to Make Your Theme Rank Math Compatible » Rank Math
    Using Variables in the SEO Title and Description » Rank Math

    This is an automated reply from Rank Math Support Bot. If you need further assistance, please reply to this topic and a human support agent will reply to you shortly.

    Hello,

    Since we did not hear back from you for 15 days, we are assuming that you found the solution. We are closing this support ticket.

    If you still need assistance or any other help, please feel free to open a new support ticket, and we will be more than happy to assist.

    Thank you.

Viewing 1 replies (of 1 total)

The ticket ‘Error when adding custom variable’ is closed to new replies.