如何在 Wordpress 上使用自定义字段中的 PHP 短代码作为 href link?

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

在我的 wordpress 页面(我将用作复制的模板)上,我需要使用自定义字段 'dropbox' 作为 href url.

我创建了一个 PHP 代码片段(简码)来替代 url:[xyz-ips 片段="dropbox"]

这是短代码中的 PHP:

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

这是页面上的代码:

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

此短代码不会将 url 从自定义字段传递到 href。有什么想法吗?

提前致谢。

您好,请尝试它可能适合您。

echo do_shortcode('dropbox');

如果您的短代码如您所描述的那样应该可以正常工作,但您应该注意短代码需要 return 值,而不是 echo 它们。您没有 post 您用来注册它的代码,所以我只能假设您是在回应内容而不是 returning 它。

话虽如此, 我只是让短代码回显整个 link,这样你就可以对整个事情进行更精细的控制:

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;
});

这样您就可以在内容的任何地方使用 [xyz-ips-link]

<?php echo do_shortcode( '[xyz-ips-link]' ); ?> 在您的页面模板中。

它还可以让您更精细地控制 link 的内容,例如 [xyz-ips-link snippet="dropbox" text="Some Alternative Text"]

您还会注意到我正在使用 get_field() instead of the_field()。 WordPress(和 ACF)都有 get_ 函数,return 一个变量供你使用,the_ 函数获取 并输出 变量默认。

你可以看到这段代码的例子here,Note:I没有安装ACF,所以我替换了href属性)

试一试

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

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

原来有一种特定的方法可以调用 url 自定义字段 (ACF)。我将下面的代码插入到 PHP 代码简码中。这很有魅力!

    <?php 

$link = get_field('dropbox');

if( $link ): ?>

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

<?php endif; ?>