Updating A Post Title Using GET Method and $wpdb Class - wordpress

I have a programming exercise and I wanted to check if what I have done so far is the best way to update a post title based on setting the query string. In my example below I create a link for updating the post and validate the origin with a nonce. I used the template_redirect action as it only fires once where as the wp and parse_query actions seemed to fire multiple times. The GET request can come from a form submit or link click but I've only attached the link example but the code should work for both situations.
function update_post_title() {
global $wpdb;
$post_id = get_query_var( 'post_id', 0 );
$post_title = get_query_var( 'post_title', '' );
$post_nonce = get_query_var( 'update_post_title_nonce', '' );
if( ! empty( $post_title ) AND $post_id > 0 ) {
if ( ! wp_verify_nonce( $post_nonce, 'update_post_title_action' ) ) {
wp_die( 'Security check failed' );
}
$post_title = sanitize_text_field( $post_title );
//$post_slug = sanitize_title_with_dashes( $post_title );
$post_id = intval( $post_id );
$rows_affected = $wpdb->update(
$wpdb->posts,
array( 'post_title' => $post_title ),
array( 'ID' => $post_id ),
array( '%s'),
array( '%d' )
);
}
}
function add_custom_query_vars( $public_query_vars ) {
$public_query_vars[] = 'post_id';
$public_query_vars[] = 'post_title';
$public_query_vars[] = 'update_post_title_nonce';
return $public_query_vars;
}
add_filter( 'query_vars', 'add_custom_query_vars' );
add_action( 'template_redirect', 'update_post_title' );
Sample link generate.
global $post;
<a href="<?php echo wp_nonce_url( add_query_arg( array(
'post_id' => 123,
'post_title' => 'The New Title', ),
site_url( $post->post_name ) ),
'update_post_title_action',
'update_post_title_nonce' );
?>">Click To Update</a>

Related

Display Custom Order Filter In WooCommerce

I am trying to display a custom admin order column in WooCommerce and I am having a hard time getting the code right here.
I have this code:
add_filter( 'woocommerce_admin_order_data_after_order_details', 'display_order_data_in_admin', 10, 1);
function display_order_data_in_admin( $output )
global $wp_query
$output .= wc_product_dropdown_categories( array(
'show_option_none' => 'Filter by Location',
'taxonomy => 'product_tag',
'name' => 'product_tag',
'selectd' => isset( $wp_query->query_vars['product_tag'] ) ? $wp_query->vars['procut_tag'] :
) );
return $output;
}
I am having a hard time displaying a column for filtering my orders by location that has been selected in checkout.
add_filter( 'manage_edit-shop_order_columns', 'wc_add_new_order_admin_list_column' );
function wc_add_new_order_admin_list_column( $columns ) {
$columns['billing_country'] = 'Country';
return $columns;
}
add_action( 'manage_shop_order_posts_custom_column', 'wc_add_new_order_admin_list_column_content' );
function wc_add_new_order_admin_list_column_content( $column ) {
global $post;
if ( 'billing_country' === $column ) {
$order = wc_get_order( $post->ID );
echo $order->get_billing_country();
}
}

Generate a dropdown with woocommerce order numbers to use in contact form 7

I've been looking everywhere, but I just can't find it.
I'd like to give users a way to ask for a refund, but in order to do this, they need to provide a mandatory order number. Ideally, this would be in a tab in the My Account page, but it could also be a simple shortcode dropped into a contact form 7 form.
I just can't find any solution, anywhere.
I did find one using Gravity Form, but I'd like to do it without a plugin.
Any help would be appreciated!
You need to modify and customize below code to load dynamic orders as your requirements:
Find here code snippet:
add_action( 'wpcf7_init', 'wpcf7_add_form_tag_orderno' );
function wpcf7_add_form_tag_orderno() {
wpcf7_add_form_tag( array( 'orderno', 'orderno*' ),
'wpcf7_orderno_form_tag_handler', array()
);
}
function wpcf7_orderno_form_tag_handler( $tag ) {
/* get all orders here*/
/*$customer_orders = wc_get_orders( array(
'limit' => -1,
'status' => array( 'wc-pending' )
));
// Iterating through each Order with pending status
foreach ( $customer_orders as $order ) {
$customer_orders = wc_get_orders( array(
'limit' => -1,
'status' => array( 'wc-pending' )
) );
// Iterating through each Order with pending status
foreach ( $customer_orders as $order ) {
// Going through each current customer order items
foreach($order->get_items() as $item_id => $item_values){
$product_id = $item_values['product_id']; // product ID
// Order Item meta data
$item_meta_data = wc_get_order_item_meta( $item_id );
// Some output
echo '<p>Line total for '.wc_get_order_item_meta( $item_id, '_line_total', true ).'</p><br>';
}
}*/
$options = '';
$options .= '<option>-- select order no ---</option>';
$options .= '<option value="1">Order #10001</option>';
$options .= '<option value="2">Order #10002</option>';
$options .= '<option value="3">Order #10003</option>';
/* use attributes */
$atts = array();
$atts['class'] = $tag->get_class_option( $class );
$atts['id'] = $tag->get_id_option();
$atts['tabindex'] = $tag->get_option( 'tabindex', 'int', true );
$atts['name'] = $tag->name;
$atts = wpcf7_format_atts( $atts );
$html = sprintf(
'<span class="wpcf7-form-control-wrap %1$s">
<select name="orderno">%2$s</select></span>',
sanitize_html_class( $tag->name ), $options);
return $html;
}
Add this shortcode in your contact form 7
[orderno orderno]
I hope it will be useful for you!
Here's what I came up with, thanks a lot for the cue!
add_action( 'wpcf7_init', 'wpcf7_add_form_tag_orderno' );
function wpcf7_add_form_tag_orderno() {
wpcf7_add_form_tag( array( 'orderno', 'orderno*' ),
'wpcf7_orderno_form_tag_handler', array()
);
}
function wpcf7_orderno_form_tag_handler( $tag ) {
$customer_orders = get_posts( apply_filters( 'woocommerce_my_account_my_orders_query',
array(
'numberposts' => $order_count,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => wc_get_order_types( 'view-orders' ),
'post_status' => array_keys( wc_get_order_statuses() ),
) ) );
if ( $customer_orders ) {
$atts = array();
$atts['class'] = $tag->get_class_option( $class );
$atts['id'] = $tag->get_id_option();
$atts['tabindex'] = $tag->get_option( 'tabindex', 'int', true );
$atts['name'] = $tag->name;
$atts = wpcf7_format_atts( $atts );
echo '<select name="orderno">';
echo '<option>'.__( "Numéro de la commande", "sinope" ).'</option>';
foreach ( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order );
$item_count = $order->get_item_count();
echo '
<option value="'.$order->get_order_number().'">
'.$order->get_order_number().'
</option>
';
}
echo '</select>';
}
}

Set Author of a saved post as its parent post author

I try to change author of saved harmonogram item with author of parent but those to functions seems not to work - empty i think. When i set the author id with constant value everything works.
$parent_post_id = wp_get_post_parent_id($post_id);
$post_author_id = get_post_field( 'post_author', $post_id );
Here is whole function
function func_auto_update_post_author( $post_id ) {
$post_type = get_post_type($post_id);
if ( "harmonogram" != $post_type ) return;
//$parent_post_id = get_queried_object_id();
$parent_post_id = wp_get_post_parent_id($post_id);
$post_author_id = get_post_field( 'post_author', $parent_post_id );
$my_post = array(
'ID' => $post_id,
'post_author' => $post_author_id,
);
remove_action('save_post', 'func_auto_update_post_author');
wp_update_post($my_post);
add_action( 'save_post', 'func_auto_update_post_author');
}
add_action( 'save_post', 'func_auto_update_post_author');
Try below Code :
function func_auto_update_post_author( $post_id )
{
$post_type = get_post_type($post_id);
if ( "harmonogram" != $post_type ) return;
$parent_post_id = wp_get_post_parent_id($post_id);
if($parent_post_id)
{
$post_author_id = get_post_field( 'post_author', $parent_post_id );
$my_post = array(
'ID' => $post_id,
'post_author' => $post_author_id
);
wp_update_post($my_post);
}
}
add_action( 'save_post', 'func_auto_update_post_author');
you can track if any error occurred during post update by putting below code in above action hook:
$post_id = wp_update_post( $my_post, true );
if (is_wp_error($post_id)) {
$errors = $post_id->get_error_messages();
foreach ($errors as $error) {
echo $error;
}
}
Hope this will help!

Output error with get_post_meta in woocommerce

I am trying to add a custom metabox in woocommerce. It has been added perfectly. My ultimate goal is to call that custom field in a function and show it in the cart.php. So I coded :
For Custom field: [I would refer http://www.remicorson.com/mastering-woocommerce-products-custom-fields/] in this regard
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
woocommerce_wp_text_input(
array(
'id' => 'number_field',
'label' => __( '<strong style="color:#239804">Your Free Products</strong>', 'woocommerce' ),
'placeholder' => '',
'description' => __( 'Please enter a number', 'woocommerce' ),
'type' => 'number',
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
)
);
echo '</div>';
}//woo_add_custom_general_fields
function woo_add_custom_general_fields_save( $post_id ){
$woocommerce_number_field = $_POST['number_field'];
if( !empty( $woocommerce_number_field ) )
update_post_meta( $post_id, 'number_field', esc_attr( $woocommerce_number_field ) );
}//woo_add_custom_general_fields_save( $post_id )
It has perfectly fitted in the Product Admin Page. Now I am creating another function where I am creating a counter for cart.php
function free_products(){
global $woocommerce ,$product, $post;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$free_number = get_post_meta( $post->ID, 'number_field', true );
$free_product = $cart_item['quantity'] * $free_number;
echo apply_filters( 'woocommerce_cart_item_quantity', $free_product, $cart_item_key );
}
}
In My cart.php when I add
<td class="product-quantity">
<?php
echo free_products();
?>
</td>
The output become zero in front end. Can anyone please help me what I am going wrong. Thanks in advance.
Try below code :
function free_products(){
global $woocommerce ,$product, $post;
foreach ( WC()->cart->get_cart() as $cart_item ) {
$my_var = $cart_item['product_id'];
$free_number = get_post_meta( $my_var, 'number_field', true );
$free_product = $cart_item['quantity'] * $free_number;
echo apply_filters( 'woocommerce_cart_item_quantity', $free_product);
}
}
Let me know if It is working for you or not.Its working for me.

Add first link from post in custom field - Wordpress

I m trying to add the first link from the post content to a custom field. Something is wrong and I ve been trying to get it to work but no luck. What should I do to add the link to "link" custom field?
add_action( 'publish_post', 'check_post' );
function check_post( $post_id ) {
$user_info = get_userdata(1);
function get_first_link() {
global $post, $posts;
preg_match_all('/href\s*=\s*[\"\']([^\"\']+)/', $post->post_content, $links);
return $links[1][0];
}
$first_link = get_first_link();
add_post_meta($post_id, 'link', $first_link, true);
add_post_meta($post_id, 'users', $user_info->user_login, true);
}
EDIT
I got it working halfway. It saves the url, but it doesn't save it when the post is published. It saves it on update. What do I need to use? I tried using publish_post but that saved the url on update also.
add_action( 'save_post', 'my_save_post', 10, 2 );
function my_save_post( $post_id, $post ) {
if ( wp_is_post_revision( $post_id ) )
return;
$matches = array();
preg_match_all( '/href\s*=\s*[\"\']([^\"\']+)/', $post->post_content, $matches );
$first_link = false;
if ( ! empty( $matches[1][0] ) )
$first_link = $matches[1][0];
$user_info = get_userdata(1);
$meta_link = $_POST['link'];
$args = array(
'post__not_in'=> array($id),
'post_type' => 'post',
'post_status' => array('publish'),
'meta_query' => array(
array(
'key' => 'link',
'value' => $first_link,
'compare' => '='
)
)
);
$existingMeta = get_posts( $args );
if(empty($existingMeta)){
//Go ahead and save meta data
update_post_meta( $post_id, 'link', esc_url_raw( $first_link ) );
update_post_meta($post_id, 'users', $user_info->user_login);
}else{
//Revert post back to draft status
update_post_meta( $post_id, 'link', $existingMeta[0]->ID );
update_post_meta($existingMeta[0]->ID, 'users', $user_info->user_login);
//Now perform checks to validate your data.
//Note custom fields (different from data in custom metaboxes!)
//will already have been saved.
$prevent_publish= true;//Set to true if data was invalid.
if ($prevent_publish) {
// unhook this function to prevent indefinite loop
remove_action('save_post', 'my_save_post');
// update the post to change post status
wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
}
}
}
Here you go:
add_action( 'save_post', 'my_save_post', 10, 2 );
function my_save_post( $post_id, $post ) {
if ( wp_is_post_revision( $post_id ) )
return;
$matches = array();
preg_match_all( '/href\s*=\s*[\"\']([^\"\']+)/', $post->post_content, $matches );
$first_link = false;
if ( ! empty( $matches[1][0] ) )
$first_link = $matches[1][0];
update_post_meta( $post_id, 'link', esc_url_raw( $first_link ) );
}

Resources