在woocammerce中添加新类别时创建页面

时间:2017-02-11 14:56:12

标签: php wordpress woocommerce

我想在 WooCommerce 中添加新类别时自动创建新页面。新页面slug与新类别相同。

所以我的代码是:

function programmatically_create_post() {

$author_id = 1;
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$empty = 0;

$args = array(
    'taxonomy' => $taxonomy,
    'orderby' => $orderby,
    'show_count' => $show_count,
    'pad_counts' => $pad_counts,
    'hierarchical' => $hierarchical,
    'title_li' => $title,
    'hide_empty' => $empty
);

$all_categories = get_categories( $args );
$lastCategory=$all_categories[0];
$slug =$lastCategory->slug;
$title=$lastCategory->name;
// If the page doesn't already exist, then create it

if( null == get_page_by_title( $title ) ) {

// Set the post ID so that we know the post was created successfully

$post_id = wp_insert_post(

  array(

   'post_author'   => $author_id,
    'post_name'   => $slug,
    'post_title'    => $title,
    'post_status'   => 'publish',
    'post_type'   => 'page',
      'post_slug'=> $slug

  )

);



// Otherwise, we'll stop

} else {

    // Arbitrarily use -2 to indicate that the page with the title already exists

    $post_id = -2;

} // end if
} // end programmatically_create_post


add_action('create_product_cat', 'programmatically_create_post', 10, 1);

我认为得到最后一类数据库,但它是错误的。我非常谷歌搜索,但我无法找到我的问题。

添加新类别后如何获取新类别slug?

有任何野兽方式添加新类别相同的新类别的页面吗?

1 个答案:

答案 0 :(得分:0)

您的整个代码都很好但是您只有一点优先级问题。现在,您只需要将优先级从1更改为2.

add_action('create_product_cat', 'programmatically_create_post', 10, 2);

这应该有用!