What is the problem?
Shortcodes should not echo. Tey return a string. So change yours to “return” instead of “echo”.
“The problem is that my website crashes if I make something as this even with “return”:
add_shortcode( ‘ps_tracklisting’, ‘display_tracklist’ );
function display_tracklist(){
global $product;
// Get the tracklist field value
$custom_field = get_post_meta( $product->get_id(), ‘_product_attributes’, false );
// Display
if( ! empty($custom_field) ){
$tracks = $custom_field[0][‘Tracklisting’][‘value’];
}
return ‘<span class=”track”>’ . nl2br($tracks) . ‘</span><br>’;
}
Define “crash”? Are you getting a PHP error?
Enable wp_debug and wp_debug_log and after an error, look at wp-content/debug.log to see if anything gets logged there. https://ww.wp.xz.cn/support/article/debugging-in-wordpress/
Thank you, Steven!
I also kept the (test-)PHP-snippet in my functions.php, so the error mentioned it was declared twice. Sorry for my inconvenience, I will keep enabling debug-mode througout this development.
Have a nice evening!
But the shortcode doesn’t do what it should do: this is the debug.log:
PHP Fatal error: Uncaught Error: Call to a member function get_id() on null in /Users/BigBalloo/www/wordpress.test/wp-content/themes/konte-child/functions.php:254
Stack trace:
#0 /Users/BigBalloo/www/wordpress.test/wp-includes/shortcodes.php(343): display_tracklist(”, ”, ‘ps_tracklisting’)
#1 [internal function]: do_shortcode_tag(Array)
#2 /Users/BigBalloo/www/wordpress.test/wp-includes/shortcodes.php(218): preg_replace_callback(‘/\\[(\\[?)(wpv\\-w…’, ‘do_shortcode_ta…’, ‘\n<div class=”wp…’)
#3 /Users/BigBalloo/www/wordpress.test/wp-includes/class-wp-hook.php(287): do_shortcode(‘\n<div class=”wp…’)
#4 /Users/BigBalloo/www/wordpress.test/wp-includes/plugin.php(206): WP_Hook->apply_filters(‘\n<div class=”wp…’, Array)
#5 /Users/BigBalloo/www/wordpress.test/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php(1683): apply_filters(‘the_content’, ‘<!– wp:toolset…’)
#6 /Users/BigBalloo/www/wordpress.test/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php(505): WP_REST_Posts_Controller->prep in /Users/BigBalloo/www/wordpress.test/wp-content/themes/konte-child/functions.php on line 254
Any ideas?