【问题标题】:Wordpress: Category Based Random Shortcode from ArrayWordpress:来自数组的基于类别的随机简码
【发布时间】:2012-11-26 02:46:12
【问题描述】:

我正试图通过建立一个附属网站进行销售,为我们的单收入家庭在这个假期赚取额外的收入。然而,经过大量研究和 WordPress 论坛的少量帮助:

http://wordpress.org/support/topic/u...3#post-3318897

我迫切需要一些 PHP 代码来根据条件类别从数组中随机选择一个 do_shortcode - 类似于 Widget Logic 插件,但用于短代码。

我正在使用:

<?php echo do_shortcode("[asle id=15]"); ?>

在我位于 www.AvengersCollectibles.com/wp 的 single.php 页面中显示我的“Azon Pro 购物清单”的简码,该简码出现在我的单个帖子页面的底部,但需要一些代码来随机显示 5 个此类中的 1 个根据 9 个类别/字符中的每一个从数组中列出。

到目前为止,推荐了以下内容:

<?php $ids = array( 43, 15, 8 ); // Default

if (in_category('Captain America')):
   $ids = array( 15, 16, 17, 19, 20 );
elseif (in_category('Spiderman')):
   $ids = array( 35, 36, 37, 39, 50, 5, 70 );
elseif (in_category('Green Hornet')):
   $ids = array( 75, 6, 22, 49 );
endif;
$id = 0;
if ( ! $id ) {
   $key = array_rand( $ids, 1 );
   $id=$ids[$key];
   echo do_shortcode("[asle id=$id]");
}

?>

但我不断收到以下错误消息:

方法未实现 不支持 GET 到 /wp/wp-admin/theme-editor.php。 此外,在尝试使用 ErrorDocument 处理请求时遇到 404 Not Found 错误。

我们将不胜感激任何帮助,我欢迎您提出的所有问题、疑虑或问题。

PS:如果您能够成功解决这个问题,我很乐意在必要时提供访问权限,并在我出售网站时提供版税。

【问题讨论】:

  • 你应该在你的“if”和“elseif”之后在要执行的代码周围加上花括号。
  • 谢谢您或您的快速回复。如果我理解正确,更像这样:
  • @ChrisHerbert - it is ok 没有大括号,这与所讨论的问题无关......
  • GWMO,根据我在下面的回答:这些错误不是来自您提供的代码。除非它在 ​​Shortcode 函数中,否则不会显示在您的问题中。

标签: php wordpress random conditional shortcode


【解决方案1】:

如果我把它放在我的functions.php:

add_shortcode( 'asle', 'so_13771287_random_shortcode' );

function so_13771287_random_shortcode( $atts ) 
{
    return 'Random ID = ' . $atts['id'];
}

以及您在single.php 中的确切代码:

<?php $ids = array( 43, 15, 8 ); // Default

if (in_category('Captain America')):
   $ids = array( 15, 16, 17, 19, 20 );
elseif (in_category('Spiderman')):
   $ids = array( 35, 36, 37, 39, 50, 5, 70 );
elseif (in_category('Green Hornet')):
   $ids = array( 75, 6, 22, 49 );
endif;
$id = 0;
if ( ! $id ) {
   $key = array_rand( $ids, 1 );
   $id=$ids[$key];
   echo do_shortcode("[asle id=$id]");
}
?>

它确实对我有用。
是的,我为测试创建了所有超级英雄类别。

短代码从每个访问的单个帖子中的对应类别中打印一个随机数。

【讨论】:

  • 亲爱的 brasofilo, 你绝对是这个假期的祝福。它似乎完美无缺——除了一个小问题。我注意到在加载新页面时,我可以在新页面顶部看到 function.php 代码,直到它完全加载。我已经在使用 WP Super Cache,还有其他建议吗?
  • 每次加载页面时,我添加到我的functions.php 文件中的上述代码会在屏幕顶部显示1-2 秒的短暂时间:屏幕截图avengerscollectibles.com/code.jpg
猜你喜欢
  • 1970-01-01
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 2012-01-02
  • 1970-01-01
相关资源
最近更新 更多