0

I will try to explain my question as good as possible. but since english is not my main language I hope you will understand.

Im trying to fill a carrousel with a custom post type. if got everything working except a read more button. which will take you to the single-post.

Now I'm trying to add it through a short code that I can add to the place where I load the metadata (this is from the backend of WordPress and not via a php file on the server..)

The only problem with my current setup is that I have to fill in the id every time I make a post like: [permalink id=131] I would like to have a short code that also gets the id from the db. so that my short code will only be [permalink]. So I can add it once to the loop.

Atm I'm using the following code in my functions.php:

function my_permalink_shortcode( $atts ) {

    $id = intval($atts['id']);
    if ($id <= 0) { return; }
    
    // Check that $id has a URL.
    $url = get_permalink($id);
    if ($url == '') { return; }
    
    // Get link option and title.
    $link = ($atts['link'] == '1') ? true : false;
    $title = (trim($atts['title']) == '') ? get_the_title($id) : $atts['title'];
    
    // Determine if we create a link.
    if ($link) {
        return '<a href="'.$url.'">'.$title.'</a>'; 
    } else {
        return $url;
    }
} 
add_shortcode('permalink', 'my_permalink_shortcode');

Thanks for reading. Kind regards. Mark

3
  • I've edited some tweaks into your question, but I would add that you should always return a string, even if it's an empty string, replace return; with return '';. I suspect all you need to do is remove if ($id <= 0) { return; } as a value of 0 will be interpreted as meaning the current post
    – Tom J Nowell
    Apr 5 at 13:55
  • Hi Tom, Thanks for changing the code and your response, i added the new code to my functions.php. and removed the if ($id <= 0) { return; } line. But i still need to input the id in the shortcode, otherwise it will return a link of the current page.
    – Mark
    Apr 5 at 17:38
  • I don't understand, if you do not provide an ID then how will it know which ID to use? Are you using this inside another shortcode that fetches posts and hoping that nested shortcodes provide some kind of context you can fetch an ID from to save typing it out? If so I'm really sorry but that's not how this works. You can either get the current post, or, you can tell it which post, what you're hoping to do is not possible. Perhaps if you provide more context for what you're doing then your question would be clearer? Do you have an example of this carousel and the permalink shortcode together?
    – Tom J Nowell
    Apr 5 at 20:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.