Adding YOAST Open Graph Image programmatically - php

I have a problem regarding the YOAST:og images. Normally you would have to add an image manually for each post/CPT post, but I would like to add the whole thing dynamically for a CPT post. It should be noted that I would like to store a dynamic image URL, depending on what is set for the contribution/post.
I have already tried the following approach:
function add_yoast_data_when_save( $post_id, $post ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
// Don't save revisions and autosaves
if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
return $post_id;
}
$yoast_opengraph_image = get_post_meta( $post_id, '_yoast_wpseo_opengraph-image', true );
$yoast_twitter_image = get_post_meta( $post_id, '_yoast_wpseo_twitter-image', true );
if ( $post->post_type == 'news' ) {
if ( empty( $yoast_opengraph_image ) || empty( $yoast_twitter_image ) ) {
$elementor_data = get_post_meta( $post_id, '_elementor_data', true );
$all_images_array = get_all_elementor_images( $elementor_data );
if ( isset( $all_images_array['teaser'][0] ) && ! empty( $all_images_array['teaser'][0] ) ) {
if ( empty( $yoast_opengraph_image ) ) {
update_post_meta( $post_id, '_yoast_wpseo_opengraph-image', $all_images_array['teaser'][0] );
}
if ( empty( $yoast_twitter_image ) ) {
update_post_meta( $post_id, '_yoast_wpseo_twitter-image', $all_images_array['teaser'][0] );
}
}
}
}
if ( $post->post_type == 'calendar' ) {
$status = get_post_meta( $post_id, 'status', true );
if ( $status == 'normal' ) {
$image = wp_get_attachment_url( get_post_meta( $post_id, 'image', true ) );
if ( empty( $yoast_opengraph_image ) || empty( $yoast_twitter_image ) ) {
if ( empty( $yoast_opengraph_image ) ) {
update_post_meta( $post_id, '_yoast_wpseo_opengraph-image', $image );
}
if ( empty( $yoast_twitter_image ) ) {
update_post_meta( $post_id, '_yoast_wpseo_twitter-image', $image );
}
}
} else {
$elementor_data = get_post_meta( $post_id, '_elementor_data', true );
$all_images_array = get_all_elementor_images( $elementor_data );
if ( isset( $all_images_array['teaser'][0] ) && ! empty( $all_images_array['teaser'][0] ) ) {
if ( empty( $yoast_opengraph_image ) ) {
update_post_meta( $post_id, '_yoast_wpseo_opengraph-image', $all_images_array['teaser'][0] );
}
if ( empty( $yoast_twitter_image ) ) {
update_post_meta( $post_id, '_yoast_wpseo_twitter-image', $all_images_array['teaser'][0] );
}
}
}
}
}
add_action( 'save_post', 'add_yoast_data_when_save', 10, 2 );
function get_all_elementor_images( $elementor_data ) {
$all_images_array = array();
if ( ! empty( $elementor_data ) ) {
$decode_json = json_decode( $elementor_data, true );
$result = array();
array_walk_recursive(
$decode_json,
function( $value, $key ) use ( &$result ) {
if ( $key === 'url' ) {
$result[] = $value;
}
}
);
foreach ( $result as $key_image => $image ) {
$attachment_id = attachment_url_to_postid( $image );
$quote = wp_get_attachment_image_src( $attachment_id, 'quote' );
$teaser = wp_get_attachment_image_src( $attachment_id, 'teaser' );
$col_6 = wp_get_attachment_image_src( $attachment_id, 'col-6' );
$col_4 = wp_get_attachment_image_src( $attachment_id, 'col-4' );
$col_3 = wp_get_attachment_image_src( $attachment_id, 'col-3' );
$col_2 = wp_get_attachment_image_src( $attachment_id, 'col-2' );
if ( ! empty( $quote[0] ) ) {
$all_images_array['quote'][] = $quote[0] . ',';
}
if ( ! empty( $teaser[0] ) ) {
$all_images_array['teaser'][] = $teaser[0] . ',';
}
if ( ! empty( $col_6[0] ) ) {
$all_images_array['col-6'][] = $col_6[0] . ',';
}
if ( ! empty( $col_4[0] ) ) {
$all_images_array['col-4'][] = $col_4[0] . ',';
}
if ( ! empty( $col_3[0] ) ) {
$all_images_array['col-3'][] = $col_3[0] . ',';
}
if ( ! empty( $col_2[0] ) ) {
$all_images_array['col-2'][] = $col_2[0] . ',';
}
}
}
return $all_images_array;
}
As you can see, I would like to update the YOAST metadata in the post metas on the "save_post" action hook. However, YOAST overwrites this parameter every time you update the post and I can't set this post meta dynamically.
In general, this complete function should be there so that editors should not maintain this data manually, but is set dynamically when the data is saved.
I hope you can help me with this topic.
Thank you in advance.

Related

Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, string given in

The above error appears in PHP 8.0, pointing to the line of code below:
if ( isset( $attachment_metadata['sizes'] ) && count( $attachment_metadata['sizes'] ) && ( isset( $attachment_metadata['sizes'][ $intermediate_size ] ) ) ) {
Section of code for this function:
function wpsc_product_image( $attachment_id = 0, $width = null, $height = null ) {
// Do some dancing around the image size
if ( ( ( $width >= 10 ) && ( $height >= 10 ) ) && ( ( $width <= 1024 ) && ( $height <= 1024 ) ) ) {
$intermediate_size = "wpsc-{$width}x{$height}";
}
// Get image url if we have enough info
if ( $attachment_id > 0 && ! empty( $intermediate_size ) ) {
// Get all the required information about the attachment
$uploads = wp_upload_dir();
$image_meta = get_post_meta( $attachment_id, '' );
$file_path = get_attached_file( $attachment_id );
// Clean up the meta array
foreach ( $image_meta as $meta_name => $meta_value ) {
$image_meta[ $meta_name ] = maybe_unserialize( array_pop( $meta_value ) );
}
$attachment_metadata = isset( $image_meta['_wp_attachment_metadata'] ) ? $image_meta['_wp_attachment_metadata'] : null;
// Determine if we already have an image of this size
if ( isset( $attachment_metadata['sizes'] ) && count( $attachment_metadata['sizes'] ) && ( isset( $attachment_metadata['sizes'][ $intermediate_size ] ) ) ) {
$intermediate_image_data = image_get_intermediate_size( $attachment_id, $intermediate_size );
$image_url = $intermediate_image_data['url'];
} else {
$image_url = home_url( "index.php?wpsc_action=scale_image&attachment_id={$attachment_id}&width=$width&height=$height" );
}
// Not enough info so attempt to fallback
} else {
if ( ! empty( $attachment_id ) ) {
$image_url = home_url( "index.php?wpsc_action=scale_image&attachment_id={$attachment_id}&width=$width&height=$height" );
} else {
$image_url = false;
}
}
if ( empty( $image_url ) && ! empty( $file_path ) ) {
$image_meta = get_post_meta( $attachment_id, '_wp_attached_file' );
if ( ! empty( $image_meta ) ) {
$image_url = $uploads['baseurl'] . '/' . $image_meta[0];
}
}
As still relatively new to php, and still learning, would appreciate any feedback or suggestions on how to overcome this error.

Filter not working in wordpress admin panel

i am working with wordpress, and i am using wordpress plugin "glowmember", in wordpress admin panel right now i can filter data with some fields and i want to add one more
filter so i can search data by "name",Here is my current code
while ( $query->have_posts() ) : $query->the_post();
$user_categories = get_post_meta( get_the_ID(), 'glow_user_categories', true );
$user_categories_specifics = get_post_meta( get_the_ID(), 'glow_categories_specific', true ) ?: [];
$user_gender = get_post_meta( get_the_ID(), 'glow_user_gender', true );
$glow_p_applications = get_post_meta( get_the_ID(), 'glow_p_application', true ) ? get_post_meta( get_the_ID(), 'glow_p_application', true ) : [];
$glow_post_title = get_post_meta( get_the_ID(), 'glow_post_title', true ) ? get_post_meta( get_the_ID(), 'glow_post_title', true ) : []; // adding this line for get data by name
if ( isset( $_GET['city'] ) && $_GET['city'] != 'all' ) {
$city = preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities($_GET['city']));
if ( empty( $user_cities ) || ! in_array( strtolower($city), $user_cities ) ) {
continue;
}
}
if ( isset( $_GET['gender'] ) && $_GET['gender'] != 'all' ) {
if ( $_GET['gender'] != $user_gender ) {
continue;
}
}
if ( isset( $_GET['post_title'] ) && $_GET['post_title'] != 'all' ) {
if ( $_GET['post_title'] != $glow_post_title ) {
continue;
}
}
But fiter not working for me, Here is my current url (using get method but not working with "name" parameter)
http://mysiteurl/wp-admin/admin.php?page=glow-members-all-users&cat=all&city=all&state=all&gender=all&cat_spec=all&post_title=lisa

How to add filter to hide out of stock products when searching for Upsells and Cross-sells in admin panel on the Linked Products tab (in woocommerce)?

On a single product, inside the admin panel, on the Linked Products tab (on woocommerce), i can set up Up-Sells and Cross-Sells Products. I can add the product i wish to link to by searching for it.
At the moment search gives all products, even the ones that are out of stock. I would like if i write down an id of a product that is out of stock, it won't appear on the list.
The function that is responsible for json result is
public static function json_search_products_and_variations() {
self::json_search_products( '', true );
}
public static function json_search_products( $term = '', $include_variations = false ) {
check_ajax_referer( 'search-products', 'security' );
if ( empty( $term ) && isset( $_GET['term'] ) ) {
$term = (string) wc_clean( wp_unslash( $_GET['term'] ) );
}
if ( empty( $term ) ) {
wp_die();
}
if ( ! empty( $_GET['limit'] ) ) {
$limit = absint( $_GET['limit'] );
} else {
$limit = absint( apply_filters( 'woocommerce_json_search_limit', 30 ) );
}
$include_ids = ! empty( $_GET['include'] ) ? array_map( 'absint', (array) wp_unslash( $_GET['include'] ) ) : array();
$exclude_ids = ! empty( $_GET['exclude'] ) ? array_map( 'absint', (array) wp_unslash( $_GET['exclude'] ) ) : array();
$exclude_types = array();
if ( ! empty( $_GET['exclude_type'] ) ) {
// Support both comma-delimited and array format inputs.
$exclude_types = wp_unslash( $_GET['exclude_type'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
if ( ! is_array( $exclude_types ) ) {
$exclude_types = explode( ',', $exclude_types );
}
// Sanitize the excluded types against valid product types.
foreach ( $exclude_types as &$exclude_type ) {
$exclude_type = strtolower( trim( $exclude_type ) );
}
$exclude_types = array_intersect(
array_merge( array( 'variation' ), array_keys( wc_get_product_types() ) ),
$exclude_types
);
}
$data_store = WC_Data_Store::load( 'product' );
$ids = $data_store->search_products( $term, '', (bool) $include_variations, false, $limit, $include_ids, $exclude_ids );
$products = array();
foreach ( $ids as $id ) {
$product_object = wc_get_product( $id );
if ( ! wc_products_array_filter_readable( $product_object ) ) {
continue;
}
$formatted_name = $product_object->get_formatted_name();
$managing_stock = $product_object->managing_stock();
if ( in_array( $product_object->get_type(), $exclude_types, true ) ) {
continue;
}
if ( $managing_stock && ! empty( $_GET['display_stock'] ) ) {
$stock_amount = $product_object->get_stock_quantity();
/* Translators: %d stock amount */
$formatted_name .= ' – ' . sprintf( __( 'Stock: %d', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product_object ) );
}
$products[ $product_object->get_id() ] = rawurldecode( $formatted_name );
}
wp_send_json( apply_filters( 'woocommerce_json_search_found_products', $products ) );
}
Before wp_send_json(...) how can i exclude from $products array the outofstock products?
Before
$products[ $product_object->get_id() ] = rawurldecode( $formatted_name );
the code
if ('outofstock' === $product_object->get_stock_status()){
continue;
}
worked for me.

Override WordPress plugin class to change upload image size

I'm trying to change the function inside the handler class for uploading user image from front end using the the code which mostly works in situations like this one:
class Custom_Class extends Main_Class {
function __construct() {
remove_action('default_action', array($this));
add_action('new_action', array($this));
}
/* custom code from here on */
}
new Custom_Class
The goal is to change the $image->resize value to 320px, but I can not even remove the action, and the original code looks like this:
class UR_Form_Handler {
/**
* Hook in methods.
*/
public static function init() {
add_action( 'template_redirect', array( __CLASS__, 'redirect_reset_password_link' ) );
add_action( 'template_redirect', array( __CLASS__, 'save_profile_details' ) );
add_action( 'template_redirect', array( __CLASS__, 'save_change_password' ) );
add_action( 'wp_loaded', array( __CLASS__, 'process_login' ), 20 );
add_action( 'wp_loaded', array( __CLASS__, 'process_lost_password' ), 20 );
add_action( 'wp_loaded', array( __CLASS__, 'process_reset_password' ), 20 );
add_action( 'user_registration_before_customer_login_form', array( __CLASS__, 'export_confirmation_request' ) );
}
/**
* Save/update a profile fields if the form was submitted through the user account page.
*
* #return mixed
*/
public function save_profile_details() {
if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
return;
}
if ( empty( $_POST['action'] ) || 'save_profile_details' !== $_POST['action'] || empty( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'save_profile_details' ) ) {
return;
}
$user_id = get_current_user_id();
if ( $user_id <= 0 ) {
return;
}
if ( has_action( 'uraf_profile_picture_buttons' ) ) {
if ( isset( $_POST['profile_pic_url'] ) && ! empty( $_POST['profile_pic_url'] ) ) {
update_user_meta( $user_id, 'user_registration_profile_pic_url', $_POST['profile_pic_url'] );
}
} else {
if ( isset( $_FILES['profile-pic'] ) && $_FILES['profile-pic']['size'] ) {
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
$upload = $_FILES['profile-pic'];
$upload_overrides = array(
'action' => 'save_profile_details',
);
$uploaded = wp_handle_upload( $upload, $upload_overrides );
if ( $uploaded && ! isset( $uploaded['error'] ) ) {
$image = wp_get_image_editor( $uploaded['file'] );
if ( ! is_wp_error( $image ) ) {
$image->resize( 150, 150, true );
$image->save( $uploaded['file'] );
}
update_user_meta( $user_id, 'user_registration_profile_pic_url', $uploaded['url'] );
} else {
ur_add_notice( $uploaded['error'], 'error' );
}
} elseif ( UPLOAD_ERR_NO_FILE !== $_FILES['profile-pic']['error'] ) {
switch ( $_FILES['profile-pic']['error'] ) {
case UPLOAD_ERR_INI_SIZE:
ur_add_notice( __( 'File size exceed, please check your file size.', 'user-registration' ), 'error' );
break;
default:
ur_add_notice( __( 'Something went wrong while uploading, please contact your site administrator.', 'user-registration' ), 'error' );
break;
}
} elseif ( empty( $_POST['profile-pic-url'] ) ) {
$upload_dir = wp_upload_dir();
$profile_url = get_user_meta( $user_id, 'user_registration_profile_pic_url', true );
// Check if profile already set?
if ( $profile_url ) {
// Then delete file and user meta.
$profile_url = $upload_dir['basedir'] . explode( '/uploads', $profile_url )[1];
if ( ! empty( $profile_url ) && file_exists( $profile_url ) ) {
#unlink( $profile_url );
}
delete_user_meta( $user_id, 'user_registration_profile_pic_url' );
}
}
}
$form_id_array = get_user_meta( $user_id, 'ur_form_id' );
$form_id = 0;
if ( isset( $form_id_array[0] ) ) {
$form_id = $form_id_array[0];
}
$profile = user_registration_form_data( $user_id, $form_id );
foreach ( $profile as $key => $field ) {
if ( ! isset( $field['type'] ) ) {
$field['type'] = 'text';
}
// Get Value.
switch ( $field['type'] ) {
case 'checkbox':
if ( isset( $_POST[ $key ] ) && is_array( $_POST[ $key ] ) ) {
$_POST[ $key ] = $_POST[ $key ];
} else {
$_POST[ $key ] = (int) isset( $_POST[ $key ] );
}
break;
default:
$_POST[ $key ] = isset( $_POST[ $key ] ) ? ur_clean( $_POST[ $key ] ) : '';
break;
}
// Hook to allow modification of value.
$_POST[ $key ] = apply_filters( 'user_registration_process_myaccount_field_' . $key, $_POST[ $key ] );
$disabled = false;
if ( isset( $field['custom_attributes'] ) && isset( $field['custom_attributes']['readonly'] ) && isset( $field['custom_attributes']['disabled'] ) ) {
if ( 'readonly' === $field['custom_attributes']['readonly'] || 'disabled' === $field['custom_attributes']['disabled'] ) {
$disabled = true;
}
}
if ( ! empty( $_POST[ $key ] ) ) {
// Validation rules.
if ( ! empty( $field['validate'] ) && is_array( $field['validate'] ) ) {
foreach ( $field['validate'] as $rule ) {
switch ( $rule ) {
case 'email':
$_POST[ $key ] = strtolower( $_POST[ $key ] );
if ( ! is_email( $_POST[ $key ] ) ) {
ur_add_notice( sprintf( __( '%s is not a valid email address.', 'user-registration' ), '<strong>' . $field['label'] . '</strong>' ), 'error' );
}
break;
}
}
}
}
}// End foreach().
do_action( 'user_registration_after_save_profile_validation', $user_id, $profile );
if ( 0 === ur_notice_count( 'error' ) ) {
$user_data = array();
foreach ( $profile as $key => $field ) {
$new_key = str_replace( 'user_registration_', '', $key );
if ( in_array( $new_key, ur_get_user_table_fields() ) ) {
if ( $new_key === 'display_name' ) {
$user_data['display_name'] = $_POST[ $key ];
} else {
$user_data[ $new_key ] = $_POST[ $key ];
}
} else {
$update_key = $key;
if ( in_array( $new_key, ur_get_registered_user_meta_fields() ) ) {
$update_key = str_replace( 'user_', '', $new_key );
}
$disabled = isset( $field['custom_attributes']['disabled'] ) ? $field['custom_attributes']['disabled'] : '';
if ( $disabled !== 'disabled' ) {
update_user_meta( $user_id, $update_key, $_POST[ $key ] );
}
}
}
if ( count( $user_data ) > 0 ) {
$user_data['ID'] = get_current_user_id();
wp_update_user( $user_data );
}
do_action( 'user_registration_save_profile_details', $user_id, $form_id );
wp_safe_redirect( ur_get_endpoint_url( 'edit-profile', '', ur_get_page_permalink( 'myaccount' ) ) );
exit;
}
}
}
Either I get Fatal error: Cannot make static method UR_Form_Handler::save_profile_details() non static in class Custom_UR_Form_Handler, or the override doesn't work at all, I'm not sure if I'm even doing this the right way, maybe there's no need to override the entire function, but I'm stuck with this, any help or idea would be much appreciated, thanks.

Find the Function that saves the image of product variation-WooCommerce

I'm trying to update the function that handles the upload of the image to variation product
![image variation] https://i.imgur.com/reNn6x7.png
I thought that the code that handles it is :
protected function set_variation_image( $variation, $image ) {
$attachment_id = isset( $image['id'] ) ? absint( $image['id'] ) : 0;
if ( 0 === $attachment_id && isset( $image['src'] ) ) {
$upload = wc_rest_upload_image_from_url( esc_url_raw( $image['src'] ) );
if ( is_wp_error( $upload ) ) {
if ( ! apply_filters( 'woocommerce_rest_suppress_image_upload_error', false, $upload, $variation->get_id(), array( $image ) ) ) {
throw new WC_REST_Exception( 'woocommerce_variation_image_upload_error', $upload->get_error_message(), 400 );
}
}
$attachment_id = wc_rest_set_uploaded_image_as_attachment( $upload, $variation->get_id() );
}
if ( ! wp_attachment_is_image( $attachment_id ) ) {
/* translators: %s: attachment ID */
throw new WC_REST_Exception( 'woocommerce_variation_invalid_image_id', sprintf( __( '#%s is an invalid image ID.', 'woocommerce' ), $attachment_id ), 400 );
}
$variation->set_image_id( $attachment_id );
// Set the image alt if present.
if ( ! empty( $image['alt'] ) ) {
update_post_meta( $attachment_id, '_wp_attachment_image_alt', wc_clean( $image['alt'] ) );
}
// Set the image name if present.
if ( ! empty( $image['name'] ) ) {
wp_update_post(
array(
'ID' => $attachment_id,
'post_title' => $image['name'],
)
);
}
return $variation;
} `
inside the class-wc-rest-product-variations-controller.php
but any modification at this function is not changing the way that the file is uploaded.
the idea is to upload the image and apply the same variation image to each variation available, but can't find the function that saves the image to the product.
#edit after itzmekhokan reply
i created a plugin that add action to woocommerce_save_product_variation
add_action('woocommerce_save_product_variation', 'salvarfoto',10,2);
function salvarfoto($variation_id,$i){
$variation = new WC_Product_Variation($variation_id);
$produto_pai =wc_get_product( $variation->get_parent_id() );
foreach( $produto_pai->get_children() as $variation_values ){
// $variation_id = $variation_values['variation_id']; // variation id
$product = new WC_Product_Variation( $variation_values );
if( $product->get_attribute( 'pa_cor' ) == $variation->get_attribute('pa_cor'))
{
$id_img = $variation->get_image_id();
$product->set_image_id($id_img);
}
$product->save();
}
}
this code apply the same image_id to all variations that has the same color attribute
Its WC_Meta_Box_Product_Data::save_variations( $post_id, $post ) within file class-wc-meta-box-product-data.php.
And -
$errors = $variation->set_props(
array(
'image_id' => isset( $_POST['upload_image_id'][ $i ] ) ? wc_clean( wp_unslash( $_POST['upload_image_id'][ $i ] ) ) : null,
)
);
image_id basically storing the each variation image id. Check the functionalities first, then I think you can do your modifications using this do_action( 'woocommerce_save_product_variation', $variation_id, $i ); hook.

Categories