Wordpress Replace words in already existed Posts - php

I have multiple words that i need to replace on posts that they are already added on the WordPress, but I don't want to change the full content, I need only the WordPress post output.
I have this code but is not working ... and I can't find how WordPress working about this ...
function SC_Replace_Words_On_Posts() {
$Replace_Words_Array = array(
'aaa' => 'aa',
);
if( isset($_REQUEST['post_id']) ) {
$Post_ID = $_REQUEST['post_id'];
} else {
$Post_ID = false;
}
$Post_Content = get_post_field('post_content', $Post_ID);
if($Post_Content != '' && is_array($Replace_Words_Array) && !empty($Replace_Words_Array)) {
foreach($Replace_Words_Array as $Find_Word => $Replace_Word) {
$Post_Content = SC_replaceWithCase($Find_Word, $Replace_Word, $Post_Content);
}
}
return $post;
}
add_filter("wp_insert_post_data", "SC_Replace_Words_On_Posts");

Related

if is amp change internal links to amp version (WordPress)

We use WordPress and would like to link amp to amp if the linked page has an amp version. We have amp structured like that: test.de/test/amp
Unfortunately this code in my functions.php isnt applying to links hard-coded inside of the post content. What do I have to change, so its working for every internal link:
add_filter( 'post_link', function( $url, $post ) {
static $recursing = false;
if ( $recursing ) {
return $url;
}
$recursing = true;
if ( ! function_exists( 'post_supports_amp' ) || ! post_supports_amp( $post ) ) {
return $url;
}
if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
$url = amp_get_permalink( $post->ID );
}
$recursing = false;
return $url;
}, 10, 2 );
At the moment its also applying to the canonical link, which is really bad for seo. How to prevent this?
Add these functions to your theme's 'functions.php'.
/* post link filter */
add_filter( 'post_link', 'change_amp_url', 10, 2 );
function change_amp_url( $url, $postobj ) {
static $recursing = false;
if ( $recursing ) {
return $url;
}
$recursing = true;
if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
if ( function_exists( 'post_supports_amp' ) && post_supports_amp( $postobj ) ) {
$url = amp_get_permalink( $postobj->ID );
}
}
$recursing = false;
return $url;
}
/* content link filter */
add_filter( 'the_content', 'change_amp_url_content' );
function change_amp_url_content($content)
{
$dom = new DOMDocument();
$dom->loadHTML($content);
$tags = $dom->getElementsByTagName('a');
foreach ($tags as $tag) {
$link = $tag->getAttribute('href'); // original url
$extralink = '';
if(stristr($link,'#')) {
$pagelinktemp = explode("#",$link);
$pagelink = $pagelinktemp[0];
$extralink = '#'.$pagelinktemp[1];
} else {
$pagelink = $link;
}
if($pagelink!="") {
$postid = url_to_postid($pagelink);
$postobj = get_post($postid); // getting appropriate post object
if($postobj) {
$newlink = change_amp_url( $pagelink, $postobj ); //new url
}
else {
$newlink = $link;
}
}
else {
$newlink = $link;
}
if($link != $newlink) // change if only links are different
{
$content = str_replace($link, $newlink.$extralink, $content);
}
}
return $content;
}
/* override canonical link */
add_filter( 'wpseo_canonical', 'amp_override_canonical' );
function amp_override_canonical($url) {
if ( substr($url,-4)=="/amp" ) {
$url = substr($url,0,-4);
}
return $url;
}
The first function will provide the AMP URL if exists.
The second one will loop through each URL in the content and change to AMP URL if valid.
The last one will rewrite the canonical URL that displayed via Yoast SEO plugin.
If you want to replace hardcoded links inside of your post content I would suggest you use the "the_content" filter for wordpress.
https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content
add_filter( 'the_content', 'filter_function_name' )
From this you should be able to regular expression match the link and append /amp to it.
Pseudo code example:
function my_the_content_filter($content)
{
if (function_exists('is_amp_endpoint') && is_amp_endpoint()) {
$patterns = array(
//patterns
);
$replacements = array(
//replacements
);
$content = preg_replace($patterns, $replacements, $content);
}
return $content;
}
add_filter('the_content', 'my_the_content_filter');
I have tested the code submitted by Outsource WordPress, and in general it works fine but the 'amp_override_canonical function overwrites all the urls of the page removing the /amp.
I have made some changes to this piece of code but they do not work as I expect. It seems that the 'wpseo_canonical' function is being invoked in a different context.
add_filter( 'wpseo_canonical', 'amp_override_canonical' );
function amp_override_canonical($url) {
if ( substr($url,-4)=="/amp" ) {
$url = substr($url,0,-4);
}
return $url;
}

Change subcategory URL(slug) in Wordpress

I have problem with slug(URL) in category/subcategory. Now i have: http://my-page.pl/animal-category/animal-subcategory. How can i delete "animal-category" for every subcategory ?
It should look like that:
http://my-page.pl/animal-category/
http://my-page.pl/animal-subcategory/
http://my-page.pl/animal-subcategory/single-page
Maybe it's simple question, but I cant find answer anywhere :)
Check below code it will help you
// Add 'cat_redirect' query variable in query_vars
add_filter('query_vars', 'no_parent_cat_query_vars');
function no_parent_cat_query_vars($query_vars) {
$query_vars[] = 'cat_redirect';
return $query_vars;
}
// Redirect if 'cat_redirect' is set
add_filter('request', 'no_parent_cat_request');
function no_parent_cat_request($query_vars) {
if(isset($query_vars['cat_redirect'])) {
$cat_link = trailingslashit(get_option( 'home' )) . user_trailingslashit( $query_vars['cat_redirect'], 'category' );
status_header(301);
header("Location: $cat_link");
exit();
}
return $query_vars;
}
// Remove category
add_filter('category_link', 'category_url_without_parent',1000,2);
function category_url_without_parent($cat_link, $cat_id)
{
$category = &get_category( $cat_id );
if ( is_wp_error( $category ) ) return $category;
$catname = $category->slug;
$cat_link = trailingslashit(get_option( 'home' )) . user_trailingslashit( $catname, 'category' );
return $cat_link;
}
// Add custom category rewrite rule
add_filter('category_rewrite_rules', 'remove_category_parent_rule');
function remove_category_parent_rule($cat_rewrite) {
global $wp_rewrite;
$cat_rewrite=array();
$cat_list=get_categories(array('hide_empty'=>false));
foreach($cat_list as $category) {
$catname = $category->slug;
$cat_rewrite['('.$catname.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
$cat_rewrite['('.$catname.')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
$cat_rewrite['('.$catname.')/?$'] = 'index.php?category_name=$matches[1]';
}
$old_base = $wp_rewrite->get_category_permastruct();
$old_base = str_replace( '%category%', '(.+)', $old_base );
$old_base = trim($old_base, '/');
$cat_rewrite[$old_base.'$'] = 'index.php?cat_redirect=$matches[1]';
return $cat_rewrite;
}

Custom Post Type Specific Media - WordPress

I have created a custom post type in WordPress but wondering if its possible to specify an upload directory specific to the custom post type and when doing and inserting of media that the media library only show the media uploaded into the specific directory for the custom post type.
save images in and media library only shows media in:
/wp-content/uplodas/custom_post_type/
UPDATE
I have the following code which will filter the content i'm looking for HOWEVER i only want to run the filter if im on the CPT of client_gallery. My if statment doesnt seem to work?
function wpse48677_get_cpt()
{
if ($_GET['post_type'] == "") {
$posts = $_GET['post'];
$postType = get_post_type($posts);
} else {
$postType = $_GET['post_type'];
}
return $postType;
}
function my_posts_where($where)
{
global $wpdb;
$post_id = false;
if (isset($_POST['post_id'])) {
$post_id = $_POST['post_id'];
$post = get_post($post_id);
if ($post) {
$where .= $wpdb->prepare(" AND my_post_parent.post_type = %s ", $post->post_type);
}
}
return $where;
}
function my_posts_join($join)
{
global $wpdb;
$join .= " LEFT JOIN {$wpdb->posts} as my_post_parent ON ({$wpdb->posts}.post_parent = 'client_gallery') ";
return $join;
}
function my_bind_media_uploader_special_filters($query)
{
add_filter('posts_where', 'my_posts_where');
add_filter('posts_join', 'my_posts_join');
return $query;
}
print wpse48677_get_cpt();
if(wpse48677_get_cpt() == 'client_gallery') {
// THIS IF STATEMENT DOESNT SEEM TO WORK? I KNOW $doJoin == client_gallery
// AS I CAN SEE IT IF I PRINT IT OUT (see above)
// IF I RUN THE ADD FILTER WITHOUT THE IF I GET THE RESULTS I"M LOOKING FOR?????
add_filter('ajax_query_attachments_args', 'my_bind_media_uploader_special_filters');
}
you will make an upload dir for your custom post type if you add this code wherever your custom post type declaration happens. this will also use this folder everytime your upload happens from a post where the post type is yours.
function super_upload_dir( $args ) {
if(!isset($_REQUEST['post_id']) || get_post_type( $id ) != $YOUR_POST_TYPE)
return $args;
$id = ( isset( $_REQUEST['post_id'] ) ? $_REQUEST['post_id'] : '' );
if( $id ) {
$newdir = '/' . $DIRECTORY_NAME;
$args['path'] = str_replace( $args['subdir'], '', $args['path'] );
$args['url'] = str_replace( $args['subdir'], '', $args['url'] );
$args['subdir'] = $newdir;
$args['path'] .= $newdir;
$args['url'] .= $newdir;
}
return $args;
}
add_filter( 'upload_dir', 'super_upload_dir' );
for the librairy filter, ive used plugins in the past that had a way to filter media items based on a shortcode, but i wouldnt know off the bat what to do to get it filtered based on current post type in the backend. sorry

Multiple if Statements issue

I am having a problem with multiple if statements. I am using && but it seems to only work for the first statement.
The code is like such:
global $post;
$args = array( 'post_id' => $post->ID );
$comment = get_comments( $args );
$user = wp_get_current_user();
if ( 3 <= count( $comment ) && $post->post_author == $user->ID) {
echo do_shortcode( '[button]' );
} else {
comment_form();
}
It basically stats that if there is less than 3 comments then show the comment form but if there is more than 3 and is the post author then show a button. The button shows but only if there are more than 3 comments. It doesn't check if it is only the post author or not, like I want it to.
What you are describing are two cases in which the button should be showed. So there have to be two ways to get into the if-block. You have to refactor your if-statement with the logical or-operator ||.
for example:
if($post->post_author == $user->ID || 3 <= count($comment)) {
echo do_shortcode( '[button]' );
} else {
comment_form();
}
I had to change the code like so to get it to work.
global $post,$current_user;
$args = array( 'post_id' => $post->ID );
$comment = get_comments( $args );
get_currentuserinfo();
if ($post->post_author == $current_user->ID ) {
echo do_shortcode( '[button]' );
} elseif ( 3 <= count( $comment ) ) {
// blank
} else {
comment_form();
}

Wordpress csv import duplicate

I've used an adapted version of a csv import plugin for wordpress. It imports the csv to create and update posts. To update existing posts I've added an edit that finds the post id by title, then if it exists it overwrites, otherwise it creates a new post.
Problem is that it seems to not be very reliable! If I import the same csv several times it over-writes most of them but I get a few duplicates. Is there any way I can make this more reliable, or is there another way I can deal with duplicate posts?
main function for creating posts here
function create_post($data, $options) {
extract($options);
//edit 1 added here
global $wpdb;
//end
$data = array_merge($this->defaults, $data);
$type = $data['csv_post_type'] ? $data['csv_post_type'] : 'post';
$valid_type = (function_exists('post_type_exists') &&
post_type_exists($type)) || in_array($type, array('post', 'page'));
if (!$valid_type) {
$this->log['error']["type-{$type}"] = sprintf(
'Unknown post type "%s".', $type);
}
$new_post = array(
'post_title' => convert_chars($data['csv_post_title']),
'post_content' => wpautop(convert_chars($data['csv_post_post'])),
'post_status' => $opt_draft,
'post_type' => $type,
'post_date' => $this->parse_date($data['csv_post_date']),
'post_excerpt' => convert_chars($data['csv_post_excerpt']),
'post_name' => $data['csv_post_slug'],
'post_author' => $this->get_auth_id($data['csv_post_author']),
'tax_input' => $this->get_taxonomies($data),
'post_parent' => $data['csv_post_parent'],
);
// edit 2 here
$new_post['ID'] = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $data['csv_post_title'] . "'" );
// ends
// pages don't have tags or categories
if ('page' !== $type) {
$new_post['tags_input'] = $data['csv_post_tags'];
// Setup categories before inserting
$cats = $this->create_or_get_categories($data, $opt_cat);
$new_post['post_category'] = $cats['post'];
}
// edit 3
if(!empty($new_post['ID'])) {
$id = wp_update_post($new_post);
} else {
$id = wp_insert_post($new_post);
}
// ends
if ('page' !== $type && !$id) {
// cleanup new categories on failure
foreach ($cats['cleanup'] as $c) {
wp_delete_term($c, 'category');
}
}
return $id;
}
thanks
Fixed! I used the built in wordpress function, get_page_by_title . Here is the code I used to target the correct post.
if (!get_page_by_title( $bpp_title, 'OBJECT', 'publications')) {
$id = wp_insert_post($new_post);
} else {
$bpp_page = get_page_by_title( $bpp_title, 'OBJECT', 'publications');
$new_post['ID'] = $bpp_page->ID;
$id = wp_update_post($new_post);
}

Categories