How to output attachment post meta on frontend in WordPress - php

I am creating a small plugin to add a 'data-pin-description' attribute to my images. I intend for the client to be able to add that meta data description to any image attachment from admin and then have that meta value be output to the tag on the front end, when the attachment is added to post content. I want the plugin to grab that meta data at the appropriate time and include it with the img tag data- attribute and value, before it's already output. End result should be:
My admin code seems to be accepting and saving the client-entered value just find, however I am having trouble outputting that data. One problem is I have been unable to identify which hook would retrieve and add that data to the tag at the correct time
I've tried querying the attachment posts but I don't know what action or filter to hook into
Here is how I'm adding the meta data in admin:
<?php
//exit if file is called directly
if (! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Adding a custom field to Attachment Edit Fields
* #param array $form_fields
* #param WP_POST $post
* #return array
*/
//add attachment fields
function ad_add_pinterest_fields( $form_fields, $post ) {
$field_value = get_post_meta( $post->ID, 'pin-description', true );
$form_fields['pin-description'] = array(
'value' => $field_value ? esc_textarea($field_value) : '',
'label' => __( 'Pin Description' ),
'helps' => __( 'Add a short description for Pinterest SEO' ),
'input' => 'textarea'
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'ad_add_pinterest_fields', null, 2 );
//save attachment fields
function ad_save_pinterest_fields( $attachment_id ) {
if ( isset( $_REQUEST['attachments'][$attachment_id]['pin-description'] ) ) {
$pinDescription = sanitize_text_field( $_REQUEST['attachments'][$attachment_id]['pin-description'] );
update_post_meta( $attachment_id, 'pin-description', $pinDescription );
}
}
add_action( 'edit_attachment', 'ad_save_pinterest_fields' );
?>
I expect to retrieve the post_meta of each attachment image for a given post, but have only received errors

to solve this I ended up hooking into image_send_to_editor to modify the image html prior to it's being sent to the editor. this way, with the image html in the editor and correctly displaying my attribute and value, when I click 'update post' the html is saved to the database with those pieces of data. when the post is viewed on the frontend, the output from the database correctly reflects as well.

Related

How to achieve search in code for dynamic-created text using PHP code as shortcode in WordPress?

I need to move certain articles on my website, all of them, to another unique category. I am using specific phrases which are at bottom of every article, but after code execution, only two articles are moved to a new category, not all of them.
Also when I search through all posts using the native Dashboard-All posts option, it returns only those two articles, not all of them. I assume that is because the text is not stored in the database because it shows only when the post renders itself on the front end.
How can I include dynamically created text in my code?
My code, just for reference:
<?php
// Move to the category Breaking News.
$target_category_id = 1982;
// Get all posts that contain the search phrase from Syndication.
$posts = get_posts(
array(
's' => 'and has been published here with permission',
'post_status' => 'any',
'posts_per_page' => -1, // This will retrieve all posts.
)
);
// Loop through the posts and move them to the target category.
foreach ( $posts as $post ) {
// Remove the post from any existing categories.
$current_categories = wp_get_post_categories( $post->ID );
wp_remove_object_terms( $post->ID, $current_categories, 'category' );
// Add the post to the target category.
wp_set_post_categories( $post->ID, array( $target_category_id ), true );
}
That specific phrase is created dynamically because I am using the WP Broadcast plugin to add text at the bottom of every broadcasted article, but I am not sure if that phrase is stored in a database or that text is dynamically populated (created) every time post is rendered on the frontend.
This is the code I am using to generate a message (and has been published here with permission) at the bottom of every article:
<?php
function broadcasted_from() {
// Check that Broadcast is enabled.
if ( ! function_exists( 'ThreeWP_Broadcast' ) ) {
return;
}
// Load the broadcast data for this post.
global $post;
$broadcast_data = ThreeWP_Broadcast()->get_post_broadcast_data( get_current_blog_id(), $post->ID );
// This post must be a child. Check for a parent.
$parent = $broadcast_data->get_linked_parent();
if ( ! $parent ) {
return;
}
// Fetch the permalink
switch_to_blog( $parent['blog_id'] );
$blog_name = get_bloginfo( 'name' );
$permalink = get_post_permalink( $parent['post_id'] );
restore_current_blog();
// And now assemble a text.
$r = sprintf( 'This article appeared in %s and has been published here with permission.', $permalink, $blog_name );
return $r;
}
add_shortcode( 'broadcasted_from', 'broadcasted_from' );
add_filter(
'the_content',
function( $content ) {
// Get the broadcast from the text.
$sc_text = do_shortcode( '[broadcasted_from]' );
// Add the text to the content.
$content .= $sc_text;
// Return the expanded content.
return $content;
}
);

WooCommerce: Name of short description meta field

I want to populate the short description field of a WooCommerce product with Gravity Forms.
Unfortunately I couldn't figure out the name of the meta field(?).
Every other meta field works fine. I've checked the code and some docs to find the correct name but I couldn't find it.
I tried the following: excerpt, postexcerpt, post_excerpt.
In the backend code the field's name is excerpt. To use the field's name works for every other meta field.
This snippet will make the short description / excerpt show up as a mappable field:
add_filter( 'gform_advancedpostcreation_excerpt', 'enable_excerpt', 10, 1 );
function enable_excerpt( $enable_excerpt ){
return true;
}
https://docs.gravityforms.com/gform_advancedpostcreation_excerpt/#examples
The great support over at Gravity Forms pushed me in the right direction.
You have to use a custom snippet to map the form field with short description / excerpt:
add_action( 'gform_advancedpostcreation_post_after_creation', 'update_product_information', 10, 4 );
function update_product_information( $post_id, $feed, $entry, $form ){
//update the excerpt
$the_post = array(
'ID' => $post_id,//the ID of the Post
'post_excerpt' => $entry['60'],
);
wp_update_post( $the_post );
}
Here you can find some more informations: https://docs.gravityforms.com/advanced-post-creation-add-on-using-third-party-post-types/#handling-fields-unable-to-be-mapped-2

How to parse data into meta box with multiple fields?

I successfully build a function, that is able to import data from a CSV into posts of a Custom Post Type. I am able to parse data into the native title and description fields, but the function fails to parse data into a meta box with multiple fields.
Here is a code snippet of the function that are parsing CSV data into post fields:
// Check and see if the current post exists within the database.
$check_post_exists = function( $title ) use ( $wpdb, $postTypeArray ) {
// Get an array of all posts within the custom post type
$posts = $wpdb->get_col( "SELECT post_title FROM {$wpdb->posts} WHERE post_type = '{$postTypeArray["custom-post-type"]}' AND post_status = 'publish'" );
// Check if the passed title exists in array
return in_array( $title, $posts );
}
$i = 0;
foreach ( $posts() as $post ) {
// If the post exists, skip this post and go to the next one
if ( $check_post_exists( $post["zoneid"] ) ) {
continue;
}
$i++;
// Insert the post into the database
$post["id"] = wp_insert_post( array(
"post_title" => $post["zoneid"],
"post_content" => $post["bemaerkning"],
"post_type" => $postTypeArray["custom-post-type"],
"post_punktcat" => array( 4 ),
"post_status" => "publish"
));
// Set post category to the value "4"
wp_set_post_terms($post["id"], 4, 'punktcat', false );
// Parse data into a custom field normally referred
// FOLLOWINF FUNCTION IS UPDATING EVERY FIELD OF THE META BOX WITH THE
VALUE OF '1'
update_post_meta( $post["id"], 'fredningszone_data', true );
}
echo '<div id="message" class="updated fade"><p>' . $i . ' posts have succesfully been imported from CSV!' . '</p></div>';
So the update_post_meta() function in the code snippet above does not provide the data of the zoneid into the custom field fredningszone_data[id].
The way I build my custom field and be seen within the following code snippet:
function fredningszone_meta_box() {
add_meta_box(
'punkt_fredningszone', // $id - Meta box ID (used in the 'id' attribute for the meta box).
'Data for fredningszone', // $title - Title of the meta box.
'punkt_fredningszone_callback', // $callback - Function that fills the box with the desired content. The function should echo its output.
'punkt', // $screen - he screen or screens on which to show the box (such as a post type, 'link', or 'comment').
'normal', // $context - The context within the screen where the boxes should display.
'high' // $priority - The priority within the context where the boxes should show ('high', 'low').
);
}
add_action( 'add_meta_boxes', 'fredningszone_meta_box' );
/**
* Enable and display custom fields.
**/
function punkt_fredningszone_callback() {
global $post;
$meta = get_post_meta( $post->ID, 'fredningszone_data', true ); ?>
<input type="hidden" name="fredningszone_data_nonce" value="<?php echo wp_create_nonce( basename(__FILE__) ); ?>">
<!-- All fields goes below this line -->
<p>
<label for="fredningszone_data[id]">ID</label>
<br>
<input type="text" name="fredningszone_data[id]" id="fredningszone_data[id]" class="regular-text widefat" placeholder="Indtast fredningszonens ID (f.eks 450)" value="<?php echo $meta['id']; ?>">
</p>
I will appreciate, if anyone would have a suggestion on how I could parse the data into one of the fields of my custom metabox with multiple fields.

How can I store the values from a WPForm in WordPress to a MySQL database?

How can I store the values from a WPForm in WordPress to a MySQL database?When we use WPForms where I have to add PHP part to store data? Can we store form data to tables when we are using free version of WPForms without buying it?
If you are using WP Forms Lite you can't do this directly, either you'll need to upgrade to PRO version or build your own custom save actions.
If you decide to go with your own custom version, some details below on how to intersect form submission on WP Forms.
WPForms has some actions you can use to do you own custom actions after form submission:
wpforms_process_complete
do_action( 'wpforms_process_complete', $this->fields, $entry, $form_data, $entry_id );
By using on your own template or plugin the wordpress hook add_action for any of the events described, you are able to get form data and do the handling you need.
Reference for wordpress add_action can be seen on the official documentation.
https://developer.wordpress.org/reference/functions/add_action/
Did a quick snippet that will help you get started:
add_action("wpforms_process_complete", 'function_save_custom_form_data');
function function_save_custom_form_data($params) {
foreach($params as $idx=>$item) {
$field_name = $item['name'];
$fiel_value = $item['value'];
// Do whatever you need
}
return true;
}
Please let me know if you need any further details.
WPForms store all form data in two tables within the native WordPress database. They are:
wp_wpforms_entries: In this table, the field values for entries are stored.
wp_wpforms_entry_meta: This table contains meta information about your entries such as IDs associated and the date that entries were submitted.
After publishing the form, make sure to add a form entry, so we can access the entry from your WordPress dashboard. Additionally, in your form builder, go to Settings ยป General and make sure that entry storing in WordPress is not disabled.
Create custom tables for example wpforms_entries and wpforms_entry_meta in your database to store form data. Use the provided action hook wpforms_process_complete to store the form entries.
add_action( 'wpforms_process_complete', 'process_entry', 5, 4 );
function process_entry( $form_fields, $entry, $form_data, $entry_id ) {
global $wpdb;
$form_id = $form_data['id'];
$entry_data = array(
'form_id' => $form_id,
'status' => 'publish',
'referer' => $_SERVER['HTTP_REFERER'],
'date_created' => current_time( 'mysql' )
);
// Insert into wpforms_entries custom table.
$success = $wpdb->insert( $wpdb->prefix . 'wpforms_entries', $entry_data );
$entry_id = $wpdb->insert_id;
// Create meta data.
if ( $entry_id ) {
foreach ( $form_fields as $field ) {
$field = apply_filters( 'wpforms_process_entry_field', $field, $form_data, $entry_id );
if ( isset( $field['value'] ) && '' !== $field['value'] ) {
$field_value = is_array( $field['value'] ) ? serialize( $field['value'] ) : $field['value'];
$entry_metadata = array(
'entry_id' => $entry_id,
'meta_key' => $field['name'],
'meta_value' => $field_value,
);
// Insert entry meta.
$wpdb->insert( $wpdb->prefix . 'wpforms_entrymeta', $entry_metadata );
}
}
}
}
Refrence: https://github.com/sanzeeb3/entries-for-wpforms/blob/master/includes/functions-wpfe-core.php#L59
Alternatively, the plugin itself is available: https://wordpress.org/plugins/entries-for-wpforms/
Free version of WPForms does not save the entry details captured in form. Therefore, you will need to write custom code to save the values in your custom DB table and then display them.
Below hook of WPForms can be used for saving data being entered in WPForms
/*hook to save entries coming from WPforms into database*/
add_action( 'wpforms_process_entry_save', array( $this, 'ank_wpforms_save_entries' ), 10, 4 );
public function ank_wpforms_save_entries( $fields, $entry, $form_id, $form_data ) {
//no need to sanitize data coming from WPForms as it is being sanitized in WPForms plugin before this hook using
//wpforms_process_validate_{$field_type} in class-process.php
$data = array();
$data['form_id'] = $form_id;
$data['entry_details'] = $fields;
//additional sanity checks are also performed while json encoding in "add" before adding in database
ank_wpforms_entry()->get_class_instance( 'entry-db' )->add( $data );
}
Alternatively , You can use this free plugin to save entries coming from WPForms into wordpress database and then display them in Wordpress Dashboard - https://wordpress.org/plugins/add-entries-functionality-to-wpforms/

How to get the image attachement custom link with PHP - Wordpress

This will return the link to the attachment:
$link=wp_get_attachment_link($image->ID);
However, I can't find a way to get the LINK TO value from the ATTACHMENT DISPLAY SETTINGS of an image. See screenshot below.
As yoavmatchulsky wrote, this field is dynamically filed by ~wp-includes/js/media-views.js after you manually choose an image
but if you have an id of attachment, use wp_get_attachment_link( $id, $size);
as size use 'full'
full ref. in codex
Or, if you are trying to use a custom link, the method described here might help.
Basically, in your functions.php, you could add a code similar to this:
// Adds a custom url field to your attachment
function attachment_custom_url( $form_fields, $post ) {
$form_fields['video-url'] = array(
'label' => 'CustomURL',
'input' => 'text',
'value' => get_post_meta( $post->ID, 'custom_url', true ),
'helps' => 'Add custom URL, if applicable',
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'attachment_custom_url', 10, 2 );
function attachment_custom_url_save( $post, $attachment ) {
if( isset( $attachment['custom-url'] ) )
update_post_meta( $post['ID'], 'custom_url', esc_url( $attachment['custom-url'] ) );
return $post;
}
add_filter( 'attachment_fields_to_save', 'attachment_custom_url_save', 10, 2 );
And then, you could call it in your php like so:
<?php
Custom Link;
?>
I know this is an old thread, but I solve this by getting the post meta of the attachment, which was easier to me.
In my installation, custom URL input is shown like this:
<input type="text" class="text" id="attachments-140443-foogallery_custom_url" name="attachments[140443][foogallery_custom_url]" value="https://mycustomurl.com">
So, I assumed that if the first brackets contains the post ID, the second one is a meta key to save this value on wp_postmeta table. And there it was, just starting with the underscore character so it would be a hidden meta data. Therefore, the easier way to get this value is like this:
get_post_meta( get_post_thumbnail_id( get_the_ID() ), '_foogallery_custom_url', true);
Of course you need to check if the post does have a thumbnail, but that's easy to adapt.

Categories