-1

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="https://example.com/objective/' . $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.

3

1 Answer 1

0

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="https://patrickmichaelregan.com/objective/' . $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.

Sign up to request clarification or add additional context in comments.

3 Comments

But I still don't understand why the $content bit in my original code did not work as intended. I'm missing something in the WP functions docs.
$content is a string representation of the enclosed content between [shortcode] and [/shortcode] (if used in this form). It doesn't ever include any information about attributes passed as part of the shortcode. See docs for add_shortcode()
@esqew I feel like you understand this content well. Please find a suitable dupe target to close with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.