Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

php - Adding custom post type / post to Woocommerce

I have a personal theme "A" and I want that it can also work without Woocommerce. When Woocommerce "WC" plugin is added I would integrate A products with WC. I have a custom post type called "objects", how can I make "object" buyable throught WC?

I've alredy seen this answer on StackOverflow Adding Custom Post Types to Woocommerce Where the solution in the end gives a free (not anymore) plugin to resolve.

I'd prefer to do this thing on my own, without helps of plugin. I'm curious and a pre-package solution isn't what i'm looking for.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have created a simple tutorial as to adding it here would be too long.

To achieved your goal, your post type must have a price. That said, the custom field for price should have a meta key _price.

if you already have a meta key which is not _price, you can add a filter to woocommerce_get_price shown below.

add_filter('woocommerce_get_price','reigel_woocommerce_get_price',20,2);
function reigel_woocommerce_get_price($price,$post){
    if ($post->post->post_type === 'post') // change this to your post type
        $price = get_post_meta($post->id, "price", true); // assuming your price meta key is price
    return $price;
}

With this, you can now add any post in your post type to the cart. Do so like http://localhost/wordpress/cart/?add-to-cart=1 where 1 is the ID of your post in your post type.

sample result image after visiting that link:

reigelgallarde.me

Now, you have to setup a form like below..

<form action="" method="post">
    <input name="add-to-cart" type="hidden" value="<?php echo $post->ID ?>" />
    <input name="quantity" type="number" value="1" min="1"  />
    <input name="submit" type="submit" value="Add to cart" />
</form>

you need to have this to get "Add to Cart" button. The name of the inputs are required to be as is.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...