I want to append some data after first image retrieved from post_content.
add_action('the_post', function($post, $query){
$post->post_content = catch_that_image();
},10,2);
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
$chtml = "YOUR DATA GOES HERE";
return "<img src='".$first_img."'>" . " " . $chtml;
}
I am trying to do this by using code. Using this I am unable to append content after first image from post_content.
Related
I've read and tried a lot before posting this.
I have a custom sitemap function that I want to trigger on update/create/save post.
I've tried to create new post, update an existing one and just save for the following hooks:
save_post
acf/save_post
pre_post_update
edit_post
the_post
publish_post
Nothing of the above works. I unit tested the function and it does work when hooked on init and admin_init. So I know it's a hook problem. Any advice would be highly appreciated.
All the code:
function pull_active_pages(){
global $wpdb;
$query = $wpdb->get_results(" SELECT * FROM `wp_posts` WHERE (`post_type` LIKE 'page' OR `post_type` LIKE 'post') AND `post_status` LIKE 'publish'; ", OBJECT);
return $query;
}
function makeSitemap(){
$file = 'sitemap.xml'; //that means in the root, provide full path
$query = pull_active_pages();
$output = '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL;
$output .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.google.com/schemas/sitemap-news/0.9 http://www.google.com/schemas/sitemap-news/0.9/sitemap-news.xsd">'.PHP_EOL;
foreach((array)$query as $record){
$output .= '<url>'.PHP_EOL;
$url = get_permalink($record->ID);
$output .= '<loc>' . $url . '</loc>'.PHP_EOL;
$last_mod = $record->post_modified_gmt;
$output .= '<lastmod>' . $last_mod .'</lastmod>'.PHP_EOL;
$output .= '<priority>1.00</priority>'.PHP_EOL;
$output .= '</url>'.PHP_EOL;
}
$flags = FILE_APPEND; //redo the whole thing no append for now
$output .='</urlset>';
file_put_contents( $file, $output);
}
add_action('save_post', function(){ makeSitemap();}, 10, 2);
You should change the action like that
add_action('save_post', 'makeSitemap');
and add absolute path to the filename
$file = ABSPATH . '/sitemap.xml'; //that means in the root, provide full path
Check this https://wpengineer.com/2382/wordpress-constants-overview/#ABSPATH
for other absolute paths constants
I want to display the last update date of a post in WordPress, i can find this code and i must put it in function.php
function wpb_last_updated_date( $content ) {
$u_time = get_the_time('U');
$u_modified_time = get_the_modified_time('U');
if ($u_modified_time >= $u_time + 86400) {
$updated_date = get_the_modified_time('F jS, Y');
$updated_time = get_the_modified_time('h:i a');
$custom_content .= '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';
}
$custom_content .= $content;
return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );
It's working but the problem that i also have update date displayed on pages, portfolios, ....
How can i limit the display of updated date just on post for the blog ?
Thanks for helping.
Just add a condition to check the post type:
function wpb_last_updated_date( $content ) {
$u_time = get_the_time('U');
$u_modified_time = get_the_modified_time('U');
if ($u_modified_time >= $u_time + 86400 && is_singular('post')) {
$updated_date = get_the_modified_time('F jS, Y');
$updated_time = get_the_modified_time('h:i a');
$custom_content .= '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';
}
$custom_content .= $content;
return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );
is_singular() queries for a single post and takes the post type as an argument.
I have the following code in my Wordpress. I need to add every uploaded image a counting number like, image_1, image_2, image_3 and so on..
The purpose of this is that every uploaded image attached to post, gets post ID name, and counting number in end to it.
It would be great if some one help me with this. Thanks!
<?php
add_filter('wp_handle_upload_prefilter', 'wpse_25894_handle_upload_prefilter');
add_filter('wp_handle_upload', 'wpse_25894_handle_upload');
function wpse_25894_handle_upload_prefilter( $file )
{
add_filter('upload_dir', 'wpse_25894_custom_upload_dir');
return $file;
}
function wpse_25894_handle_upload( $fileinfo )
{
remove_filter('upload_dir', 'wpse_25894_custom_upload_dir');
return $fileinfo;
}
function wpse_25894_custom_upload_dir($path)
{
/*
* Determines if uploading from inside a post/page/cpt - if not, default Upload folder is used
*/
$use_default_dir = ( isset($_REQUEST['post_id'] ) && $_REQUEST['post_id'] == 0 ) ? true : false;
if( !empty( $path['error'] ) || $use_default_dir )
return $path; //error or uploading not from a post/page/cpt
/*
* Save uploads in ID based folders
*
*/
$customdir = '/' . $_REQUEST['post_id'];
$path['path'] = str_replace($path['subdir'], '', $path['path']); //remove default subdir (year/month)
$path['url'] = str_replace($path['subdir'], '', $path['url']);
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;
}
// The filter runs when resizing an image to make a thumbnail or intermediate size.
add_filter( 'image_make_intermediate_size', 'wpse_123240_rename_intermediates' );
function wpse_123240_rename_intermediates( $image ) {
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
// Build our new image name
$postid = $_REQUEST['post_id'];
$random = rand(1,5);
$new_name = $dir . $postid . '_' . $random . $ext;
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}
?>
Now this code generates images named postid_randomnumber.jpg
I just need to add 20 images at maximum, so if I can have numbers from 1-20, that is also working fine with my purposes.
-- UPDATE --
I canged the last part of code to this, it is not maybe the cleanest solution, but it works:
function wpse_123240_rename_intermediates( $image )
{
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
//$count = get_option( 'wpa59168_counter', 1 );
// Build our new image name
$postid = $_REQUEST['post_id'];
$increment = 1;
$new_name = $dir . $postid . '_1' . $ext;
while(is_file($new_name)) {
$increment++;
$new_name = $dir . $postid . '_' . $increment . $ext;
}
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}
I need to know if it's possible how to get_the_tags() to array?
i want to like this
$myarray = array('one', 'two', 'three', 'four', 'five', 'six');
i want use this code with "replace the_content" like this
<?php
function replace_content($content){
foreach(get_the_tags() as $tag) {
$out .= $tag->name .',';
$csv_tags .= '"' . $tag->name . '"';
}
$find = array($out);
$replace = array($csv_tags);
$content = str_replace($find, $replace, $content);
return $content;
}
add_filter('the_content', 'replace_content');
?>
find tag in content and replace with link
$posttags = get_the_tags();
$my_array = array();
if ($posttags) {
foreach($posttags as $tag) {
$my_array[] = $tag->name ;
}
.. and if your final goal is to output it like you wrote above then :
echo implode(',', $my_array);
.. and by the type of question , I was not sure if by one,two.. you might be meaning ID , so :
$posttags = get_the_tags();
$my_array = array();
if ($posttags) {
foreach($posttags as $tag) {
$my_array[] = $tag->term_id ;
}
BTW - a quick look at the codex would have shown you that ...
You should be able to do something like this:
global $wpdb;
// get all term names in an indexed array
$array = $wpdb->get_results("SELECT name FROM wp_terms", ARRAY_N);
// walk over the array, use a anonymous function as callback
array_walk($array, function(&$item, $key) { $item = "'".$item[0]."'"; });
Notice that anonymous functions are only available since PHP 5.3
You should be able to do the same thing using get_the_tags() if you only want tags for a specific post:
$tags = get_the_tags();
array_walk($tags, function(&$item, $key) { $item = "'".$item->name."'"; });
Judging from your updated question you don't need any of the above code, the only thing you need to to in order to get single quotes around each tag is:
foreach(get_the_tags() as $tag) {
$out .= $tag->name . ',';
$csv_tags .= '"' . "'".$tag->name."'" . '"';
}
Trying to remove the gallery shortcode from the post content and save in a variable for use elsewhere in the template. The new Wordpress gallery tool is great for selecting which images they want and assigning captions, hoping to use this to create the gallery, but then pull it out of the content on the front-end.
So this little snipped works just fine for removing the gallery and reapplying formatting... however I want to save that gallery shortcode.
$content = strip_shortcodes( get_the_content() );
$content = apply_filters('the_content', $content);
echo $content;
Hoping to save the shortcode so it can be parsed into an array and used to recreate a custom gallery setup on the front-end. An example of this shortcode I'm trying to save is...
[gallery ids="1079,1073,1074,1075,1078"]
Any suggestions would be greatly appreciated.
Function to grab First Gallery shortcode from post content:
// Return first gallery shortcode
function get_shortcode_gallery ( $post = 0 ) {
if ( $post = get_post($post) ) {
$post_gallery = get_post_gallery($post, false);
if ( ! empty($post_gallery) ) {
$shortcode = "[gallery";
foreach ( $post_gallery as $att => $val ) {
if ( $att !== 'src') {
if ( $att === 'size') $val = "full"; // Set custom attribute value
$shortcode .= " ". $att .'="'. $val .'"'; // Add attribute name and value ( attribute="value")
}
}
$shortcode .= "]";
return $shortcode;
}
}
}
// Example of how to use:
echo do_shortcode( get_shortcode_gallery() );
Function to delete First gallery shortcode from Post content:
// Deletes first gallery shortcode and returns content
function strip_shortcode_gallery( $content ) {
preg_match_all( '/'. get_shortcode_regex() .'/s', $content, $matches, PREG_SET_ORDER );
if ( ! empty( $matches ) ) {
foreach ( $matches as $shortcode ) {
if ( 'gallery' === $shortcode[2] ) {
$pos = strpos( $content, $shortcode[0] );
if ($pos !== false)
return substr_replace( $content, '', $pos, strlen($shortcode[0]) );
}
}
}
return $content;
}
// Example of how to use:
$content = strip_shortcode_gallery( get_the_content() ); // Delete first gallery shortcode from post content
$content = str_replace( ']]>', ']]>', apply_filters( 'the_content', $content ) ); // Apply filter to achieve the same output that the_content() returns
echo $content;
just use the get_shortcode_regex():
<?php
$pattern = get_shortcode_regex();
preg_match_all('/'.$pattern.'/s', $post->post_content, $shortcodes);
?>
that will return an array of all the shortcodes in your content, which you can then output wherever you feel, like so:
<?php
echo do_shortcode($shortcodes[0][1]);
?>
similarly, you could use the array entries to check for shortcodes in your content and remove them with str_replace():
<?php
$content = $post->post_content;
$content = str_replace($shortcodes[0][1],'',$content);
?>
Something like $gallery = do_shortcode('[gallery]'); might work.