'save_custom_order',
'nonce' => wp_create_nonce( 'order_sorting_nonce' ),
'hirarchical' => ( is_post_type_hierarchical( $typenow ) ? 'true' : 'false' ),
) );
}
/**
* Save custom content order coming from ajax call
*
* @since 5.0.0
*/
public function save_custom_content_order()
{
global $wpdb ;
// Check user capabilities
if ( !current_user_can( 'edit_pages' ) ) {
wp_send_json( 'Something went wrong.' );
}
// Verify nonce
if ( !wp_verify_nonce( $_POST['nonce'], 'order_sorting_nonce' ) ) {
wp_send_json( 'Something went wrong.' );
}
// Get ajax variables
$action = ( isset( $_POST['action'] ) ? $_POST['action'] : '' );
$item_parent = ( isset( $_POST['item_parent'] ) ? absint( $_POST['item_parent'] ) : 0 );
$menu_order_start = ( isset( $_POST['start'] ) ? absint( $_POST['start'] ) : 0 );
$post_id = ( isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0 );
$item_menu_order = ( isset( $_POST['menu_order'] ) ? absint( $_POST['menu_order'] ) : 0 );
$items_to_exclude = ( isset( $_POST['excluded_items'] ) ? absint( $_POST['excluded_items'] ) : array() );
$post_type = ( isset( $_POST['post_type'] ) ? $_POST['post_type'] : false );
// Make processing faster by removing certain actions
remove_action( 'pre_post_update', 'wp_save_post_revision' );
// $response array for ajax response
$response = array();
// Update the item whose order/position was moved
if ( $post_id > 0 && !isset( $_POST['more_posts'] ) ) {
// https://developer.wordpress.org/reference/classes/wpdb/update/
$wpdb->update(
$wpdb->posts,
// The table
array(
'menu_order' => $item_menu_order,
),
array(
'ID' => $post_id,
)
);
clean_post_cache( $post_id );
$items_to_exclude[] = $post_id;
}
// Get all posts from the post type related to ajax request
$query_args = array(
'post_type' => $post_type,
'orderby' => 'menu_order title',
'order' => 'ASC',
'posts_per_page' => -1,
'suppress_filters' => true,
'ignore_sticky_posts' => true,
'post_status' => array(
'publish',
'future',
'draft',
'pending',
'private'
),
'post_parent' => $item_parent,
'post__not_in' => $items_to_exclude,
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
);
$posts = new WP_Query( $query_args );
if ( $posts->have_posts() ) {
// Iterate through posts and update menu order and post parent
foreach ( $posts->posts as $post ) {
// If the $post is the one being displaced (shited downward) by the moved item, increment it's menu_order by one
if ( $menu_order_start == $item_menu_order && $post_id > 0 ) {
$menu_order_start++;
}
// Only process posts other than the moved item, which has been processed earlier outside this loop
if ( $post_id != $post->ID ) {
// Update menu_order
$wpdb->update( $wpdb->posts, array(
'menu_order' => $menu_order_start,
), array(
'ID' => $post->ID,
) );
clean_post_cache( $post->ID );
}
$items_to_exclude[] = $post->ID;
$menu_order_start++;
}
die( json_encode( $response ) );
} else {
die( json_encode( $response ) );
}
}
/**
* Set default ordering of list tables of sortable post types by 'menu_order'
*
* @link https://developer.wordpress.org/reference/classes/wp_query/#methods
* @since 5.0.0
*/
public function orderby_menu_order( $query )
{
global $pagenow, $typenow ;
$options = get_option( ASENHA_SLUG_U, array() );
$content_order_for = $options['content_order_for'];
$content_order_enabled_post_types = array();
foreach ( $options['content_order_for'] as $post_type_slug => $is_custom_order_enabled ) {
if ( $is_custom_order_enabled ) {
$content_order_enabled_post_types[] = $post_type_slug;
}
}
// Use custom order in wp-admin listing pages/tables for enabled post types
if ( is_admin() && 'edit.php' == $pagenow && !isset( $_GET['orderby'] ) ) {
if ( in_array( $typenow, $content_order_enabled_post_types ) && (post_type_supports( $typenow, 'page-attributes' ) || is_post_type_hierarchical( $typenow )) ) {
$query->set( 'orderby', 'menu_order title' );
$query->set( 'order', 'ASC' );
}
}
}
/**
* Make sure newly created posts are assigned the highest menu_order so it's added at the bottom of the existing order
*
* @since 6.2.1
*/
public function set_menu_order_for_new_posts( $post_id, $post, $update )
{
$options = get_option( ASENHA_SLUG_U, array() );
$content_order_for = $options['content_order_for'];
$content_order_enabled_post_types = array();
foreach ( $options['content_order_for'] as $post_type_slug => $is_custom_order_enabled ) {
if ( $is_custom_order_enabled ) {
$content_order_enabled_post_types[] = $post_type_slug;
}
}
// Only assign menu_order if there are none assigned when creating the post, i.e. menu_order is 0
if ( in_array( $post->post_type, $content_order_enabled_post_types ) && ('auto-draft' == $post->post_status || 'publish' == $post->post_status) && $post->menu_order == '0' && false === $update ) {
$post_with_highest_menu_order = get_posts( array(
'post_type' => $post->post_type,
'posts_per_page' => 1,
'orderby' => 'menu_order',
'order' => 'DESC',
) );
if ( $post_with_highest_menu_order ) {
$new_menu_order = (int) $post_with_highest_menu_order[0]->menu_order + 1;
// Assign the one higher menu_order to the new post
$args = array(
'ID' => $post_id,
'menu_order' => $new_menu_order,
);
wp_update_post( $args );
}
}
}
/**
* Add media replacement button in the edit screen of media/attachment
*
* @since 1.1.0
*/
public function add_media_replacement_button( $fields, $post )
{
// Enqueues all scripts, styles, settings, and templates necessary to use all media JS APIs.
// Reference: https://codex.wordpress.org/Javascript_Reference/wp.media
wp_enqueue_media();
// Add new field to attachment fields for the media replace functionality
$fields['asenha-media-replace'] = array();
$fields['asenha-media-replace']['label'] = '';
$fields['asenha-media-replace']['input'] = 'html';
$fields['asenha-media-replace']['html'] = '
Replace Media
The current file will be replaced with the uploaded and/or selected file while retaining the current ID, publish date and file name. Thus, no existing links will break.
Note that you can only replace with the same file type, e.g. JPG can only be replaced by JPG.
';
return $fields;
}
/**
* Replace existing media with the newly updated file
*
* @link https://plugins.trac.wordpress.org/browser/replace-image/tags/1.1.7/hm-replace-image.php#L55
* @since 1.1.0
*/
public function replace_media( $old_attachment_id )
{
$old_post_meta = get_post( $old_attachment_id, ARRAY_A );
$old_post_mime = $old_post_meta['post_mime_type'];
// e.g. 'image/jpeg'
// Get the new attachment/media ID, meta and mime type
if ( isset( $_POST['new-attachment-id'] ) && !empty($_POST['new-attachment-id']) ) {
$new_attachment_id = intval( sanitize_text_field( $_POST['new-attachment-id'] ) );
$new_post_meta = get_post( $new_attachment_id, ARRAY_A );
$new_post_mime = $new_post_meta['post_mime_type'];
// e.g. 'image/jpeg'
}
// Check if the media file ID selected via the media frame and passed on to the #new-attachment-id hidden field
// Ensure the mime type matches too
if ( !empty($new_attachment_id) && is_numeric( $new_attachment_id ) && $old_post_mime == $new_post_mime ) {
$new_attachment_meta = wp_get_attachment_metadata( $new_attachment_id );
// If original file is larger than 2560 pixel
// https://make.wordpress.org/core/2019/10/09/introducing-handling-of-big-images-in-wordpress-5-3/
if ( array_key_exists( 'original_image', $new_attachment_meta ) ) {
// Get the original media file path
$new_media_file_path = wp_get_original_image_path( $new_attachment_id );
} else {
// Get the path to newly uploaded media file. An image file name may end with '-scaled'.
$new_attachment_file = get_post_meta( $new_attachment_id, '_wp_attached_file', true );
$upload_dir = wp_upload_dir();
$new_media_file_path = $upload_dir['basedir'] . '/' . $new_attachment_file;
}
// Check if the new media file exist / was successfully uploaded
if ( !is_file( $new_media_file_path ) ) {
return false;
}
// Delete existing/old media files. Post and post meta entries for it are still there in the database.
$this->delete_media_files( $old_attachment_id );
// If original file is larger than 2560 pixel
// https://make.wordpress.org/core/2019/10/09/introducing-handling-of-big-images-in-wordpress-5-3/
if ( array_key_exists( 'original_image', $new_attachment_meta ) ) {
// Get the original media file path
$old_media_file_path = wp_get_original_image_path( $old_attachment_id );
} else {
// Get the path to the old/existing media file that will be replaced and deleted. An image file name may end with '-scaled'.
$old_attachment_file = get_post_meta( $old_attachment_id, '_wp_attached_file', true );
$old_media_file_path = $upload_dir['basedir'] . '/' . $old_attachment_file;
}
// Check if the directory path to the old media file is still intact
if ( !file_exists( dirname( $old_media_file_path ) ) ) {
// Recreate the directory path
mkdir( dirname( $old_media_file_path ), 0755, true );
}
// Copy the new media file into the old media file's path
copy( $new_media_file_path, $old_media_file_path );
// Regenerate attachment meta data and image sub-sizes from the new media file that was just copied to the old path
$old_media_post_meta_updated = wp_generate_attachment_metadata( $old_attachment_id, $old_media_file_path );
// Update new media file's meta data with the ones from the old media. i.e. new media file will carry over the post ID and post meta of the old media file. i.e. only the files are replaced for the old media's ID and post meta in the database.
wp_update_attachment_metadata( $old_attachment_id, $old_media_post_meta_updated );
// Delete the newly uploaded media file and it's sub-sizes, and also delete post and post meta entries for it in the database.
wp_delete_attachment( $new_attachment_id, true );
// Add old attachment ID to recently replaced media option. This will be used for cache busting to ensure the new replacement images are immediately loaded in the browser / wp-admin
$extra_options = get_option( 'admin_site_enhancements_extra', array() );
$recently_replaced_media = ( isset( $extra_options['recently_replaced_media'] ) ? $extra_options['recently_replaced_media'] : array() );
if ( count( $recently_replaced_media ) >= 5 ) {
// Remove first/oldest attachment ID
array_shift( $recently_replaced_media );
}
$recently_replaced_media[] = $old_attachment_id;
$recently_replaced_media = array_unique( $recently_replaced_media );
$extra_options['recently_replaced_media'] = $recently_replaced_media;
update_option( 'admin_site_enhancements_extra', $extra_options );
}
}
/**
* Delete the existing/old media files when performing media replacement
*
* @link https://plugins.trac.wordpress.org/browser/replace-image/tags/1.1.7/hm-replace-image.php#L80
* @since 1.1.0
*/
public function delete_media_files( $post_id )
{
$attachment_meta = wp_get_attachment_metadata( $post_id );
// Will get '-scaled' version if it exists, e.g. /path/to/uploads/year/month/file-name.jpg
$attachment_file_path = get_attached_file( $post_id );
// e.g. file-name.jpg
$attachment_file_basename = basename( $attachment_file_path );
// Delete intermediate images if there are any
if ( isset( $attachment_meta['sizes'] ) && is_array( $attachment_meta['sizes'] ) ) {
foreach ( $attachment_meta['sizes'] as $size => $size_info ) {
// /path/to/uploads/year/month/file-name.jpg --> /path/to/uploads/year/month/file-name-1024x768.jpg
$intermediate_file_path = str_replace( $attachment_file_basename, $size_info['file'], $attachment_file_path );
wp_delete_file( $intermediate_file_path );
}
}
// Delete the attachment file, which maybe the '-scaled' version
wp_delete_file( $attachment_file_path );
// If original file is larger than 2560 pixel
// https://make.wordpress.org/core/2019/10/09/introducing-handling-of-big-images-in-wordpress-5-3/
if ( array_key_exists( 'original_image', $attachment_meta ) ) {
$attachment_original_file_path = wp_get_original_image_path( $post_id );
// Delete the original file
wp_delete_file( $attachment_original_file_path );
}
}
/**
* Customize the attachment updated message
*
* @link https://github.com/WordPress/wordpress-develop/blob/6.0.2/src/wp-admin/edit-form-advanced.php#L180
* @since 1.1.0
*/
public function attachment_updated_custom_message( $messages )
{
$new_messages = array();
foreach ( $messages as $post_type => $messages_array ) {
if ( $post_type == 'attachment' ) {
// Message ID for successful edit/update of an attachment is 4. e.g. /wp-admin/post.php?post=a&action=edit&classic-editor&message=4 Customize it here.
$messages_array[4] = 'Media file updated. You may need to hard refresh your browser to see the updated media preview image below.';
}
$new_messages[$post_type] = $messages_array;
}
return $new_messages;
}
/**
* Append cache busting parameter to the end of image srcset
*
* @since 5.7.0
*/
public function append_cache_busting_param_to_image_srcset(
$sources,
$size_array,
$image_src,
$image_meta,
$attachment_id
)
{
$extra_options = get_option( 'admin_site_enhancements_extra', array() );
$recently_replaced_media = ( isset( $extra_options['recently_replaced_media'] ) ? $extra_options['recently_replaced_media'] : array() );
if ( is_admin() && in_array( $attachment_id, $recently_replaced_media ) ) {
foreach ( $sources as $size => $source ) {
$source['url'] .= (( false === strpos( $source['url'], '?' ) ? '?' : '&' )) . 't=' . time();
$sources[$size] = $source;
}
}
return $sources;
}
/**
* Append cache busting parameter to the end of image src
*
* @since 5.7.0
*/
public function append_cache_busting_param_to_attachment_image_src( $image, $attachment_id )
{
$extra_options = get_option( 'admin_site_enhancements_extra', array() );
$recently_replaced_media = ( isset( $extra_options['recently_replaced_media'] ) ? $extra_options['recently_replaced_media'] : array() );
if ( is_admin() && !empty($image[0]) && in_array( $attachment_id, $recently_replaced_media ) ) {
$image[0] .= (( false === strpos( $image[0], '?' ) ? '?' : '&' )) . 't=' . time();
}
return $image;
}
/**
* Append cache busting parameter to image src for js
*
* @since 5.7.0
*/
public function append_cache_busting_param_to_attachment_for_js( $response, $attachment )
{
$extra_options = get_option( 'admin_site_enhancements_extra', array() );
$recently_replaced_media = ( isset( $extra_options['recently_replaced_media'] ) ? $extra_options['recently_replaced_media'] : array() );
if ( is_admin() && in_array( $attachment->ID, $recently_replaced_media ) ) {
if ( false !== strpos( $response['url'], '?' ) ) {
$response['url'] .= (( false === strpos( $response['url'], '?' ) ? '?' : '&' )) . 't=' . time();
}
if ( isset( $response['sizes'] ) ) {
foreach ( $response['sizes'] as $size_name => $size ) {
$response['sizes'][$size_name]['url'] .= (( false === strpos( $size['url'], '?' ) ? '?' : '&' )) . 't=' . time();
}
}
}
return $response;
}
/**
* Add SVG mime type for media library uploads
*
* @link https://developer.wordpress.org/reference/hooks/upload_mimes/
* @since 2.6.0
*/
public function add_svg_mime( $mimes )
{
global $roles_svg_upload_enabled ;
$current_user = wp_get_current_user();
$current_user_roles = (array) $current_user->roles;
// single dimensional array of role slugs
if ( count( $roles_svg_upload_enabled ) > 0 ) {
// Add mime type for user roles set to enable SVG upload
foreach ( $current_user_roles as $role ) {
if ( in_array( $role, $roles_svg_upload_enabled ) ) {
$mimes['svg'] = 'image/svg+xml';
}
}
}
return $mimes;
}
/**
* Check and confirm if the real file type is indeed SVG
*
* @link https://developer.wordpress.org/reference/functions/wp_check_filetype_and_ext/
* @since 2.6.0
*/
public function confirm_file_type_is_svg(
$filetypes_extensions,
$file,
$filename,
$mimes
)
{
global $roles_svg_upload_enabled ;
$current_user = wp_get_current_user();
$current_user_roles = (array) $current_user->roles;
// single dimensional array of role slugs
if ( count( $roles_svg_upload_enabled ) > 0 ) {
// Check file extension
if ( substr( $filename, -4 ) == '.svg' ) {
// Add mime type for user roles set to enable SVG upload
foreach ( $current_user_roles as $role ) {
if ( in_array( $role, $roles_svg_upload_enabled ) ) {
$filetypes_extensions['type'] = 'image/svg+xml';
$filetypes_extensions['ext'] = 'svg';
}
}
}
}
return $filetypes_extensions;
}
/**
* Sanitize the SVG file and maybe allow upload based on the result
*
* @since 2.6.0
*/
public function sanitize_and_maybe_allow_svg_upload( $file )
{
if ( !isset( $file['tmp_name'] ) ) {
return $file;
}
$file_tmp_name = $file['tmp_name'];
// full path
$file_name = ( isset( $file['name'] ) ? $file['name'] : '' );
$file_type_ext = wp_check_filetype_and_ext( $file_tmp_name, $file_name );
$file_type = ( !empty($file_type_ext['type']) ? $file_type_ext['type'] : '' );
// Load sanitizer library - https://github.com/darylldoyle/svg-sanitizer
$sanitizer = new Sanitizer();
if ( 'image/svg+xml' === $file_type ) {
$original_svg = file_get_contents( $file_tmp_name );
$sanitized_svg = $sanitizer->sanitize( $original_svg );
// boolean
if ( false === $sanitized_svg ) {
$file['error'] = 'This SVG file could not be sanitized, so, was not uploaded for security reasons.';
}
file_put_contents( $file_tmp_name, $sanitized_svg );
}
return $file;
}
/**
* Generate metadata for the svg attachment
*
* @link https://developer.wordpress.org/reference/functions/wp_generate_attachment_metadata/
* @since 2.6.0
*/
public function generate_svg_metadata( $metadata, $attachment_id, $context )
{
if ( get_post_mime_type( $attachment_id ) == 'image/svg+xml' ) {
// Get SVG dimensions
$svg_path = get_attached_file( $attachment_id );
$svg = simplexml_load_file( $svg_path );
$width = 0;
$height = 0;
if ( $svg ) {
$attributes = $svg->attributes();
if ( isset( $attributes->width, $attributes->height ) ) {
$width = intval( floatval( $attributes->width ) );
$height = intval( floatval( $attributes->height ) );
} elseif ( isset( $attributes->viewBox ) ) {
$sizes = explode( ' ', $attributes->viewBox );
if ( isset( $sizes[2], $sizes[3] ) ) {
$width = intval( floatval( $sizes[2] ) );
$height = intval( floatval( $sizes[3] ) );
}
}
}
$metadata['width'] = $width;
$metadata['height'] = $height;
// Get SVG filename
$svg_url = wp_get_original_image_url( $attachment_id );
$svg_url_path = str_replace( wp_upload_dir()['baseurl'] . '/', '', $svg_url );
$metadata['file'] = $svg_url_path;
}
return $metadata;
}
/**
* Return svg file URL to show preview in media library
*
* @link https://developer.wordpress.org/reference/hooks/wp_ajax_action/
* @link https://developer.wordpress.org/reference/functions/wp_get_attachment_url/
* @since 2.6.0
*/
public function get_svg_attachment_url()
{
$attachment_url = '';
$attachment_id = ( isset( $_REQUEST['attachmentID'] ) ? $_REQUEST['attachmentID'] : '' );
// Check response mime type
if ( $attachment_id ) {
$attachment_url = wp_get_attachment_url( $attachment_id );
echo $attachment_url ;
die;
}
}
/**
* Return svg file URL to show preview in media library
*
* @link https://developer.wordpress.org/reference/functions/wp_prepare_attachment_for_js/
* @since 2.6.0
*/
public function get_svg_url_in_media_library( $response )
{
// Check response mime type
if ( $response['mime'] === 'image/svg+xml' ) {
$response['image'] = array(
'src' => $response['url'],
);
}
return $response;
}
/**
* Add external permalink meta box for enabled post types
*
* @since 3.9.0
*/
public function add_external_permalink_meta_box( $post_type, $post )
{
$options = get_option( ASENHA_SLUG_U, array() );
$enable_external_permalinks_for = $options['enable_external_permalinks_for'];
foreach ( $enable_external_permalinks_for as $post_type_slug => $is_external_permalink_enabled ) {
if ( get_post_type() == $post_type_slug && $is_external_permalink_enabled ) {
// Skip adding meta box for post types where Gutenberg is enabled
// if (
// function_exists( 'use_block_editor_for_post_type' )
// && use_block_editor_for_post_type( $post_type_slug )
// ) {
// continue; // go to the beginning of next iteration
// }
add_meta_box(
'asenha-external-permalink',
// ID of meta box
'External Permalink',
// Title of meta box
[ $this, 'output_external_permalink_meta_box' ],
// Callback function
$post_type_slug,
// The screen on which the meta box should be output to
'normal',
// context
'high'
);
}
}
}
/**
* Render External Permalink meta box
*
* @since 3.9.0
*/
public function output_external_permalink_meta_box( $post )
{
?>
Keep empty to use the default WordPress permalink. External permalink will open in a new browser tab.