Ecommerce Shopify WordPress Discussion

How can I write a custom shortcode that takes a single string as an argument?

I'm trying to create a shortcode that takes a single string as an argument, and then returns a hyperlink based on the string. In the code below, the value of $content passed to my function is always null and I can't figure out why. Where am I going wrong? function add_objective_hyperlink($atts, $content = null) { // var_dump($content); $the_objective = strtolower($content); $the_objective = str_replace(' ','-', $the_objective); $the_objective = preg_replace('/[^a-z0-9-]+/', '-', $the_objective); $the_hyperlink = '<a href="' . $the_objective . '">' . $content . '</a>'; return $the_hyperlink; } add_shortcode('obj', 'add_objective_hyperlink'); I'm passing my shortcode in like this within my post content: [obj "The Thing I Want to Do"], and I'm expecting to see a hyperlink appear in my post. My var_dump($content) always returns string(0) "", though, which of course means there's no hyperlink in my page.
I managed to get my own code working by changing the inputs to my function from ($atts, $content) to simply ($input) (which is an array), then grabbing the first element of the array, converting it to a string, and then the rest of my code works as intended. function add_objective_hyperlink($input) { $the_content = (string)$input[0]; $the_objective = $the_content; $the_objective = strtolower($the_objective); $the_objective = str_replace(' ','-', $the_objective); $the_objective = preg_replace('/[^a-z0-9-]+/', '-', $the_objective); $the_hyperlink = '<a href="' . $the_objective . '">' . $the_content . '</a>'; return $the_hyperlink; } add_shortcode('obj', 'add_objective_hyperlink'); This allows me to use [obj "The Thing I Want To Do"] as my shortcode.

December 30, 2023

Our products

The help you need, when you need it

App by Turbo Engine

3 apps • 5.0 average rating

Turbosify Speed Booster

5.0 (7)
Get better conversions by optimizing shopify store Google page speed Installed

Turbosify Translator for Wordpress Woocommerce

5.0 (74) Free Wordpress Woocommerce Plugin
Translate your wordpress website to multiple language within 1 click, no configuration needed, no No technical required

Grow your business here

Whether you want to sell products down the street or around the world, we have all the tools you need.