繁体   English   中英

WordPress将变量传递给另一个短代码

[英]WordPress Pass variable to another shortcode

我有来自不同开发人员的多个插件,这些插件允许我显示亚马逊产品。 他们都要求我在他们的短代码中输入亚马逊类别ID。

[amazon bestseller="1234567"]
[amz_links node="1234567"]
[amazon_toprated category="1234567"]

我在大量的页面,小部件等中使用这些短代码。我偶尔需要更改ID,并且手动更改它们是一个巨大的麻烦。

我的想法是创建我自己的短代码,例如[myamazon_id]并在其他短代码中输入该短代码: [amazon bestseller="[myamazon_id]"]

不幸的是,这似乎不起作用,因为它们是自封闭的短代码,显然不允许短代码内的短代码。

我目前的解决方案是使用一个插件,允许我在WordPress页面和小部件中使用PHP。

[insert_php]echo do_shortcode( '[amazon bestseller="'.myamazonid().'"]' );[/insert_php]

这确实有效,但我想知道是否有更好的解决方案将varible传递给短代码。 直接在页面和小部件上使用PHP实际上并不是我感觉良好的东西。

我的目标是拥有这样的东西: [amazon bestseller="[myamazon_id]"]

一个简单的解决方案就是Plugin Post Snippets 在这个插件中,您可以创建3个新的短代码,其中包含3个带有类别ID的亚马逊短代码。 现在您可以使用新创建的短代码,如果您想更改类别ID,只需在一个地方编辑即可。

这样的短代码[amazon bestseller="myamazon_id"]与下面的代码。

您不需要使用这些大括号"[""]"换行另一个短代码

function first_shortcode_amazon( $atts ) {
    $newvar = do_shortcode('['.$atts['bestseller'].']');
    return $newvar;
}
add_shortcode( 'amazon', 'first_shortcode_amazon' );


function second_shortcode_for_amazonid( $atts ) {
    global $post;
    // here i have placed global post id. you can do code to get amazon id here
    return 'AMAZON_ID=> '.$post->ID;
}
add_shortcode( 'myamazon_id', 'second_shortcode_for_amazonid' );

首先,您必须在函数中定义$ atts项,因为$ atts是一个数组。

以下是在短代码中传递变量的完整代码 -

假设您需要通过短代码显示类别的所有产品,您需要在函数文件中执行以下代码 -

     function creative_writing_func($atts) {
     $args = array(
    'post_type'      => 'product',
    'posts_per_page' => 10,
    'product_cat'    => $atts['categoryname']
);

$loop = new WP_Query( $args );

while ( $loop->have_posts() ) : $loop->the_post();
    global $product;
    echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
endwhile;

wp_reset_query();
}

add_shortcode('creative_writing_func_short', 'creative_writing_func');

现在您只需将短代码代码粘贴到模板文件或Wordpress默认编辑器中 -

[creative_writing_func_short categoryname="creative-writing-english-literature"]

我们在短代码中传递类别名称(创意 - 写作 - 英语 - 文学)。

测试了它,它的工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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