繁体   English   中英

WP_Query 按标签搜索

[英]WP_Query searching by tag

我正在使用 WooCommerce 设置 WordPress,其中一个要求是进行一些集成,将另一个网站的人直接带到特定产品。 我在产品标签上设置了外部产品参考

一个示例传入查询是:

http://localhost/TestSite/search?q=9404

我写了一个简短的插件来执行此操作,但我似乎无法通过标签搜索产品

例如,您可以看到 $params 的两行,当按产品 ID 搜索时,最上面的一行(当前已注释掉)工作正常,但尝试从标签开始的最下面的行没有任何结果。 你能看出我哪里出错了吗?

PS 这是我第一次尝试使用 wordpress 插件。 它可能效率低下、安全性受到威胁或存在一些明显的问题。 我将把它提交给堆栈溢出代码审查,但我需要解决最后一个错误!

谢谢你尽你所能的帮助。 此外,如果您可以建议从标签获取产品 URL 的替代方法,我会感兴趣。

//Test Product Id: 11030
//Tag on Test Product: 9404
//http://localhost/TestSite/search?q=9404

function TagLinker() {

    if (isset($_GET['q']))
    {
        $TagNumber = $_GET['q'];

        //create the params array
        //$params = array('post_type' => 'product', 'p' => 11030);
        $params = array('post_type' => 'product', 'tag' => $TagNumber);

        $wc_query = new WP_Query($params);

        if ($wc_query -> have_posts() ) {
            $wc_query -> the_post();

            $product_id = get_the_ID();

            $url = get_permalink( $product_id );

            wp_reset_postdata();

            if ( wp_redirect( $url ) ) {exit;}
        };
    }

}

add_action( 'init', 'TagLinker' );

请试试这个:

function TagLinker(){

    if (isset($_GET['q']))
    {
        $TagNumber = $_GET['q'];
        $params=array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'tax_query' => array( array(
                            'taxonomy' => 'product_tag',
                            'field' => 'slug',
                            'terms' => $TagNumber
                        )
        ));
        $wc_query = new WP_Query($params);

        if ($wc_query -> have_posts() ) {
            $wc_query -> the_post();

            $product_id = get_the_ID($wc_query->ID);

            $url = get_permalink( $product_id );

            echo $url;
            //wp_reset_postdata();
            //if ( wp_redirect( $url ) ) {exit;}
        };
    }
}
add_action( 'init', 'TagLinker' );
$params=array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'tax_query' => array( array(
                            'tag' => $TagNumber
                        ),
        ));

你应该在数组中给出标签。 请参考开发者页面中的标签部分。 https://developer.wordpress.org/reference/classes/wp_query/

$params = array(
    'post_status'    => 'publish',
    'post_type'      => 'product',
    'tax_query'      => array(
        array(
            'taxonomy' => 'product_tag',
            'field' => 'slug',
            'terms' => $TagNumber,//this is category slug da mani
        )
    )
);

试试这段代码。 它在我的机器上工作。

暂无
暂无

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

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