Wordpress: Trigger a function when a new post published - wordpress

I want a function that triggers when a new WordPress post publish.
add_action( 'publish_post', 'post_published_notification', 10, 2 );
function post_published_notification( $post_id, $post ) {
$author = $post->post_author; /* Post author ID. */
$name = get_the_author_meta( 'display_name', $author );
$email = get_the_author_meta( 'user_email', $author );
$title = $post->post_title;
$permalink = get_permalink( $post_id );
$edit = get_edit_post_link( $post_id, '' );
$to[] = sprintf( '%s <%s>', $name, $email );
$subject = sprintf( 'Published: %s', $title );
$message = sprintf( 'Congratulations, %s! Your article "%s" has been published.' . "\n\n", $name, $title );
$message .= sprintf( 'View: %s', $permalink );
$headers[] = '';
wp_mail( $to, $subject, $message, $headers );
}
I tried this one. I tried also different statuses such as save_post but I didn't get any email when the user add a new post and publish it. so it doesn't work. how can I solve this problem?

You use the publish_post hook. If get_post_meta() returns a value, it will trigger your actions to occur.
function run_on_post_publish( $post_id ) {
$post_data = get_post_meta( $post_id, 'run_once', true );
if ( ! empty( $post_data ) ) {
return;
}
// Run the action you wish to occur when a post is published
update_post_meta( $post_id, 'run_once', true );
}
add_action( 'publish_post', 'run_on_post_publish' );

Related

add wait before add action function is run

I am sending extra Mail after new woocommerce order.
I am using woo commerce_new_order hook.
Problem is that when the email arrives it hasn't had product info. I think that woocommerce_new_order hook fires before everything are stored in the database. Because if I run this with the existing order every info is included.
The question is how could I add a delay before data is fetched and email is sent?
add_action( 'woocommerce_new_order', 'extra_mail_after_new_order', 20, 1 );
function extra_mail_after_new_order( $order_id ) {
$order = wc_get_order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_name = $item->get_name();
$product_id = $item->get_product_id();
$product = wc_get_product($product_id);
$product_variation_id = $item->get_variation_id();
$product_data = $product->get_meta('extra_email')
}
add_filter('wp_mail_content_type', function( $content_type ) {
return 'text/html';
});
$to = 'mail.mail#gmail.com';
$subject = $product_name . ' uusi tilaus!';
$message = 'Order id: '. $order_id . '<br />product name: '. $product_name . '<br />product id: '. $product_id. '<br />product meta: '. $product_data. '<br />status: '. $status ;
wp_mail( $to, $subject, $message ); }
Problem was solved with this hook
woocommerce_booking_in-cart_to_pending-confirmation_notification

WooCommerce: How do I add a product thumbnail image to added to cart message?

I'm using this snippet below to slightly modify Woocommerce's added to cart message. It redirects to the cart page from product pages. I'd like to add the product's thumbnail image to that Woocommerce message notification to show it clearer to the customer what has been added to the cart. Any solutions? I've tried a bunch of different ways, but no success.
function ace_add_to_cart_message_html( $message, $products ) {
$count = 0;
$titles = array();
foreach ( $products as $product_id => $qty ) {
$titles[] = ( $qty > 1 ? absint( $qty ) . ' Ɨ ' : '' ) . sprintf( _x( 'ā€œ%sā€', 'Item name in quotes', 'woocommerce' ), strip_tags( get_the_title( $product_id ) ) );
$count += $qty;
}
$titles = array_filter( $titles );
$added_text = sprintf( _n(
'%s has been added to your cart.', // Singular
'%s are added to your cart.', // Plural
$count, // Number of products added
'woocommerce' // Textdomain
), wc_format_list_of_items( $titles ) );
$message = sprintf( '%s %s', esc_url( wc_get_checkout_url() ), esc_html__( 'Proceed to checkout', 'woocommerce' ), esc_html( $added_text ) );
return $message;
}
You can use wc_add_to_cart_message action hook. try the below code.
function add_product_image_wc_add_to_cart_message_html( $message, $product_id ){
if ( has_post_thumbnail( $product_id ) ):
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $product_id ), 'single-post-thumbnail' );
endif;
$message = sprintf( '<img src="'.$image[0].'" style="height: 50px;width: 50px;float: left;margin-right: 10px;" />%s', $message );
return $message;
}
add_filter( 'wc_add_to_cart_message', 'add_product_image_wc_add_to_cart_message_html', 10, 2 );
Tested and Works

How to get the vendor_ids for each of the vendors with products on the cart page in woocommerce

global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = $values['data']->post;
echo "<b>".$_product->post_title.'</b> <br> Quantity: '.$values['quantity'].'<br>';
$price = get_post_meta($values['product_id'] , '_price', true);
echo " Price: ".$price."<br>";
I have used the following to get data about the products on the cart and display it. is it possible to get the vendor of each product too and how can I do that in woo commerce? again from the cart page because I want to echo the vendor address back under each product on the cart page.
add_filter( 'woocommerce_get_item_data', 'wc_add_address_to_cart', 10, 2 );
function wc_add_address_to_cart( $other_data, $cart_item ) {
$post_data = get_post( $cart_item['product_id'] );
$post_data->post_author;
$vendor_id = $post_data->post_author;
echo '<br>';
$Add = 'Address: ';
$city = 'City: ';
$tel = 'Phone: ';
echo $test;
$user_id = $vendor_id;
// Get all user meta data for $user_id
$meta = get_user_meta( $user_id );
// Filter out empty meta data
$meta = array_filter( array_map( function( $a ) {
return $a[0];
}, $meta ) );
echo $Add;
print_r( $meta ['_vendor_address_1'] );
echo '<br>';
echo $city;
print_r( $meta['_vendor_city'] );
echo '<br>';
echo $tel;
print_r( $meta['_vendor_phone'] );
return $other_data;
}
Finally got what I was looking for. Just add that to the functions.php

How to add custom filed and save it in wordpress?

Following code I tried out But it is not save value of custom Fileds.
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'product', 'side', 'high' );
}
In above I have add code it is display when posttype is product
function cd_meta_box_cb( $product)
{
$values = get_post_custom( $product->ID );
$text = isset( $values['my_meta_box_text'] ) ? esc_attr($values['my_meta_box_text'][0] ) : ā€;
?>
<p>
<label for="my_meta_box_text">Text Label</label>
<input type="text" name="my_meta_box_text" id="my_meta_box_text" value="<?php echo $text; ?>" />
</p>
<?php
}
In above code it will added the metabox with textbox and if value in metabox then it is display
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $product_id )
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
}
I want to save data in a wp_postmeta table. Above code i have tried out. I am beginner in wordpress.Can any give me suggestion ?
Use This code for creating custom fields for post.
class Rational_Meta_Box {
private $screens = array(
'post',
);
private $fields = array(
array(
'id' => 'custom-field-1',
'label' => 'custom field 1',
'type' => 'text',
),
array(
'id' => 'custom-field-2',
'label' => 'custom field 2',
'type' => 'text',
),
);
/**
* Class construct method. Adds actions to their respective WordPress hooks.
*/
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
add_action( 'save_post', array( $this, 'save_post' ) );
}
/**
* Hooks into WordPress' add_meta_boxes function.
* Goes through screens (post types) and adds the meta box.
*/
public function add_meta_boxes() {
foreach ( $this->screens as $screen ) {
add_meta_box(
'my-custom-fields',
__( 'my custom fields', 'wordpress' ),
array( $this, 'add_meta_box_callback' ),
$screen,
'advanced',
'high'
);
}
}
/**
* Generates the HTML for the meta box
*
* #param object $post WordPress post object
*/
public function add_meta_box_callback( $post ) {
wp_nonce_field( 'my_custom_fields_data', 'my_custom_fields_nonce' );
echo 'its for custom fields for post typle';
$this->generate_fields( $post );
}
/**
* Generates the field's HTML for the meta box.
*/
public function generate_fields( $post ) {
$output = '';
foreach ( $this->fields as $field ) {
$label = '<label for="' . $field['id'] . '">' . $field['label'] . '</label>';
$db_value = get_post_meta( $post->ID, 'my_custom_fields_' . $field['id'], true );
switch ( $field['type'] ) {
default:
$input = sprintf(
'<input %s id="%s" name="%s" type="%s" value="%s">',
$field['type'] !== 'color' ? 'class="regular-text"' : '',
$field['id'],
$field['id'],
$field['type'],
$db_value
);
}
$output .= $this->row_format( $label, $input );
}
echo '<table class="form-table"><tbody>' . $output . '</tbody></table>';
}
/**
* Generates the HTML for table rows.
*/
public function row_format( $label, $input ) {
return sprintf(
'<tr><th scope="row">%s</th><td>%s</td></tr>',
$label,
$input
);
}
/**
* Hooks into WordPress' save_post function
*/
public function save_post( $post_id ) {
if ( ! isset( $_POST['my_custom_fields_nonce'] ) )
return $post_id;
$nonce = $_POST['my_custom_fields_nonce'];
if ( !wp_verify_nonce( $nonce, 'my_custom_fields_data' ) )
return $post_id;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
foreach ( $this->fields as $field ) {
if ( isset( $_POST[ $field['id'] ] ) ) {
switch ( $field['type'] ) {
case 'email':
$_POST[ $field['id'] ] = sanitize_email( $_POST[ $field['id'] ] );
break;
case 'text':
$_POST[ $field['id'] ] = sanitize_text_field( $_POST[ $field['id'] ] );
break;
}
update_post_meta( $post_id, 'my_custom_fields_' . $field['id'], $_POST[ $field['id'] ] );
} else if ( $field['type'] === 'checkbox' ) {
update_post_meta( $post_id, 'my_custom_fields_' . $field['id'], '0' );
}
}
}
}
new Rational_Meta_Box;
So it will create custom fields in your post type and also saved it too.
follow this for the references https://developer.wordpress.org/plugins/metadata/creating-custom-meta-boxes/
Just replace your add_action( 'save_post', 'cd_meta_box_save' ); function and put below code.
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $product_id )
{
if( isset( $_POST[ 'my_meta_box_text' ] ) ) {
update_post_meta( $product_id,'my_meta_box_text', $_POST['my_meta_box_text'] );
}
}
Full code like ( it's working fine and also save custom field in postmeta table)
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'side', 'high' );
}
function cd_meta_box_cb( $product)
{
$values = get_post_custom( $product->ID );
$text = isset( $values['my_meta_box_text'] ) ? esc_attr($values['my_meta_box_text'][0] ) : '';
?>
<p>
<label for="my_meta_box_text">Text Label</label>
<input type="text" name="my_meta_box_text" id="my_meta_box_text" value="<?php echo $text; ?>" />
</p>
<?php
}
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $product_id )
{
if( isset( $_POST[ 'my_meta_box_text' ] ) ) {
update_post_meta( $product_id,'my_meta_box_text', $_POST['my_meta_box_text'] );
}
}
Take a look at Pods.
It is a very powerful plugin for customization.
http://pods.io/

Getting orderID and total amount in Woocommerce? why so difficult?

I added this function in my themes functions.php but it just not working.. any idea what i do wrong?
function woocommerce_thankyou_fun( $order_id )
{
$order = new WC_Order( $order_id );
// $ttotal = $order->get_order_total();
//echo trim( str_replace( '#', '', $order->get_order_number() ) );
//$order_id = absint( $wp->query_vars['order-received'] );
//$order = new WC_Order($GLOBALS['post']->ID);
echo $order;
}
add_shortcode('Woocommerce-Thankyou', 'woocommerce_thankyou_fun');
Use this code to see all datamember of order object.
function woocommerce_thankyou_fun( $order_id )
{
$order = new WC_Order( $order_id );
echo "<pre>";
print_r( $order);
echo "</pre>";
die();
}
add_shortcode('woocommerce-thankyou', 'woocommerce_thankyou_fun',20,1);

Resources