Php 使用wp\u set\u object\u术语以编程方式创建和插入wordpress产品标签

Php 使用wp\u set\u object\u术语以编程方式创建和插入wordpress产品标签,php,wordpress,woocommerce,metadata,Php,Wordpress,Woocommerce,Metadata,我有大约2000种没有标签的产品。现在我想更新这些产品的标签。我想为所有2000种产品设置post_title=tag 下面的代码适用于将自定义标记设置为产品的产品 wp_set_object_terms($productID, array('product_tag1','product_tag2','product_tag3'), 'product_tag'); 而不是使每个产品的前端工作复杂化 有人可以指导我如何使用php为我的所有产品设置标签。你可以在你的产品中循环并分配标签,可能是这样

我有大约2000种没有标签的产品。现在我想更新这些产品的标签。我想为所有2000种产品设置post_title=tag

下面的代码适用于将自定义标记设置为产品的产品

wp_set_object_terms($productID, array('product_tag1','product_tag2','product_tag3'), 'product_tag');
而不是使每个产品的前端工作复杂化


有人可以指导我如何使用php为我的所有产品设置标签。

你可以在你的产品中循环并分配标签,可能是这样的:

更新: 如果您只想在没有任何现有标记的帖子中添加标记,可以执行以下操作:

<?php
add_action('init', 'add_tags_products');

function add_tags_products()
{
    $args = array(
        'post_type' => 'products', // your product post type
        'posts_per_page' => - 1,
    );

    $posts = get_posts($args);

    foreach ($posts as $post):
        setup_postdata($post);

        // get the title of the post
        $title = get_the_title($post->ID);

        // check to see if the post has any tags
        if( ! has_term( '', 'product_tag', $post->ID ) ) :
            // create the term
            wp_set_object_terms($post->ID, array($title), 'product_tag');
        endif;

        wp_reset_postdata();
    endforeach;

}

您可以循环浏览您的产品并分配标签,可能是这样的:

更新: 如果您只想在没有任何现有标记的帖子中添加标记,可以执行以下操作:

<?php
add_action('init', 'add_tags_products');

function add_tags_products()
{
    $args = array(
        'post_type' => 'products', // your product post type
        'posts_per_page' => - 1,
    );

    $posts = get_posts($args);

    foreach ($posts as $post):
        setup_postdata($post);

        // get the title of the post
        $title = get_the_title($post->ID);

        // check to see if the post has any tags
        if( ! has_term( '', 'product_tag', $post->ID ) ) :
            // create the term
            wp_set_object_terms($post->ID, array($title), 'product_tag');
        endif;

        wp_reset_postdata();
    endforeach;

}

要将帖子标题设置为标签吗?@Mason-是。我正在使用woocommerce。我想设置post\u title=tag,其中post\u type=product@Mason-有什么指导或线索可以解决这个问题吗?你想将帖子标题设置为标签吗?@Mason-有。我正在使用woocommerce。我想设置post\u title=tag,其中post\u type=product@Mason-解决此问题的任何指导或线索我将其添加到functions.php中,但在代码运行异常良好时,它什么也没做。它只有一个小问题,它替换了旧标签。我想它应该设置标签只为产品,没有标签。例如,有空标记的产品必须添加一个条件,检查post是否包含标记。请使用相关条件更新代码。在“空标记”条件更新后,代码不工作。我将其添加到functions.php中,但在代码运行异常良好时,它什么也没有做。它只有一个小问题,它替换了旧标签。我想它应该设置标签只为产品,没有标签。例如,有空标签的产品必须添加一个条件,检查post是否包含标签。请使用相关条件更新代码。更新“空标签”条件后,代码不起作用