Hello,
we want our users to be able to upload posts to our blog from the front-end (using the great gravity forms) and we are facing two issues that need to be resolved:
1) We need the images (up to five) that have been upload using the <strong>multi upload field to be linked to the WP gallery</strong> so we can make changes to them in the edit mode and display them smoothly on the articles. The first picture should be the featured image and the other 4 should be attached to the gallery. Some code for the functions.php would be great!
2) We are using a "<strong>list field</strong>" in Gravity forms for our users to show their sources and links. We need the field to be linked to three seperate ACF custom fields to be displayed in the articles.
Some ideas for code:
1)
public function migrate_post_meta(){
#Verify authorization and authentication
if ( ! $this->verify_request() )
return;
global $wpdb;
#Retrieve all featured image postmeta rows from prior theme
$query = $wpdb->prepare( "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $this->meta_ );
$results = $wpdb->get_results( $query );
if ( $results ){
foreach( $results as $result ){
#Check if meta_value is a path
if( preg_match( '/\//', $result->meta_value ) ){
$this->get_attachment_by_url( $result->meta_value, $result->post_id );
continue;
}
#Check if meta_value is an ID
if( is_int( (int)$result->meta_value ) )
#Add a native WordPress featured image postmeta row
if( update_post_meta( $result->post_id, '_thumbnail_id', $result->meta_value ) )
#Send a message to the screen
show_message( "Post #$result->post_id - Featured image was set properly." );
}
}
2)
<?php
add_action('gform_after_submission', 'show_me_everything');
function show_me_everything($entry) {
$list_values = unserialize($entry[6]);
}
Kyle answers:
Hi there, I use this all the time for multi file upload
add_filter("gform_after_submission_52", "my_add_post_attachements",10,2); //Your form ID
function my_add_post_attachements($entry, $form){
$submit = array();
$submit = $entry["1"]; //The field ID of the multi upload
$submit = stripslashes($submit);
$submit = json_decode($submit, true);
foreach ($submit as $key => $value){
require_once(ABSPATH . 'wp-admin/includes/image.php');
$post_id = The post ID of the page you are adding images
$url = $value;
$file = copy_post_image2($url, $post_id);
if(!$file)
return false;
$name_parts = pathinfo($name);
$name = trim( substr( $name, 0, -(1 + strlen($name_parts['extension'])) ) );
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$title = $name;
$content = '';
$attachment = array(
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => $post_id,
'post_title' => $title,
'post_content' => $content,
);
$id = wp_insert_attachment($attachment, $file, $post_id);
if ( !is_wp_error($id) ) {
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
}
}
}
function copy_post_image2($url, $post_id){
$time = current_time('mysql');
if ( $post = get_post($post_id) ) {
if ( substr( $post->post_date, 0, 4 ) > 0 )
$time = $post->post_date;
}
//making sure there is a valid upload folder
if ( ! ( ( $uploads = wp_upload_dir($time) ) && false === $uploads['error'] ) )
return false;
$name = basename($url);
$filename = wp_unique_filename($uploads['path'], $name);
// Move the file to the uploads dir
$new_file = $uploads['path'] . "/$filename";
$uploaddir = wp_upload_dir();
$path = str_replace($uploaddir["baseurl"], $uploaddir["basedir"], $url);
if(!copy($path, $new_file))
return false;
// Set correct file permissions
$stat = stat( dirname( $new_file ));
$perms = $stat['mode'] & 0000666;
@ chmod( $new_file, $perms );
// Compute the URL
$url = $uploads['url'] . "/$filename";
if ( is_multisite() )
delete_transient( 'dirsize_cache' );
$type = wp_check_filetype($new_file);
return array("file" => $new_file, "url" => $url, "type" => $type["type"]);
}
Kyle comments:
You need to update 3 things there: Form ID, Field ID, and Post ID
robork comments:
Hi Kyle,
thanks for your quick reply.
A few quick questions:
1)If I add the code to my functions.php it stops working - anything I'm missing here?
2)Where do I need to add the post ID? As a new post is generated each time the GF ist being filled it should be linked to that new post
3) add_filter("gform_after_submission_52", "my_add_post_attachements",10,2); //Your form ID
My GF ID is 10 but there is a 10 and a 2 - which one needs to be replaced?
4) Any idea for the list field?
Many thanks! We are getting there!
Tim
Kyle comments:
For the list field, are you limiting it to one row? So you are setting a post ID, or are you using the same post ID as the images?
robork comments:
List field has up to three rows - so three different values are being stored.
The list field is in the same GF form as the images
Kyle comments:
1) My fault when I added a comment I removed a row, use this: [[LINK href="http://pastie.org/8701611"]]http://pastie.org/8701611[[/LINK]] just change your field ID on line 12
2) Okay, in that instance you can use $entry["post_id"], I added it to the new pastie
3) Change the 52 actually so 3) add_filter("gform_after_submission_10", "my_add_post_attachements",10,2);
4) Want to hit the image first and then do the list? I will hit it once we get the image right for you
robork comments:
Hi Kyle,
it still seems to break my functions php when I just copy and paste the entire code and the update the file in WP editor.
<?php
/**
* Plugin Name:
* Plugin URI:
* Description: I
* Author: Robork
* Author URI:
* Version: 1.0.0
*/
/* Place custom code below this line */
add_filter("gform_after_submission_10", "my_add_post_attachements",10,2); //Your form ID
function my_add_post_attachements($entry, $form){
$submit = array();
$submit = $entry["1"]; //The field ID of the multi upload
$submit = stripslashes($submit);
$submit = json_decode($submit, true);
foreach ($submit as $key => $value){
require_once(ABSPATH . 'wp-admin/includes/image.php');
$post_id = $entry["post_id"];The post ID of the page you are adding images
$url = $value;
$file = copy_post_image2($url, $post_id);
if(!$file)
return false;
$name_parts = pathinfo($name);
$name = trim( substr( $name, 0, -(1 + strlen($name_parts['extension'])) ) );
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$title = $name;
$content = '';
$attachment = array(
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => $post_id,
'post_title' => $title,
'post_content' => $content,
);
$id = wp_insert_attachment($attachment, $file, $post_id);
if ( !is_wp_error($id) ) {
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
}
}
}
function copy_post_image2($url, $post_id){
$time = current_time('mysql');
if ( $post = get_post($post_id) ) {
if ( substr( $post->post_date, 0, 4 ) > 0 )
$time = $post->post_date;
}
//making sure there is a valid upload folder
if ( ! ( ( $uploads = wp_upload_dir($time) ) && false === $uploads['error'] ) )
return false;
$name = basename($url);
$filename = wp_unique_filename($uploads['path'], $name);
// Move the file to the uploads dir
$new_file = $uploads['path'] . "/$filename";
$uploaddir = wp_upload_dir();
$path = str_replace($uploaddir["baseurl"], $uploaddir["basedir"], $url);
if(!copy($path, $new_file))
return false;
// Set correct file permissions
$stat = stat( dirname( $new_file ));
$perms = $stat['mode'] & 0000666;
@ chmod( $new_file, $perms );
// Compute the URL
$url = $uploads['url'] . "/$filename";
if ( is_multisite() )
delete_transient( 'dirsize_cache' );
$type = wp_check_filetype($new_file);
return array("file" => $new_file, "url" => $url, "type" => $type["type"]);
}
// @ http://wp-mix.com/set-attachment-featured-image/
add_filter('the_content', 'set_featured_image_from_attachment');
function set_featured_image_from_attachment($content) {
global $post;
if (has_post_thumbnail()) {
// display the featured image
$content = the_post_thumbnail() . $content;
} else {
// get & set the featured image
$attachments = get_children(array(
'post_parent' => $post->ID,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order'
));
if ($attachments) {
foreach ($attachments as $attachment) {
set_post_thumbnail($post->ID, $attachment->ID);
break;
}
// display the featured image
$content = the_post_thumbnail() . $content;
}
}
return $content;
}
/*Register Robork Menus*/
add_action( 'init', 'register_my_menus' );
function register_my_menus() {
register_nav_menus(
array(
'main-navigation' => __( 'Main Navigation Menu Block' ),
'category-navigation' => __( 'Floating Categories Menu' ),
'footer-bar' => __( 'Footer Menu bar' )
)
);
}
/* Slider Functions*/
/* Slider Function to pull all images*/
function revconcept_get_images($post_id) {
global $post;
$thumbnail_ID = get_post_thumbnail_id();
$images = get_children( array('post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );
if ($images) :
foreach ($images as $attachment_id => $image) :
if ( $image->ID != $thumbnail_ID ) :
$img_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true); //alt
if ($img_alt == '') : $img_alt = $image->post_title; endif;
$big_array = image_downsize( $image->ID, 'full' );
$img_url = $big_array[0];
echo '<li>';
echo '<img src="';
echo $img_url;
echo '" alt="';
echo $img_alt;
echo '" />';
echo '</li><!--end slide-->';
endif; endforeach; endif; }
/*Add some Javascript*/
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array(), '1.10.2');
wp_enqueue_script( 'jquery');
function my_add_scripts() {
wp_register_script('flexslider-init', get_bloginfo('stylesheet_directory').'/js/flexslider-init.js', array('jquery', 'flexslider'));
wp_enqueue_script( 'flexslider-init');
wp_register_script('flexslider', get_bloginfo('stylesheet_directory').'/js/jquery.flexslider-min.js', array('jquery'));
wp_enqueue_script( 'flexslider');
}
add_action('wp_enqueue_scripts', 'my_add_scripts');
/*Add some CSS Style*/
function my_add_styles() {
wp_enqueue_style('flexslider', get_bloginfo('stylesheet_directory').'/js/flexslider.css');
}
add_action('wp_enqueue_scripts', 'my_add_styles');
add_action('acf/register_fields', 'my_register_fields');
function my_register_fields()
{
include_once('acf-location/acf-location.php');
}
/**
Beitragsbild hinzufügen
*/
add_theme_support( 'post-thumbnails' );
/**
Gravity Forms upload Pfad ändern
*/
add_filter("gform_upload_path", "change_upload_path", 10, 2);
function change_upload_path($path_info, $form_id){
$path_info["path"] = "/is/htdocs/wp1025602_ND5ABK6JFF/robork/wp-content/uploads/2014/01/";
$path_info["url"] = "http://robork.de/wp-content/uploads/2014/01/";
return $path_info;
}
/**
* Gravity Wiz // Multi-File Merge Tag for Post Content Templates
*
* Enhance the merge tag for multi-file upload fields by adding support for outputting markup that corresponds to the
* uploaded file. Example: image files will be wrapped in an <img> tag. Out of the box, this snippet only supports
* images and is limited to the 'jpg', 'png', and 'gif'.
*
* The default merge tag for the multi-file upload field will output the URL for each of the files.
*
* @version 1.0
* @author David Smith <[email protected]>
* @license GPL-2.0+
* @link http://gravitywiz.com/...
* @copyright 2013 Gravity Wiz
*/
class GW_Multi_File_Merge_Tag {
private static $instance = null;
/**
* Temporarily stores the values of the 'gform_merge_tag_filter' filter for use in the 'gform_replace_merge_tags' filter.
*
* @var array
*/
private $_merge_tag_args = array();
private $_settings = array();
private function __construct() {
add_filter( 'gform_merge_tag_filter', array( $this, 'filter_merge_tag' ), 10, 5 );
}
public static function get_instance() {
if( null == self::$instance )
self::$instance = new self;
return self::$instance;
}
public function get_default_args() {
return array(
'form_id' => false,
'exclude_forms' => array(),
'markup' => array(
array(
'file_types' => array( 'jpg', 'png', 'gif' ),
'markup' => '<img src="{url}" width="100%" />'
),
array(
'file_types' => array( 'mp4', 'ogg', 'webm' ),
'markup' => '<video width="320" height="240" controls>
<source src="{url}" type="video/{ext}">
Your browser does not support the video tag.
</video>'
),
array(
'file_types' => array( 'ogv' ),
'markup' => '<video width="320" height="240" controls>
<source src="{url}" type="video/ogg">
Your browser does not support the video tag.
</video>'
)
)
);
}
public function register_settings( $args = array() ) {
$args = wp_parse_args( $args, $this->get_default_args() );
if( ! $args['form_id'] ) {
$this->_settings['global'] = $args;
} else {
$this->_settings[$args['form_id']] = $args;
}
}
public function filter_merge_tag( $value, $input_id, $options, $field, $raw_value ) {
if( empty( $this->_settings ) )
return $value;
// only process for individual merge tags (no {all_fields})
if( $input_id != $field['id'] || ! $this->is_applicable_field( $field ) )
return $value;
$this->_merge_tag_args = compact( 'value', 'input_id', 'options', 'field', 'raw_value' );
$this->_merge_tag_args['placeholder'] = "{:{$input_id}:{$options}}";
add_filter( 'gform_replace_merge_tags', array( $this, 'replace_merge_tag' ), 10, 7 );
// replace merge tag to be replaced later
return $this->_merge_tag_args['placeholder'];
}
public function replace_merge_tag( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {
preg_match_all( '/{[^{]*?:(\d+(\.\d+)?)(:(.*?))?}/mi', $text, $matches, PREG_SET_ORDER );
foreach( $matches as $match ) {
$input_id = $match[1];
$field = GFFormsModel::get_field( $form, $input_id );
if( ! $this->is_applicable_field( $field ) )
continue;
if( $format != 'html' ) {
$value = $this->_merge_tag_args['value'];
} else {
$value = GFFormsModel::get_lead_field_value( $entry, $field );
$files = empty( $value ) ? array() : json_decode( $value, true );
$value = '';
foreach( $files as &$file ){
$value .= $this->get_file_markup( $file, $form['id'] );
}
}
$text = str_replace( $match[0], $value, $text );
}
return $text;
}
public function get_file_markup( $file, $form_id ) {
$value = str_replace( " ", "%20", $file );
$file_info = pathinfo( $value );
extract( $file_info ); // gives us $dirname, $basename, $extension, $filename
if( ! $extension )
return $value;
$markup_settings = $this->get_markup_settings( $form_id );
if( empty( $markup_settings ) )
return $value;
foreach( $markup_settings as $file_type_markup ) {
$file_types = array_map( 'strtolower', $file_type_markup['file_types'] );
if( ! in_array( strtolower( $extension ), $file_types ) )
continue;
$markup = $file_type_markup['markup'];
$tags = array(
'{url}' => $file,
'{filename}' => $filename,
'{basename}' => $basename,
'{ext}' => $extension
);
foreach( $tags as $tag => $tag_value ) {
$markup = str_replace( $tag, $tag_value, $markup );
}
$value = $markup;
break;
}
return $value;
}
public function get_markup_settings( $form_id ) {
$form_markup_settings = rgars( $this->_settings, "$form_id/markup" ) ? rgars( $this->_settings, "$form_id/markup" ) : array();
$global_markup_settings = rgars( $this->_settings, 'global/markup' ) ? rgars( $this->_settings, 'global/markup' ) : array();
return array_merge( $form_markup_settings, $global_markup_settings );
}
public function is_excluded_form( $form_id ) {
$excluded_forms = (array) rgars( $this->_settings, 'global/exclude_forms' );
return in_array( $form_id, $excluded_forms );
}
public function is_applicable_field( $field ) {
$is_valid_form = ! $this->is_excluded_form( $field['formId'] );
$is_file_upload_filed = GFFormsModel::get_input_type( $field ) == 'fileupload';
$is_multi = rgar( $field, 'multipleFiles' );
return $is_valid_form && $is_file_upload_filed && $is_multi;
}
}
function gw_multi_file_merge_tag() {
return GW_Multi_File_Merge_Tag::get_instance();
}
gw_multi_file_merge_tag()->register_settings();
/*This class will migrate both attachment IDs and external image URLs into your featured images*/
class Featured_Image_Migration{
#Instantiate the migration by hitting /wp-admin/?migrate-post-meta=foobar
protected $key = 'migrate-post-meta';
protected $secret = 'foobar';
#This is your legacy meta_key
protected $meta_key = 'mainimg_medium';
function __construct(){
#Force this to run last so all includes are available
add_action( 'admin_init', array($this, 'migrate_post_meta'), 999999 );
}
public function migrate_post_meta(){
#Verify authorization and authentication
if ( ! $this->verify_request() )
return;
global $wpdb;
#Retrieve all featured image postmeta rows from prior theme
$query = $wpdb->prepare( "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = %s", $this->meta_ );
$results = $wpdb->get_results( $query );
if ( $results ){
foreach( $results as $result ){
#Check if meta_value is a path
if( preg_match( '/\//', $result->meta_value ) ){
$this->get_attachment_by_url( $result->meta_value, $result->post_id );
continue;
}
#Check if meta_value is an ID
if( is_int( (int)$result->meta_value ) )
#Add a native WordPress featured image postmeta row
if( update_post_meta( $result->post_id, '_thumbnail_id', $result->meta_value ) )
#Send a message to the screen
show_message( "Post #$result->post_id - Featured image was set properly." );
}
}
#Kill the admin process to see the message log
exit;
}
private function verify_request(){
#Only admins and those with the key/secret can run this in wp-admin
if( current_user_can( 'manage_options' ) && isset( $_GET[$key] ) && $_GET[$key] === $secret )
return true;
return false;
}
private function get_attachment_by_url( $url, $post_id ){
global $wpdb;
#This is about as close as we can come to finding the attachment
$query = $wpdb->prepare( "SELECT ID from $wpdb->posts WHERE guid = %s LIMIT 1", $url );
$id = $wpdb->get_var( $query );
if($id)
#We found a match in the database!
return $id;
else{
#If the URL is external, download the image into the post attachments
add_action( 'add_attachment', array( $this, 'add_attachment') );
$attachment = media_sideload_image( $url, $post_id );
remove_action( 'add_attachment', array( $this, 'add_attachment') );
}
}
public function add_attachment($id){
#Get attachment post object
$attachment = get_post( $id );
#Add our newly sideloaded attachment as the featured image
if( update_post_meta( $attachment->post_parent, '_thumbnail_id', $attachment->ID ) )
show_message( "Post #$attachment->post_parent - Featured image was sideloaded and set properly." );
}
}
new Featured_Image_Migration;
/* Add is Tree Function*
function is_tree($pid)
{
global $post;
$ancestors = get_post_ancestors($post->$pid);
$root = count($ancestors) - 1;
$parent = $ancestors[$root];
if(is_page() && (is_page($pid) || $post->post_parent == $pid || in_array($pid, $ancestors)))
{
return true;
}
else
{
return false;
}
};
/* Place custom code above this line. */
?>
Kyle comments:
Sorry, hard to check code in the small space here, change this line
$post_id = $entry["post_id"];The post ID of the page you are adding images
to this
$post_id = $entry["post_id"];//The post ID of the page you are adding images
robork comments:
YEEEESSS! You are brilliant Kyle! I have been working on this issue for a few days and couldn't solve it!
How about the links? Can we get that solved as well (see screenshots below)
We have a few more jobs for you - do you wanna run this via wpquestions or should we PM?