Unable to get Post meta in plugins - wordpress

I'm Trying to make a plugin that send emails with the post content to an email when admin
check the check box. I found some codes and trying to do this
The plugin creates meta box with check box custom field.
Problem:
Not able to get custom field value in the plugin using get_post_meta to check whether to send the email or not
Following is the code:
add_action('admin_init','add_metabox_post_sidebar');
add_action('save_post','save_metabox_post_sidebar');
/*
* Funtion to add a meta box to enable/disable the posts.
*/
function add_metabox_post_sidebar()
{
add_meta_box("Enable Sidebar", "Enable Sidebar", "enable_sidebar_posts", "post", "side", "high");
}
function enable_sidebar_posts(){
global $post;
$check=get_post_custom($post->ID );
$checked_value = isset( $check['post_sidebar'] ) ? esc_attr( $check['post_sidebar'][0] ) :
'no';
?>
<label for="post_sidebar">Enable Sidebar:</label>
<input type="checkbox" name="post_sidebar" id="post_sidebar" <?php if($checked_value=="yes")
{echo "checked=checked"; } ?> >
<?php
}
/*
* Save the Enable/Disable sidebar meta box value
*/
function save_metabox_post_sidebar($post_id)
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
$checked_value = isset( $_POST['post_sidebar'] ) ? 'yes' : 'no';
update_post_meta( $post_id, 'post_sidebar', $checked_value );
}
// Function that runs when a post is published
function run_when_post_published( $post ) {
$author = get_userdata($post->post_author);
$category = get_the_category();
$author_id = $post->post_author;
$author = get_the_author_meta( 'nickname', $author_id );
$title = get_the_title();
$permalink = get_permalink();
$featured = get_the_post_thumbnail_url();
$email_subject = $title;
$message = apply_filters( 'the_content', $post->post_content );
$message2=wp_strip_all_tags($message);
$message3= html_entity_decode($message2);
$headers = 'Manarty <info#example.com>';
global $wp_query;
$thePostID = $wp_query->post->ID;
$k=get_post_meta( $thePostID, 'post_sidebar', true);
if(!empty($k) ) {
$email = 'test#test.com';
wp_mail( $email, $email_subject, $message3 );
}
}
// Makes sure email only gets sent the first time a post is published
add_action('new_to_publish', 'run_when_post_published');
add_action('draft_to_publish', 'run_when_post_published');
add_action('pending_to_publish', 'run_when_post_published');

It think your problem might be here:
$k=get_post_meta( $thePostID, 'post_sidebar', true);
if in fact you already had saved 'post_sidebar' correctly it means that you don't have the correct value of $thePostID
Instead of your code try this, it works for me:
global $post;
$currentPostObject = $post;
$currentPostObjectID = $currentPostObject->ID;

Related

WooCommerce Hook - woocommerce_after_cart_item_name

I am using a function to add custom meta to products. I have used the following hooks for SHOW on Product Loop woocommerce_after_shop_loop_item and Product Single Page woocommerce_product_meta_end.
So, when applying to get the same results on CART PAGE product/item by using the hook
woocommerce_after_cart_item_name it doesn’t work with no results.
Why isn’t the hook woocommerce_after_cart_item_name working if it works with the other previous hooks mentioned?
This the code I am using. I just change the hook to make it to show in Product Loop and Product Single Page, need it to show on cart Products as well. I was just wondering why it doesn't work with cart item hook..
public function woocommerce_after_cart_item_name()
{
global $product;
if ( !PluginOptions::value('shop_season') && !PluginOptions::value('shop_car_type') )
return;
$product_id = $product->get_id();
$season = get_post_meta( $product_id, 'season', true );
$car_type = get_post_meta( $product_id, 'car_type', true );
$tips_seasons = $this->ui_tips_season();
$tips_car_types = $this->ui_tips_car_types();
?>
<div class="tyre-details tyre-tips">
<?php if ( PluginOptions::value('shop_season') && $season ): ?>
<?php echo $tips_seasons[ strtolower($season) ]; ?>
<?php endif ?>
<?php if ( PluginOptions::value('shop_car_type') && $car_type ): ?>
<?php echo $tips_car_types[ strtolower($car_type) ]; ?>
<?php endif ?>
</div>
<?php
}
It is from a plugin. I was just given this code from woocommerce support but i do not know how to complete it. He says to replace with my meta_keys in the code which I will post below here. Can you help me finish this? or tell me where I need to replace. My meta_keys are $season and $car-type but i don't know how to apply with the code provided by woocommerce.
// Display custom cart item meta data (in cart and checkout)
add_filter( 'woocommerce_get_item_data', 'display_cart_item_custom_meta_data', 10, 2 );
function display_cart_item_custom_meta_data( $item_data, $cart_item ) {
$meta_key = 'PR CODE';
if ( isset($cart_item['add_size']) && isset($cart_item['add_size'] [$meta_key]) ) {
$item_data[] = array(
'key' => $meta_key,
'value' => $cart_item['add_size'][$meta_key],
);
}
return $item_data;
}
// Save cart item custom meta as order item meta data and display it everywhere on orders and email notifications.
add_action( 'woocommerce_checkout_create_order_line_item', 'save_cart_item_custom_meta_as_order_item_meta', 10, 4 );
function save_cart_item_custom_meta_as_order_item_meta( $item, $cart_item_key, $values, $order ) {
$meta_key = 'PR CODE';
if ( isset($values['add_size']) && isset($values['add_size'][$meta_key]) ) {
$item->update_meta_data( $meta_key, $values['add_size'][$meta_key] );
}
}
I located the ClassName (class FeatureTyreTips) and added that to the code you provided. I entered this in functions.php and it said fatal error when loading the cart page. I also tried placing it in the cart.php with same results...and I tried in the same plugin file where this code came from originally. All 3 locations did not work...only difference was that it did not show fatal error when adding and activating your new code in the plugin file when loading cart page. Any ideas? grazie Vdgeatano
The "Fatal Error" is most likely due to the fact that "the non-static method cannot be called statically": PHP - Static methods
I have now corrected the code.
Considering that the class name that was missing in your code is FeatureTyreTips, the correct code to add some text after the product name is:
add_action( 'woocommerce_after_cart_item_name', 'add_custom_text_after_cart_item_name', 10, 2 );
function add_custom_text_after_cart_item_name( $cart_item, $cart_item_key ) {
// create an instance of the "PluginOptions" class
$PluginOptions = new PluginOptions();
if ( ! $PluginOptions->value( 'shop_season' ) && ! $PluginOptions->value( 'shop_car_type' ) ) {
return;
}
$product = $cart_item['data'];
$season = get_post_meta( $product->get_id(), 'season', true );
$car_type = get_post_meta( $product->get_id(), 'car_type', true );
// create an instance of the "FeatureTyreTips" class
$FeatureTyreTips = new FeatureTyreTips();
$tips_seasons = $FeatureTyreTips->ui_tips_season();
$tips_car_types = $FeatureTyreTips->ui_tips_car_types();
if ( ! $PluginOptions->value('shop_season') || ! $season ) {
$season = '';
}
if ( ! $PluginOptions->value('shop_car_type') || ! $car_type ) {
$car_type = '';
}
$html = '<div class="tyre-details tyre-tips">' . trim( $season . ' ' . $car_type ) . '</div>';
echo $html;
}
The code has been tested (where possible) and works.It needs to be added to your theme's functions.php file or in your plugin.

How to remove Author Tag from being visible in Discord's previews?

When sharing a post to Discord, the preview Discord generates shows the author name and URL. We removed all information about the author but it didn't stop the author tag from showing.
That’s done via oEmbed. Add below code in your functions.php file
add_filter( 'oembed_response_data', 'disable_embeds_filter_oembed_response_data_' );
function disable_embeds_filter_oembed_response_data_( $data ) {
unset($data['author_url']);
unset($data['author_name']);
return $data;
}
**disorc may have stored the response in cache so create new post or page and test that **
#hrak has the right idea but his answer lacks context for those of us not used to dealing with PHP.
What I ended up doing was check if there was already a filter for 'oembed_response_data' in /wp-includes/default-filters.php. Mine looked like this:
add_filter( 'oembed_response_data', 'get_oembed_response_data_rich', 10, 4 );
Add the previous line to the specified file if, for whatever reason, it isn't there already.
Afterward, I checked in wp-includes/embed.php for the get_oembed_response_data_rich function, which looked like this:
function get_oembed_response_data_rich( $data, $post, $width, $height ) {
$data['width'] = absint( $width );
$data['height'] = absint( $height );
$data['type'] = 'rich';
$data['html'] = get_post_embed_html( $width, $height, $post );
// Add post thumbnail to response if available.
$thumbnail_id = false;
if ( has_post_thumbnail( $post->ID ) ) {
$thumbnail_id = get_post_thumbnail_id( $post->ID );
}
if ( 'attachment' === get_post_type( $post ) ) {
if ( wp_attachment_is_image( $post ) ) {
$thumbnail_id = $post->ID;
} elseif ( wp_attachment_is( 'video', $post ) ) {
$thumbnail_id = get_post_thumbnail_id( $post );
$data['type'] = 'video';
}
}
if ( $thumbnail_id ) {
list( $thumbnail_url, $thumbnail_width, $thumbnail_height ) = wp_get_attachment_image_src( $thumbnail_id, array( $width, 99999 ) );
$data['thumbnail_url'] = $thumbnail_url;
$data['thumbnail_width'] = $thumbnail_width;
$data['thumbnail_height'] = $thumbnail_height;
}
return $data;
}
I just added the two lines of code that #hrak introduced in his answer to remove the author tag (name and URL) from $data before it was returned:
function get_oembed_response_data_rich( $data, $post, $width, $height ) {
(...)
if ( $thumbnail_id ) {
list( $thumbnail_url, $thumbnail_width, $thumbnail_height ) = wp_get_attachment_image_src( $thumbnail_id, array( $width, 99999 ) );
$data['thumbnail_url'] = $thumbnail_url;
$data['thumbnail_width'] = $thumbnail_width;
$data['thumbnail_height'] = $thumbnail_height;
}
unset($data['author_url']);
unset($data['author_name']);
return $data;
}
As before, add the get_oembed_response_data_rich function if it does not already exist. After about 5-10 minutes, Discord link embeds stopped showing the author tag.
Source:
http://hookr.io/filters/oembed_response_data/
https://developer.wordpress.org/reference/functions/get_oembed_response_data_rich/
I've done this by emptying the posted_by function like this article shows, in the "Use Code to Remove the Author Name" section
https://wpdatatables.com/how-to-hide-the-author-in-wordpress/
basically find the posted_by function and empty it
function twentynineteen_posted_by() {
}
endif;

metabox checkbox value is not updating

data gets updated correctly in the the database. however, when i'm in WP, the checkboxes don't get the values correctly...they all show up as unchecked. any thoughts on how to do this.
Thanks in advance
/* Fire our meta box setup function on the post editor screen. */
add_action( 'load-post.php', 'smashing_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'smashing_post_meta_boxes_setup' );
/* Meta box setup function. */
function smashing_post_meta_boxes_setup() {
/* Add meta boxes on the 'add_meta_boxes' hook. */
add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_flautist_access_save_meta', 10, 2 );
}
/* Create one or more meta boxes to be displayed on the post editor screen. */
function smashing_add_post_meta_boxes() {
add_meta_box(
'smashing-flautist-access', // Unique ID
esc_html__( 'Post Viewing Permission', 'smashing_flautist' ), // Title
'smashing_flautist_access_meta_box', // Callback function
'destinations', // Admin page (or post type)
'normal', // Context
'default' // Priority
);
}
/* Display the post meta box. */
function smashing_flautist_access_meta_box( $object, $box ) { ?>
<?php wp_nonce_field( basename( __FILE__ ), 'smashing_flautist_access_nonce' ); ?>
<table class="smashing-flautist-access">
<tr align="left">
<th>Username</th>
<th> </th>
<th>Visiblity</th>
<th> </th>
<th>Name</th>
</tr>
<?php
global $post;
$users = get_users('role=subscriber');
foreach ($users as $user) {
$user_info = get_userdata( $user->ID );
if(get_post_meta( $object->ID, 'smashing_flautist_access', true ) == $user->user_login) $ifchecked = 'checked="checked" ';
echo "<tr>";
echo "<td>$user->user_login</td><td> </td>";
echo "<td align=\"center\"><input type=\"checkbox\" name=\"smashing-flautist-access\" id=\"smashing-flautist-access\" value=\"$user->user_login\" " . $ifchecked ."/></td><td> </td>";
echo "<td>$user_info->last_name, $user_info->first_name</td><td> </td>";
echo "</tr>";
unset($ifchecked);
} ?></table>
<?php }
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_flautist_access_save_meta', 10, 2 );
/* Save the meta box's post metadata. */
function smashing_flautist_access_save_meta( $post_id, $post ) {
/* Make all $wpdb references within this function refer to this variable */
global $wpdb;
/* Verify the nonce before proceeding. */
if ( !isset( $_POST['smashing_flautist_access_nonce'] ) || !wp_verify_nonce( $_POST['smashing_flautist_access_nonce'], basename( __FILE__ ) ) )
return $post_id;
/* Get the post type object. */
$post_type = get_post_type_object( $post->post_type );
/* Check if the current user has permission to edit the post. */
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
return $post_id;
/* Get the posted data and sanitize it for use as an HTML class. */
$new_meta_value = ( isset( $_POST['smashing-flautist-access'] ) ? sanitize_html_class( $_POST['smashing-flautist-access'] ) : '' );
/* Get the meta key. */
$meta_key = 'smashing_flautist_access';
/* Get the meta value of the custom field key. */
$meta_value = get_post_meta( $post_id, $meta_key, true );
/* If a new meta value was added and there was no previous value, add it. */
if ( $new_meta_value && '' == $meta_value )
{
add_post_meta( $post_id, $meta_key, $new_meta_value, true );
$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'private' WHERE ID = ".$post_id." AND post_type ='post'"));
}
/* If the new meta value does not match the old value, update it. */
elseif ( $new_meta_value && $new_meta_value != $meta_value )
{
update_post_meta( $post_id, $meta_key, $new_meta_value );
$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'private' WHERE ID = ".$post_id." AND post_type ='post'"));
}
/* If there is no new meta value but an old value exists, delete it. */
elseif ( '' == $new_meta_value && $meta_value )
{
delete_post_meta( $post_id, $meta_key, $meta_value );
$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'public' WHERE ID = ".$post_id." AND post_type ='post'"));
}
}
Instead of:
if(get_post_meta( $object->ID, 'smashing_flautist_access', true ) == $user->user_login) $ifchecked = 'checked="checked" ';
Try:
$ifchecked = (get_post_meta( $object->ID, 'smashing_flautist_access', true ) == $user->user_login)? 'CHECKED ':'';
Using this, you can also remove the unset($ifchecked); as you are always assigning $ifchecked a new value in each iteration. The unset doesn't hurt anything, it's just not necessary.
HTH,
=C=

Trying to add a custom meta box to wordpress

I am trying to add a custom meta box to a wordpress page which stores a value in a custom field. It is not working. The meta box is displayed but when you press update the value entered ito the text box is lost and nothing is written to the wp_postmeta table (no _c3m_sponsor_ur meta_key is created)
I have adapted this from an example online. I also tried adding a die statement to see if the save post is even called but nothing dies. I also dont understand why the add_post_meta isn't being created for the page
add_action( 'add_meta_boxes', 'c3m_sponsor_meta' );
function c3m_sponsor_meta() {
add_meta_box( 'c3m_meta', 'Sponsor URL Metabox', 'c3m_sponsor_url_meta', 'page', 'side', 'high' );
}
function c3m_sponsor_url_meta( $post ) {
$c3m_sponsor_url = get_post_meta( $post->ID, '_c3m_sponsor_url', true);
if (!isset($c3m_sponsor_url))
add_post_meta($post->ID, '_c3m_sponsor_url', '', false);
echo 'Please enter the sponsors website link below';
?>
<input type="text" name="c3m_sponsor_url" value="<?php echo esc_attr( $c3m_sponsor_url ); ?>" />
<?php
}
add_action( 'save_post', 'c3m_save_project_meta' );
function c3m_save_project_meta( $post_ID ) {
die('here');
global $post;
if( $post->post_type == "page" ) {
if (isset( $_POST ) ) {
update_post_meta( $post_ID, '_c3m_sponsor_url', strip_tags( $_POST['c3m_sponsor_url'] ) );
}
}
}
Any help in fixing this is muh appreciated
Thanks a lot
This may be help you:--
add_action( 'save_post', 'c3m_save_project_meta' );
function c3m_save_project_meta( $post_ID ) {
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] )
{
if (isset( $_POST ) ) {
update_post_meta( $post_ID, '_c3m_sponsor_url', strip_tags( $_POST['c3m_sponsor_url'] ) );
}
}
}
Edited:-
You can simply use Advanced Custom Fields plugin instead of using code. This plugin much helpful for custom meta fields.

Wordpress - Meta Field Update

I created a couple meta fields in Wordpress for a Custom Post Type. They are 'Price' and 'Details'. If I got to the 'edit post' page, and i change something in one of these fields, but then decide to just leave the page by hitting 'back' in the browser or closing the window, i get a warning from my browser "are you sure you want to leave the page?". When I hit 'Yes', it erases anything that's in those 2 fields, even what was previously stored before my editing.
Any idea why this could be?
Here's some of my code in functions.php:
add_action("admin_init", "admin_init");
function admin_init()
{
add_meta_box("price", "Price", "price_field", "product", "normal", "high");
add_meta_box("details", "Details", "details_field", "product", "normal", "high");
}
function price_field()
{
global $post;
$custom = get_post_custom($post->ID);
$price = $custom["price"][0];
?>
<label>Price: $</label>
<input name="price" value="<?php echo $price; ?>" />
<?php
}
function details_field()
{
global $post;
$custom = get_post_custom($post->ID);
$details = $custom["details"][0];
?>
<label>Details:</label>
<input name="details" rows='5' value="<?php echo $details; ?>" />
<?php
}
/*--------------------------------*/
/* Save PRICE and DETAILS fields */
/*--------------------------------*/
add_action('save_post', 'save_details');
function save_details()
{
global $post;
update_post_meta($post->ID, "price", $_POST["price"]);
update_post_meta($post->ID, "details", $_POST["details"]);
}
This is because you didnt add filtering in your save details method. Remember action hook "save_post" is also called once the post is auto save in draft even if you didnt click the update or the publish button. Try this
add_action('save_post', 'save_details');
function save_details($post_id){
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// uncomment if youre using nonce
//if ( !wp_verify_nonce( $_POST['my_noncename'], plugin_basename( __FILE__ ) ) )
// return;
// Check permissions
//change the "post" with your custom post type
if ( 'post' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
//if success go to your process
//you can erase your global $post and dont use $post->ID rather change it with $post_id since its our parameter
update_post_meta($post_id, "price", $_POST["price"]);
update_post_meta($post_id, "details", $_POST["details"]);
}
NOTE: in if ( 'post' == $_POST['post_type'] ) line, change "post" to your post type

Resources