使用MySQL预先添加特定产品类别的产品名称

时间:2017-04-16 23:05:42

标签: php sql wordpress woocommerce product

在WooCommerce中,我想在产品名称中添加几个字符,因此它们与客户端的QB SKU相匹配。

相关产品属于同一产品类别。我希望有一个mySql查询/命令,我可以调整一下这个可怜的伪代码:

表格中的

wp_posts,其中category =" a product category" PREPEND" abc _"到产品名称。

任何想法?

感谢。

2 个答案:

答案 0 :(得分:1)

更新:我不是SQL专家,但它肯定会帮助您了解如何构建完整的SQL查询。

  

在下面的末尾,你会发现一个你将运行一次的自定义功能,它将完成这项任务。

  1. 获取您的产品类别ID ...
  2. 在“wp_term_taxonomy”表中检查相应的'term_taxonomy_id'(通常与产品类别ID相同)。
  3. 以下是获取此特定类别的产品ID数组的方法:

    global $wpdb;
    
    // Define HERE the corresponding 'term_taxonomy_id' of your product category.
    $term_taxonomy_id = 11;
    
    $table_name = $wpdb->prefix . "term_relationships";
    $product_ids = $wpdb->get_col( "
        SELECT object_id  
        FROM $table_name 
        WHERE `term_taxonomy_id` = $term_taxonomy_id 
        ORDER BY $table_name.object_id ASC
    " );
    

    经过测试和工作

    使用该代码,您可以创建一个能够实现您想要的功能的功能:

    function prepending_products_names(){
    
        global $wpdb;
    
        // Define HERE the corresponding 'term_taxonomy_id' of your product category.
        $term_taxonomy_id = 11;
    
        $table_name = $wpdb->prefix . "term_relationships";
        $product_ids = $wpdb->get_col( "
            SELECT object_id
            FROM $table_name
            WHERE `term_taxonomy_id` = $term_taxonomy_id
            ORDER BY $table_name.object_id ASC
        " );
    
        foreach( $product_ids as $product_id ){
            // get the post object
            $post_obj = get_post($product_id);
            // get the product sku
            $product_sku = get_post_meta( $product_id, '_sku', true);
            // Customizing the product name
            // (You can prepend the a part of the sku to it)
            $custom_product_name = 'abc_'. $post_obj->post_title;
    
            // Updating the product name
            wp_update_post( array(
                'id' => $product_id,
                'post_title' => $custom_product_name,
            ) );
        }
    }
    
    // Run this one time reloading a backend page and comment it 
    // (or remove the code aftewards).
    
    if(is_admin())
        prepending_products_names();
    

    代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。

    此代码经过测试并有效。

答案 1 :(得分:1)

您希望获得当前的产品类别ID

/// <summary>
/// Deep insert parent and child.
/// </summary>
/// <param name="parentEntityPluralName"></param>
/// <param name="entity"></param>
public TEntity SaveWithChildren<TEntity>(string parentEntityPluralName, TEntity entity) where TEntity : BaseEntityType
{
    // need to serialize the entity so that we can send parent and child together
    string serializedEntity = Newtonsoft.Json.JsonConvert.SerializeObject(entity, new Newtonsoft.Json.JsonSerializerSettings() { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore });

    // create a handler for the httpclient
    using (System.Net.Http.HttpClientHandler httpHandler = new System.Net.Http.HttpClientHandler())
    {
        // create the httpclient and add the handler
        using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(httpHandler))
        {
            // setup the headers
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Prefer", @"odata.include-annotations=""*""");
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json;odata.metadata=minimal");

            // setup the content to send
            using (System.Net.Http.StringContent odataContent = new System.Net.Http.StringContent(serializedEntity))
            {
                // setup the content type to json
                odataContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                // post the data to the odata service
                using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsync(this.BaseUri + parentEntityPluralName, odataContent).Result)
                {
                    // get back any errors or content
                    string content = response.Content.ReadAsStringAsync().Result;

                    // show error if service failed
                    if (response.IsSuccessStatusCode == false)
                    {
                        throw new Exception(content);
                    }

                    // try to convert the object back from the service call
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<TEntity>(content);
                }
            }
        }
    }
}

然后使用此选项根据产品类别设置值。

<?php 
session_start();

$dbserver = 'localhost';
    $dbname = '########';
    $dbuser = '########';
    $dbpassword = '########';

    $category = $_GET['category'];
    $db = mysqli_connect($dbserver, $dbuser, $dbpassword, $dbname);

    if (mysqli_connect_errno()) {
        die("Connection failed: " . mysqli_connect_error());
    }
    mysqli_select_db($db, $dbname);
    $sql = "SELECT * FROM products WHERE category = '".$category."'";
    $result = mysqli_query($db, $sql);

    if (!$result) {
        die ('Error: Could not select products'.mysqli_error($db));
    } 

   function make_size_select($product) {
    echo '<select name="unit_menu">';
    $price_set = array(
        'halfpint'=>$product['halfpint'],
        'pint'=>$product['pint'],
        'dk'=>$product['dk'],
        'quart'=>$product['quart']);

    $handles = array(
        'halfpint'=>'Half Pint (8 oz)',
        'pint'=>'Pint (16 oz)',
        'dk'=>'Dutch Kettle (16 oz)',
        'quart'=>'Quart (32 oz)');

    foreach ($price_set as $key=>$value) {
        if ( $value > 0.00) {
            echo '<option value="'.$value.'">'.$handles[$key].'</option>';
        }
    }
    echo '</select>';
}
?>

<!DOCTYPE HTML>
<html>
<head>
  <title>Smoky Mountain Honey House</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link href="../css/style.css" rel="stylesheet" type="text/css"  media="all" />
  <link href="../css/custom.css" rel="stylesheet" type="text/css"  media="all" />
  <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
  <script type="text/javascript" src="../js/jquery-1.9.0.min.js"></script>
  <script type="text/javascript" src="../js/menu.js"></script> 
  <script>
  $(window).load(function() {
    var product = $.getJSON(<?php echo json_encode($result); ?>);
    showUnitPrice(product);
    showRowTotal(product);
  });

   // show the price for a single unit based on current values for unit_size and unit_type
  function setUnitPrice(product) {
    // get the value for unit_type
    var item_type = $.closest('.unit_type');
    // get the value for unit size
    var item_size = $.closest('.unit_size');

    // Get the base price for the item
    var unit_price = Object.keys(product[item_size]);

    // If the unit type is 'ind', divide the price by 12
    if (item_type.value == "ind") {
        unit_price = unit_price / 12;
    }

    return unit_price;
 }

 function showUnitPrice(product) {
    var unit_price = setUnitPrice(product);
    $(this).closest('.unit_price').val(unit_price);
 }

 function showRowTotal(product) {
    var unit_price = setUnitPrice(product);
    var row_price = unit_price * $(this).closest('.qty').value;
    $(this).closest('row_price').val(row_price);
 }



    </script>
 </head>
<body>
    <!----start-header----->

<div class="header_img">
     <div class="himage_half"><img src="../images/honeyhouse-1.jpg" alt="" /></div>
    <div class="himage_half">
        <script>
        $(document).load() {
            $(this).load('template/js/cart/cart.html');
        }
</script>
</div>
</div>
<div class="wrap">
    <div class="header">                
        <div class="logo">
            <a href="../index.php"><img src="../images/logo.png" alt=""></a>
        </div>
        <div class="menu">
          <nav class="clearfix">
            <ul class="clearfix">
                <li><a href="../index.html">HOME</a></li>
                <li><a href="../about.html">ABOUT</a></li>
                <li><a href="../locations.html">LOCATIONS</a></li>
                <li><a href="../shop.html">SHOP</a></li>
                <li><a href="../contact.html">CONTACT</a></li>
            </ul>
            <a href="#" id="pull">Menu</a>
          </nav>
        </div>
    </div>

   <!----End-header----->

<div class="wrap">
    <div class="content">
    <?php 
    while ($row = mysqli_fetch_assoc($result)) {
    $products[] = $row;
    foreach ($products as $product) { ?>
        <div class="product_row">
        <form name="order_row_<?php echo $product['product_id']; ?>" action="#" method="post">
            <div class="product_cell product_id">
                <input type="hidden" name="product_id" value="<?php echo $product['product_id']; ?>">
                <?php echo ucfirst($product['name']); ?>
            </div>
            <div class="product_cell">
                <select name="unit_type" onChange="showUnitPrice(product);">
                    <option value="ind" selected>By the Jar</option>
                    <option value="case">By the Case</option>
                </select>
            </div>
            <div class="product_cell unit_menu"">
                <?php echo make_size_select($product); ?>
            </div>
            <div class="product_cell qty">
                <input type="number" name="qty" max="11" label="How many?" />
            </div>
            <div class="product_cell unit-price"></div>
            <div class="product_cell row-price"></div>
            <div class="product_cell">
                <button class="add-to-cart" onclick="addToCart();">Add To Cart</button>
            </div>
        </form>
        </div>
    <?php }}; ?>

  </div> 
  </div>


<div class="copy-right">
        <p>&copy; 2016 Smoky Mountain Honey House</p>
        <p>Template by <a href="http://w3layouts.com/"> W3layouts</a></p>
</div>
 <!---End-footer---->

</body>
</html>

现在让我们把它放在一起并挂钩一个函数,用你为变量global $post; $terms = get_the_terms( $post->ID, 'product_cat' ); foreach ($terms as $term) { $category_id = $term->term_id; break; } 选择的值附加的新标题替换你当前的标题

if ($category_id == "1"){
        $sku = "your_value_if_current_cat_id_is_2";
}elseif ($category_id == "2"){
        $sku = "your_value_if_current_cat_id_is_2";
}else{
        $sku = "your_value_for_all_other_categories";
}

将该函数放入functions.php文件