向post_content添加两个json字段

时间:2017-01-11 作者:timholz

我对php的知识有限,下面是场景和我的问题:我正在导入一个json文件,以便以编程方式生成产品。这一切都很好。唯一的问题是,我有两个json字段,我想将它们都插入到产品描述中。

这是我使用的函数:

function insert_product ($product_data) {
$title = $product_data[\'title\'];
//$subtitle = $product_data[\'title\'][\'b029\'];

if (!get_page_by_title($title, \'OBJECT\', \'product\')){
$post = array( // Set up the basic post data to insert products

    \'post_author\'  => 1,
    \'post_content\' => $product_data[\'note\'],
    //instead of putting note2 into post_excerpt i\'d prefer to have it in post_content
    \'post_excerpt\' => $product_data[\'note2\'],
    \'post_status\'  => \'publish\',
    \'post_title\'   => $product_data[\'title\'],
    \'post_type\'    => \'product\',
);


$post_id = wp_insert_post($post); // Insert the post returning the new post id

if (!$post_id) // If there is no post id something has gone wrong so don\'t proceed
{
    return false;
}


    update_post_meta($post_id, \'_price\', $product_data[\'price\']);
    update_post_meta($post_id, \'_regular_price\', $product_data[\'price\']);
    update_post_meta( $post_id,\'_visibility\',\'visible\'); // Set the product to visible, if not it won\'t show on the front end
    $cat_ids = array( 40 );
    wp_set_object_terms($post_id, $cat_ids, \'product_cat\'); // Set up its categories
    wp_set_object_terms($post_id, \'single\', \'product_type\'); // Set it to a single product type

    }

function insert_products ($products)  {
if (!empty($products)) // No point proceeding if there are no products
{
    array_map(\'insert_product\', $products);
}
}

function do_products(){
    $json_file = file_get_contents(\'file.json\');
    strip_tags($json_file, \'.\');
    $products_data = json_decode($json_file, true);


    insert_products($products_data);

}
add_action(\'init\',\'do_products\',100);
如何将两个json字段或其调用的任何内容合并为一个:

"note": "fdsfsdfdsfsdfsd",
"note2": "dsadsadasdasd,
我想将它们添加到:

post_content
我尝试过:

\'post_content\' => array($product_data[\'note\'],$product_data[\'note2\']),
这将返回警告:

Warning: strpos() expects parameter 1 to be string, array given in /Applications/MAMP/htdocs/wordpress/wp-includes/formatting.php on line 2137
然后:

\'post_content\' => $product_data[array_merge([\'note1\'] ,[\'note2\'])],
下一个警告:

 Warning: Illegal offset type in /Applications/MAMP/htdocs/wordpress/wp-content/plugins/insert books/insert_database_books.php on line 25   
有没有办法合并“note”和“note2”,然后将其添加到post\\u内容中?感谢您的关注。西奥

1 个回复
SO网友:timholz

这就是解决方案:

\'post_content\' => $product_data[\'note\'] . \'<br>\'. $product_data[\'note2\'],
这将串联字符串“note”和“note2”。谢谢你的提示。