简体   繁体   中英

How do I use a PHP Short Code from custom field as an href link on Wordpress?

On my wordpress page (which I will use as a template to duplicate) I need to use a custom field 'dropbox' as an href url.

I created a PHP Code Snippet (shortcode) to use as a replacement for the url: [xyz-ips snippet="dropbox"]

Here is the PHP within the shortcode:

<?php the_field('dropbox'); ?>

Here is the code on the page:

<a href="[xyz-ips snippet=" dropbox"]"="" target="_new">download the documents</a>

This short code will not pass the url from custom field to the href. Any thoughts?

Thanks in advance.

Your shortcode should be working if it's as you describe, but you should note shortcodes need to return values, not echo them. You didn't post the code you're using to register it, so I can only assume you're echoing content instead of returning it.

With that said, I would just make the shortcode echo out the whole entire link, that way you have a bit more granular control over the whole thing:

add_shortcode( 'xyz-ips-link', function( $atts ){
    extract( shortcode_atts( array(
        'snippet' => 'dropbox',
        'text'    => 'Download the Documents', 
        'target'  => '_new',
    ), $atts ) );


    $link = sprintf( '<a href="%s" target="%s">%s</a>', get_field( $snippet ), $target, $text );

    return $link;
});

This will let you just use [xyz-ips-link] anywhere in your content,

or <?php echo do_shortcode( '[xyz-ips-link]' ); ?> <?php echo do_shortcode( '[xyz-ips-link]' ); ?> in your page templates.

It also gives you more granular control over the content of the link, such as [xyz-ips-link snippet="dropbox" text="Some Alternative Text"] .

You'll also note I'm using get_field() instead of the_field() . WordPress (and ACF) both have get_ functions that return a variable for you to use, and the_ functions which get and output the variable by default.

You can see an example of this code here , Note:I don't have ACF installed, so I replaced the href attribute)

嗨,请尝试它可能对您有用。

echo do_shortcode('dropbox');

Try it

$dropdown = get_the_field('dropbox');
echo do_shortcode($dropbox);

OR

$dropdown = get_field('dropbox');
echo do_shortcode($dropbox);

So it turns out there is a specific way to call url custom fields (ACF). I inserted the below code into a PHP Code shortcode. This worked like a charm!

    <?php 

$link = get_field('dropbox');

if( $link ): ?>

    <a class="button" href="<?php echo $link; ?>" target="_new">download documents</a>

<?php endif; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM