Created
April 11, 2019 08:22
-
-
Save stirtingale/57a4c48d4c42dc74059186ed162a78d0 to your computer and use it in GitHub Desktop.
Wordpress Post Content to Caption and Gallery Field ACF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// vars | |
$post_id = get_the_id(); | |
$images = get_field('gallery'); | |
$caption = get_field('caption'); | |
$content = get_the_content(); | |
// var_dump($post_id); | |
// var_dump($images); | |
// var_dump($caption); | |
if(empty($images)): | |
function get_attachment_id( $url ) { | |
$attachment_id = 0; | |
$dir = wp_upload_dir(); | |
if ( false !== strpos( $url, $dir['baseurl'] . '/' ) ) { // Is URL in uploads directory? | |
$file = basename( $url ); | |
$query_args = array( | |
'post_type' => 'attachment', | |
'post_status' => 'inherit', | |
'fields' => 'ids', | |
'meta_query' => array( | |
array( | |
'value' => $file, | |
'compare' => 'LIKE', | |
'key' => '_wp_attachment_metadata', | |
), | |
) | |
); | |
$query = new WP_Query( $query_args ); | |
if ( $query->have_posts() ) { | |
foreach ( $query->posts as $post_id ) { | |
$meta = wp_get_attachment_metadata( $post_id ); | |
$original_file = basename( $meta['file'] ); | |
$cropped_image_files = wp_list_pluck( $meta['sizes'], 'file' ); | |
if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) { | |
$attachment_id = $post_id; | |
break; | |
} | |
} | |
} | |
} | |
return $attachment_id; | |
} | |
function linkExtractor($html){ | |
$linkArray = array(); | |
if(preg_match_all('/<img\s+.*?src=[\"\']?([^\"\' >]*)[\"\']?[^>]*>/i',$html,$matches,PREG_SET_ORDER)){ | |
foreach($matches as $match){ | |
if(!empty($match)){ | |
array_push($linkArray,array($match[1],$match[2])); | |
} | |
} | |
} | |
return $linkArray; | |
} | |
$icount = 0; | |
$image_arrray = linkExtractor($content); | |
$attachments_array = array(); | |
foreach($image_arrray as $image){ | |
$icount++; | |
$url = $image[0]; | |
// echo "<br><strong>Image ".$icount.":</strong> "; | |
// echo $url; | |
// echo "<br>"; | |
// echo "<br><strong>Image ".$icount." ID:</strong> "; | |
$imageid = get_attachment_id($url); | |
// echo $imageid; | |
$attachments_array[] = $imageid; | |
} | |
update_field('gallery',$attachments_array,$post_id) | |
endif; // images | |
if(empty($caption)): | |
// text to caption field | |
$withptags = wpautop($content); | |
$caption = strip_tags($withptags); | |
// echo($caption); | |
update_field('caption',$caption,$post_id); | |
endif; // caption | |
?> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment