How to create a permalink based on the text entered (using PHP code) - permalinks

My code is like this
<script>
function doDashes2(str) {
return str.replace(/[^a-z0-9]+/gi, '-').replace(/^-*|-*$/g, '').toLowerCase();
}
str="this permalink! __is_ created, using javascript (jQuery)";
alert(doDashes2(str));
</script>
The output comes as "this-permalink-is-created-using-javascript-jquery"
Can anybody suggest, how to do it using PHP

use this.
function sterilize($title)
{
$result = strtolower($title);
// strip all non word chars
$result = preg_replace('/\W/', ' ', $result);
// replace all white space sections with a dash
$result = preg_replace('/\ +/', '-', $result);
// trim dashes
$result = preg_replace('/\-$/', '', $result);
$result = preg_replace('/^\-/', '', $result);
return $result;
}

Related

Replace space with hyphen for image filename on upload

I'm using the code bellow (I found it here on stack overflow from this post) to auto rename image filename and fill alt and title field based on post title.
The good thing is it's working, it's doing its job but problem is with filename : it's using post title with spaces, comas, etc. as filename, which is really not good. It's perfect for filling the title and alt fields but not for a filename.
So, just for the filename, I would like to add something to replace spaces by hyphen (and if possible remove potentials comas or other punctuation)
I thought that the part add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 ); would to the job, but it's not.
But as I'm really not sure what I'm doing, and as I have poor PHP knowledge, I would be very grateful if you could teach me how to make it work :
function file_renamer( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
if( $post_id = array_key_exists("post_id", $_POST) ? $_POST["post_id"] : null) {
if($post = get_post($post_id)) {
return $post->post_title . $ext;
}
}
$my_image_title = $post;
$file['name'] = $my_image_title . - uniqid() . $ext; // uniqid method
// $file['name'] = md5($name) . $ext; // md5 method
// $file['name'] = base64_encode($name) . $ext; // base64 method
return $filename;
}
add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 );
/* Automatically set the image Title, Alt-Text, Caption & Description upon upload */
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
// Get the parent post ID, if there is one
if( isset($_REQUEST['post_id']) ) {
$post_id = $_REQUEST['post_id'];
} else {
$post_id = false;
}
if ($post_id != false) {
$my_image_title = get_the_title($post_id);
} else {
$my_image_title = get_post( $post_ID )->post_title;
}
// Sanitize the title: remove hyphens, underscores & extra spaces:
$my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title );
// Create an array with the image meta (Title, Caption, Description) to be updated
// Note: comment out the Excerpt/Caption or Content/Description lines if not needed
$my_image_meta = array(
'ID' => $post_ID, // Specify the image (ID) to be updated
'post_title' => $my_image_title, // Set image Title to sanitized title
'post_content' => $my_image_title, // Set image Description (Content) to sanitized title
);
// Set the image Alt-Text
update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
// Set the image meta (e.g. Title, Excerpt, Content)
wp_update_post( $my_image_meta );
}
}
Thanks for your help !
So solution was replacing post_title by post_name in file_renamer function.
Exactly this part : change return $post->post_title . $ext; and replace it with return $post->post_name . $ext;
And it's working. On upload, this function is renaming the file name with hyphens and filling title, alt text and description fields based on Post Title (without hyphens).

WORDPRESS Get Filename to use as ALT

I have been using this code to set alt text to equal the title as the alt text is missing. Previously though I had used $attr['alt'] = $attr['title']; in order to use the filename as alt. It, however contains hyphens, so now I am trying to find a different way to get the filename.
I have read quite a few suggestions on how to retrieve the filename but so far nothing is working. Would also like to remove the file extension.
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes($attr, $attachment) {
global $post;
$product = wc_get_product( $post->ID );
if ($post->post_type == 'product') {
$image_id = get_post_thumbnail_id();
$image_filename = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
$attr['alt'] = basename($image_filename);
}
return $attr;
}
How can I achieve this?
Assuming your current code works (I have not tested it) you can simply replace hyphens in title with spaces:
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes($attr, $attachment) {
global $post;
$product = wc_get_product( $post->ID );
if ($post->post_type == 'product') {
$image_id = get_post_thumbnail_id();
$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
$attr['alt'] = str_replace("-", " ", $attr['title']);
}
return $attr;
}

Conditionally change upload directory on XMLRPC call according to username

I've searched seemingly every relevant question on this but I'm stuck, as none of them address the particular case of uploads through XML RPC.
I want to conditionally change the Wordpress file upload directory, only if the file is coming in through an XML RPC call and only if the call is coming in from a particular user.
My approach is based on a combination of this Answer, this Answer and the Codex.
Here's what I tried with no luck:
add_filter( 'xmlrpc_methods', 'call_intercept1' );
function call_intercept1( $methods ) {
$methods[ 'metaWeblog.newMediaObject' ] = 'custom_upload1';
return $methods;}
function custom_upload1( $args ) {
global $wpdb;
$username = $this->escape( $args[1] );
$password = $this->escape( $args[2] );
$data = $args[3];
$name = sanitize_file_name( $data['name'] );
$type = $data['type'];
$bits = $data['bits'];
if ( !$user = $this->login($username, $password) )
return $this->error;
if ( $username = "XXX" ) {
add_filter('upload_dir', 'custom_upload_dir1');
}
$upload = wp_upload_bits($name, null, $bits);
if ( ! empty($upload['error']) ) {
/* translators: 1: file name, 2: error message */
$errorString = sprintf( __( 'Could not write file %1$s (%2$s).' ), $name, $upload['error'] );
return new IXR_Error( 500, $errorString );
}
return $upload;
}
function custom_upload_dir1( $param ){
$custom_dir = '/the-desired-directory';
$param['path'] = $param['path'] . $custom_dir;
$param['url'] = $param['url'] . $custom_dir;
error_log("path={$param['path']}");
error_log("url={$param['url']}");
error_log("subdir={$param['subdir']}");
error_log("basedir={$param['basedir']}");
error_log("baseurl={$param['baseurl']}");
error_log("error={$param['error']}");
return $param;
}
The file is being uploaded correctly, but the conditional directory change isn't happening.
Does someone know why that would be?
I was able to get this worked out, essentially using Ulf B's Custom Upload Dir as a model and simplifying it from there.
For anyone else facing the same problem, here's what works:
// XMLRPC Conditional Upload Directory
add_action('xmlrpc_call', 'redirect_xmlrpc_call');
function redirect_xmlrpc_call($call){
if($call !== 'metaWeblog.newMediaObject'){return;}
global $wp_xmlrpc_server;
$username = $wp_xmlrpc_server->message->params[1];
$data = $wp_xmlrpc_server->message->params[3];
if($username !== "XXX"){return;}
else {custom_pre_upload($data);}}
function custom_pre_upload($data){
add_filter('upload_dir', 'custom_upload_dir');
return $data;}
function custom_post_upload($fileinfo){
remove_filter('upload_dir', 'custom_upload_dir');
return $fileinfo;}
function custom_upload_dir($path){
if(!empty($path['error'])) { return $path; } //error; do nothing.
$customdir = '/' . 'your-directory-name';
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;}

How to update wordpress content

add_filter('the_content','filter_trendland_content');
//create a the function to get the content of the page by using the hook the_content
function filter_trendland_content($content) {
$getdata = $content;
if ( preg_match_all( '#(?:<a.+?href=["|\'](?P<link_url>.+?)["|\'].*?>\s*)?(?P<img_tag><img.+?src=["|\'](?P<img_url>.+?)["|\'].*?>){1}(?:\s*</a>)?#is', $getdata, $images ) ) {
foreach ( $images[img_url] as $key => $value) {
$subdomain = rand( 1, 3 );
$newurl="yaseen.media$subdomain.com";
$content = preg_replace('/\bmedia.trendland.com\b/', $newurl, $value);
print $content;
}
print $getdata;
}
//return $getdata;
}
I am using the above method to replace the url's with the new one and update the content of the page but the page content is still the same so please help me with this..
Looking at your function, it does not return a value.
Instead of printing the output, return the content back to the filter.
Also, you are iterating through an empty object - $images[img_url]. Check the documentation for preg_match_all. It returns a multi-dimensional array of matches.
You code looks over-engineered and the word boundary in your regex would probably prevent a match. The following may achieve what you need providing that all instances of media.trendland.com require replacing.
function filter_trendland_content($content) {
$subdomain = rand( 1, 3 );
$newurl='yaseen.media' . $subdomain . '.com';
$content = preg_replace('/media.trendland.com/', $newurl, $content);
return $content;
}

Preg_split screws up the BR tag?

I am struggling with this one for half a day now and i can't seem to get it right. I have a custom function in my wordpress site, that automatically creates an excerpt. This all goes well, but for some (i guess logical) reason it also cuts off the <br /> tag, since it has a space.
How to fix this? This has to do with the preg_split function right?
Below is my code:
function custom_wp_trim_excerpt($text) {
$raw_excerpt = $text;
if ( '' == $text ) {
//Retrieve the post content.
$text = get_the_content('');
//Delete all shortcode tags from the content.
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$allowed_tags = '<p>,<br>,<br/>,<br />,<a>,<em>,<strong>,<img>'; /*** MODIFY THIS. Add the allowed HTML tags separated by a comma.***/
$text = strip_tags($text, $allowed_tags);
$excerpt_word_count = 40; /*** MODIFY THIS. change the excerpt word count to any integer you like.***/
$excerpt_length = apply_filters('excerpt_length', $excerpt_word_count);
$excerpt_end = ' ' . '...' . '';
$excerpt_more = apply_filters('excerpt_more', ' ' . $excerpt_end);
$words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
if ( count($words) > $excerpt_length && $words ) {
array_pop($words);
$text = implode(' ', $words);
$text = $text . $excerpt_more;
} else {
$text = implode(' ', $words);
}
}
return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_wp_trim_excerpt');
Thanks!
You can add this to make all of the HTML break characters the same:
$text = preg_replace('!<br ?/>!i','<br>',$text);
Before these lines:
$allowed_tags = '<p>,<br>,<a>,<em>,<strong>,<img>'; /*** MODIFY THIS. Add the allowed HTML tags separated by a comma.***/
$text = strip_tags($text, $allowed_tags);
When you're doing preg_split("/[\n\r\t ]+/",$text) you're splitting the space in the break <br /> character.
You can also simplify the regex in the preg_split() statement:
$words = preg_split("!\s+!", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
Since you're allowing the other tags they probably contain spaces too though.

Resources