lschuyler / glossary

Glossary plugin.
0 stars 0 forks source link

Why does specifying the parameter type cause a fatal error? #1

Closed lschuyler closed 2 years ago

lschuyler commented 2 years ago

On this line: https://github.com/lschuyler/glossary/blob/a19823e18770dd2fb0932a1b1a9c2563363416ff/wpvip-glossary.php#L123 if I specify array as the parameter type, it results in a fatal error:

Fatal error: Uncaught Error: Argument 1 passed to WPVIP_Glossary::create_glossary_shortcode() must be of the type array, string given, called in /.../public/wp-includes/shortcodes.php on line 356
in /.../public/wp-content/plugins/wpvip-glossary/wpvip-glossary.php on line 123

Why?

lschuyler commented 2 years ago

I think I'm doing it wrong.

I have too much in that create_glossary_shortcode function.

The docs for add_shortcode say: "Note that the function called by the shortcode should never produce an output of any kind. " But I'm not only outputting, but querying the database, and never returning anything to the add_shortcode function.

I better rework this.

lschuyler commented 2 years ago

This is a better model to follow: https://developer.wordpress.org/plugins/shortcodes/shortcodes-with-parameters/

I'm replacing all the echo's with a string concatenation, and then returning that string from the create_glossary_shortcode method.

lschuyler commented 2 years ago

OK fixed that, but still have this happening:

[09-Mar-2022 17:53:25 UTC] PHP Fatal error:  Uncaught TypeError: Argument 1 passed to WPVIP_Glossary::create_glossary_shortcode() must be of the type array, string given, called in /.../wp-includes/shortcodes.php on line 356 and defined in /.../wp-content/plugins/wpvip-glossary/wpvip-glossary.php:128
Stack trace:
#0 /.../wp-includes/shortcodes.php(356): WPVIP_Glossary->create_glossary_shortcode('', '', 'glossary')

So it is passing a '' for the $atts value which is causing the problem. When I specify at least one attribute in the shortcode, like [glossary thumbnails="yes"] it works fine. Can I set up the empty value to be an array somehow?

lschuyler commented 2 years ago

I think the only option is to make the type for $atts mixed, and then do something like this at the start of that method:

// if no attributes specified in shortcode by user, an empty string is passed for the $atts value. Switch it to an array.
        if ( $atts == '' ) {
            $atts = [];
        }
lschuyler commented 2 years ago

Fixed in https://github.com/lschuyler/glossary/commit/e54b1b9fa98c383df50d6ae3169a538b88520b7d.