我正在尝试编写一些php来显示Woocommerce中所有当前价格(包括变体)的列表。
我对php很新,所以我不太清楚我在做什么。
我一直在使用此代码输出所有页面和产品永久链接的列表:
<?php
include "wp-load.php";
$posts = new WP_Query('post_type=any&posts_per_page=-1&post_status=publish');
$posts = $posts->posts;
/*
global $wpdb;
$posts = $wpdb->get_results("
SELECT ID,post_type,post_title
FROM {$wpdb->posts}
WHERE post_status<>'auto-draft' AND post_type NOT IN ('revision','nav_menu_item')
");
*/
header('Content-type:text/plain');
foreach($posts as $post) {
switch ($post->post_type) {
case 'revision':
case 'nav_menu_item':
break;
case 'page':
$permalink = get_page_link($post->ID);
break;
case 'post':
$permalink = get_permalink($post->ID);
break;
case 'attachment':
$permalink = get_attachment_link($post->ID);
break;
default:
$permalink = get_post_permalink($post->ID);
break;
}
echo "\n{$post->post_type}\t{$permalink}\t{$post->post_title}";
}
哪个效果很好。但我试图像这样适应它:
<?php
include "wp-load.php";
$posts = new WP_Query('post_type=any&posts_per_page=-1&post_status=publish');
$posts = $posts->posts;
/*
global $wpdb;
$posts = $wpdb->get_results("
SELECT ID,post_type,post_title
FROM {$wpdb->posts}
WHERE post_status<>'auto-draft' AND post_type NOT IN ('revision','nav_menu_item')
");
*/
header('Content-type:text/plain');
foreach($posts as $post) {
switch ($post->post_type) {
case 'revision':
global $product;
return $name.' '.$product->get_price_html();
}
echo "\n{$post->post_type}\t{$permalink}\t{$post->get_price_html}";
}
但这显然不起作用。它只输出一个帖子类型列表。
任何人都可以帮我改编一个脚本,输出一个产品名称列表及其相关价格,包括变化吗?非常感谢,我要去学习php!
答案 0 :(得分:0)
以下是您的需求:
<ul>
<?php
foreach (get_posts('post_type=product&post_status=publish') as $product) {
$product = get_product($product->ID);
if ($product->product_type == "variation")
continue;
if ($product->product_type = "variable") {
?><li><?php echo $product->post->post_title . ": " . $product->get_price_html(); ?>
<ul><?php foreach($product->get_children() as $child) { ?>
<li><?php $child_product = $product->get_child($child->variation_id);
echo $child_product->post->post_title . ": " . $product->get_price_html(); ?>
</li><?php } ?>
</ul>
</li><?php
} else {
?><li><?php
}
}
?>
</ul>