Update Post content’s images

Below Code Update post content image if image src is intermediate image path.

It also update <img> tag height, width and src attribute. And update class with `size-full`

$content= preg_replace_callback('/<img.*?>/',[ $this, 'content_image_fix_callback' ],$post->post_content);


/**
* Updating Image src | height | width and class
*
* @param array $matches
*
* @return string
*/
public function content_image_fix_callback( $matches ) {
	$text          = $matches[0];

	preg_match( "/src=\"?'?[^ ]*?-[0-9]+x[0-9]+\.(jpg|jpeg|gif|png)/i", $text, $data_matches_src );
	preg_match( "/wp-image-(\d+)/", $text, $data_matches_class );
	if ( ! empty( $data_matches_src[1] ) && ! empty( $data_matches_class[1] ) ) {
		$attachment_id = (int) $data_matches_class[1];
		$img_src_full  = wp_get_attachment_image_src( $attachment_id, "full" );
		if ( ! empty( $img_src_full ) ) {
			$text = preg_replace( "/(src=\"?'?)[^ ]*?(\"'?)/", '$1' . $img_src_full[0] . '$2', $text );

			if ( ! empty( $img_src_full[1] ) ){
				$text = preg_replace( "/(width=\"?'?)[^ ]*?(\"'?)/", '$1' . $img_src_full[1] . '$2', $text );
			}

			if ( ! empty( $img_src_full[2] ) ){
				$text = preg_replace( "/(height=\"?'?)[^ ]*?(\"'?)/", '$1' . $img_src_full[2] . '$2', $text );
			}

			$text = preg_replace( "/(class=\"?'?[^\"']*)size-[^ \"']+([^\"']*\"?'?)/i", '$1size-full$2', $text );
		}

	}

	return $text;
}

Image Migration

Here are listed some useful command and regex which are very user wile migrating image image from one server to another.

Created zip with images which is listed on CSV

tar -cvf missing.tar -T sample.csv

CSV file need path of image file and Zip it will be on same path.

Exclude intermediate size image and create zip updated directory structure for multisite

find 2021 -type f -print | egrep -v '\-[0-9]+x[0-9]+\.(jpg|png|jpeg|gif)$' | tar cvfz 2021.tar.gz --transform 's,^,uploads/sites/2/,' -T -

Check <img> has Intermediate image

preg_match( "/src=\"?'?[^ ]*?-[0-9]+x[0-9]+\.(jpg|jpeg|gif|png)/i", $text, $data_matches_src );

Update html tag attribute value using regex

$text = preg_replace( "/(attr=\"?'?)[^ ]*?(\"'?)/", '$1' . 'NewVal' . '$2', $text );

$text = preg_replace( "/(class=\"?'?[^\"']*)size-[^ \"']+([^\"']*\"?'?)/i", '$1NewVal$2', $text );

Filter intermediate image

In WordPress, While migration site, Media will large chunks to migrate. For making that seamless we should filter out all intermediate image sizes.

Below command will filter intermediate image sizes for upload-dir and create zip file

find uploads-dir -type f -print | egrep -v '\-[0-9]+x[0-9]+\.(jpg|png|jpeg|gif)$' | tar cvfz media-files.tar.gz -T -

Extend core WordPress Tag block Example

import { addFilter } from '@wordpress/hooks';
import { useSelect, dispatch } from '@wordpress/data';
import { SelectControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { NAMESPACE } from '../helper';

(function () {
	function PrimaryTagUI(OriginalComponent) {
		return function (props) {
			const { slug } = props;

			if (slug === 'post_tag') {
				return (
					<PrimaryTagSelector { ...props }> {/* eslint-disable-line */}
						<OriginalComponent {...props} /> {/* eslint-disable-line */}
					</PrimaryTagSelector>
				);
			}

			return <OriginalComponent {...props} />; /* eslint-disable-line */
		};
	}

	addFilter('editor.PostTaxonomyType', 'primary-tag', PrimaryTagUI);
})();

/**
 * PrimaryTagSelector Component
 *
 * @param {Object} props React props
 */
function PrimaryTagSelector(props) {
	const { children, terms } = props;

	const tags = useSelect((select) => {
		return select('core').getEntityRecords('taxonomy', 'post_tag', {
			include: terms.join(','),
		});
	});

	const primaryTag = useSelect((select) => {
		return select('core/editor').getEditedPostAttribute('primary_tag');
	});

	const hasTags = tags && tags.length > 1;

	/**
	 * Update the Primary Tag
	 *
	 * @param {number} primaryTag ID of the taxonomy that should be stored as the Primary
	 */
	function updatePrimaryTag(primaryTag) {
		// eslint-disable-next-line radix
		dispatch('core/editor').editPost({ primary_tag: parseInt(primaryTag) });
	}

	// set the primary tag automatically if just one element is present
	if (tags && tags.length === 1) {
		updatePrimaryTag(tags[0].id);
	} else if (!hasTags) {
		updatePrimaryTag(0);
	}

	return (
		<>
			{children}
			{!!hasTags && (
				<SelectControl
					onChange={updatePrimaryTag}
					label={__('Primary Tag', NAMESPACE)}
					value={primaryTag}
					options={tags.map((tag) => {
						return {
							label: tag.name,
							value: tag.id,
						};
					})}
				/>
			)}
		</>
	);
}

Install PHP Ioncube extension?

//Download ioncube package
$ cd /tmp
$ wget https://downloads.ioncube.com/loader_downloads/ioncube_loaders_lin_x86-64.tar.gz

//Unzip ioncube package
$ tar -zxvf ioncube_loaders_lin_x86*

//For find php extension Directory
$ php -i | grep extension_dir
extension_dir => /usr/lib/php/20151012 => /usr/lib/php/20151012

//Copy ioncube file to your php extension Directory. Make sure you copy loader with correct version accoding to your php version.
$sudo cp /tmp/ioncube/ioncube_loader_lin_7.2.so /usr/lib64/php/modules

//Find PHP.ini path from Phpinfo();

//Open php.ini
$ Sudo vim /ext/php.ini

//To load ioncube extension path add following line at starting of in php.ini.
zend_extension = /usr/lib64/php/modules/ioncube_loader_lin_7.2.so

Remove action/filters using class name?

function remove_filters_for_anonymous_class($tag, $class, $method)
{
    $filters = $GLOBALS['wp_filter'][$tag];
    if (empty ($filters)) {
        return;
    }
    foreach ($filters as $priority => $filter) {
        foreach ($filter as $identifier => $function) {
            if (is_array($function)
                and is_a($function['function'][0], $class)
                and $method === $function['function'][1]
            ) {
                remove_filter(
                    $tag,
                    array($function['function'][0], $method),
                    $priority
                );
            }
        }
    }
}

Cron job with WordPress

Many time cron will slow your site to end user. It’s little bit complex to debug.

WP-Cron works different way. It’s not based on the server, or the server’s clock.

In WordPress, It check every time a person calls one of your pages or posts. Every time WordPress goes to work, it checks to see if there are any jobs that need to leverage WP-Cron.

But that’s a bit uncertain, as you might imagine. Especially for sites that don’t get hit very often. and for large site, every request can  execute process that goes to work and takes up server resources. That might easily bring your server down if you don’t have adequate resources.

So in the end, WP-Cron will not work small sites as well as very large site.

We need to another mechanism to run WP-cron job,  The mechanism is Cronjob [ based on server ].

Continue reading →

BuddyPress Profile Views

I am happy to introduce Buddypress profile view plugin Which allow you to manage your member profile views. We got idea of this plugin form Linked profile view.  This plugin provide similar functionality for buddypress.

Idea :

  • No of view of member profile
  • To know which member is popular on network
  • Display popular member  list
  • Member can access their profile view graph

Feature of this plugin:

  • View count on Profile
  • Profile view statistics
  • Language support
  • Live Notification on profile view

Roadmap:

  • Add provision to disable Notification
  • Widget based on profile views

Download : https://wordpress.org/plugins/buddy-views/

Contributors : @DipsKakadiya @mehulkaklotar @yapareshya @Utkarsh_ME @Sanket

Make Private Buddypress Member directory

function make_private_members_profiles(){
// Bail if not a profile page.

if ( ! bp_is_user_profile() && ! bp_is_members_directory() )
return;

// Allow admin users.
if ( current_user_can( 'manage_options' ) )
return;

// Allow the profile owner.
if ( bp_is_user_profile() && bp_loggedin_user_id() == bp_displayed_user_id() )
return;

// If we get to here, redirect to homepage.
bp_core_redirect( home_url() );
}

add_action( 'bp_init', 'make_private_members_profiles') );