无法将php代码放回shortcode


Unable to put php code in return of shortcode

我需要在wordpress帖子中隐藏下载的URL。我找到了一个很好的脚本来做这件事,但它不是一个插件。我已经安装了这个脚本,并创建了一个函数来包含它。我根本不是php的专业人员。

然而,脚本通常有一行代码:

<a href="<?php downloadurl('http://yourdomainname.comdownloadables.zip','veryspecials'); ?>" >Your Downloadables</a>

我不能把这个直接放在帖子里,所以我试图为它做一个短代码,但我被卡住了。我的短代码是:

function secshort_func($atts, $content = null) {
extract(shortcode_atts(array(
    "linkurl" => '#Download_Does_Not_Exist',
    "linktitle" => 'Download',
), $atts));
return '<a href="<?php downloadurl(' .$linkurl. ','veryspecials'); ?>" >' .$linktitle. '</a>';
}
add_shortcode( 'secdown', 'secshort_func' );

我在尝试运行这个时遇到了错误,通过消除过程,我知道它来自返回代码的这一部分:

"<?php downloadurl(' .$linkurl. ','veryspecials'); ?>"

在互联网上搜索解决方案并尝试了我能想到的一切之后,我完全陷入了困境。

任何帮助都将不胜感激——我被困在这样一件小事上简直要疯了!

一些观察结果以及答案:

  1. 设置代码格式。它使故障排除时的生活更加轻松。良好的缩进是巨大的(请参阅下面的格式化代码)
  2. 不要使用隐晦/缩写的函数名。键入它们,以便创建自文档化代码
  3. 最好是而不是使用摘录。有些人说这没关系,但它可能会产生令人困惑的代码,很难解决,因为你不知道变量来自哪里。最好显式设置变量。(在您的情况下,因为您只使用它们一次,所以最简单的做法是以数组形式引用它们-$atts['link_url']
  4. 您可以调用该函数,但它必须连接到字符串中(见下文)。您的代码(以及另一个答案)将php传递到字符串中,而不是调用函数并将结果传递到字符串

格式化代码,带答案:

// Use a clearer function name.  No need for  "func", that's implied
function download_link_shortcode($atts, $content = NULL) {  
    // Declare $defaults in a separate variable to be clear, easy to read
    $defaults = array(
        "link_url"   => '#Download_Does_Not_Exist',
        "link_title" => 'Download',
    );
    // Merge the shortcode attributes
    $atts = shortcode_atts( $defaults, $atts );
    // Concatenate in the results of the `download` function call....
    return '<a href="' . downloadurl( $atts['link_url'], 'veryspecials' ) . '">' . $atts['link_title'] . '</a>';
}
add_shortcode( 'secdown', 'download_link_shortcode' );

尝试使用双外引号和转义内单引号,如下所示:

return "<a href=''<?php downloadurl(''" . $linkurl . "'',''veryspecials''); ?>'' >" .$linktitle. '</a>';