Skip to content

Instantly share code, notes, and snippets.

@gdarko
Created February 5, 2023 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdarko/ab74f3e5a7a03067917c2bf54c918813 to your computer and use it in GitHub Desktop.
Save gdarko/ab74f3e5a7a03067917c2bf54c918813 to your computer and use it in GitHub Desktop.
Simple plugin that sets Digital License Manager defaults when you publish a new products. To install this, drop it in mu-plugins or plugins dir.
<?php
/**
* Plugin Name: DLM Product Defaults
* Description: Sample plugin that sets product defaults when you publish a product for a first time or create via Woo APIs.
* Author: Darko Gjorgjijoski
* Version: 1.0.0
* License: GPLv2 or later
*/
if ( ! defined( 'ABSPATH' ) ) {
return;
}
class DLM_Plugin_Product_Defaults {
/**
* Constructor
*/
public function __construct() {
add_action( 'woocommerce_new_product', [ $this, 'new_product_set_defaults' ], 10, 2 );
add_action( 'transition_post_status', [ $this, 'new_product_published_from_admin' ], 10, 3 );
}
/**
* Returns default product values
* @return array
*/
function get_product_defaults() {
return [
'dlm_licensed_product' => 1, // or 0 for no.
'dlm_licensed_product_delivered_quantity' => 1, // how much keys to be delivered upon purchase.
'dlm_licensed_product_licenses_source' => 'generators', // or 'stock', if 'stock', then the bellow generator id is not required.
'dlm_licensed_product_assigned_generator' => 1, // generator id, found in License Manager > Generators
'dlm_licensed_product_activations_behavior' => 'standard', // or 'quantity'
];
}
/**
* Set's initial Digital License Manager settings when using the WooCommerce's PHP API
*
* @param int $id
* @param \WC_Product $product
*
* @return void
*/
public function new_product_set_defaults( $id, $product ) {
$default = $this->get_product_defaults();
foreach ( $default as $key => $value ) {
$product->add_meta_data( $key, $value, true );
}
$product->save();
}
/**
* Set's initial Digital License Manager settings when publishing products from /wp-admin.
*
* @param $new_status
* @param $old_status
* @param $post
*
* @return void
*/
public function new_product_published_from_admin( $new_status, $old_status, $post ) {
if ( 'publish' === $new_status && 'draft' === $old_status ) {
if ( (int) get_post_meta( $post->ID, 'dlm_publish_flag', true ) ) {
return;
}
$product = wc_get_product( $post->ID );
if ( $product ) {
$this->new_product_set_defaults( $post->ID, $product );
}
update_post_meta( $post->ID, 'dlm_publish_flag', 1 );
}
}
}
new DLM_Plugin_Product_Defaults();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment