Wordpress auto-generated "canonical" links - how to add a custom URL parameter? - wordpress

Does anyone know how to modify the Wordpress canonical links to add a custom URL parameter?
I have a Wordpress site with a page that queries a separate (non-Wordpress) database. I passed the URL parameter "pubID" to display individual books and it is working OK.
Example: http://www.uglyducklingpresse.org/catalog/browse/item/?pubID=63
But the individual book pages are not showing up properly in Google - the ?pubID parameter is stripped out.
I think maybe this is because all the item pages have the same auto-generated "canonical" URL link tag in the source - one with the "pubID" parameter stripped out.
Example: link rel='canonical' href='http://www.uglyducklingpresse.org/catalog/browse/item/'
Is there a way to perhaps edit .htaccess to add a custom URL parameter to Wordpress, so that the parameter is not stripped out by permalinks and the "canonical" links?
Or maybe there's another solution ... Thank you for any ideas!

You should be able to replace Wordpress's rel_canonical action function with your own function in which (when your conditions are meet) you create a canonical link appending the query string variable. The following should work, although you'll probably need to change the conditions to meet your needs.
remove_action('wp_head', 'rel_canonical');
add_action('wp_head', 'my_rel_canonical');
function my_rel_canonical() {
if (is_page('item') && isset($_GET['pubID'])) {
global $post;
$link = get_permalink($post->ID) . '?pubID=' . absint($_GET['pubID']);
echo "<link rel='canonical' href='$link' />\n";
} else {
rel_canonical();
}
}

Related

Wordpress add rewrite rule doesn't work for me

I'm developing a plugin that creates 2 pages: one listing page and one details page.
I don't use custom types. I have created a table into the database where I save the company details and also a slug for the details page.
It's working properly but I have a problem with the URLs. They are not pretty.
On the listing page I use this code to create the link:
<?php echo stripslashes($value->company_name); ?>
The generated link looks like this:
https://www.website.com/company/details/?companyname=new-company-name
I use the query because I need it on the details page, where I use this code:
$company_slug = $_GET['companyname'];
$company_details = $wpdb->get_row("SELECT * FROM $table_company WHERE company_slug = '$company_slug'");
This is how I retrieve the company details from sql and it also works just fine.
I have created manually in Wordpress the details page.
The problem is that I want the details URL to look pretty, like this:
https://www.website.com/company/details/new-company-name/
Generating it like this it's easy but when I click, I get a 404, since the query from URL is missing.
I was thinking it's easy to create directly the pretty URL and on the details page to parse the URL and get the company slug. It didn't work. I get a 404 maybe because the page doesn't physically exist.
So, I've done some research about URL rewrite and I have found some examples but none worked.
I have found tried this code also:
add_filter('query_vars', function($vars) {
$vars[] = "companyname";
return $vars;
});
function custom_rewrite_rule() {
add_rewrite_rule('^companyname/?([^/]*)/?','company/details/?companyname=$matches[1]','top');
}
add_action('init', 'custom_rewrite_rule', 10, 0);
I've read that I shouldn't use matches if I use a custom URL instead of index.php, so I have also tried without matches:
add_rewrite_rule('^companyname/?([^/]*)/?','company/details/?companyname=$1','top');
No results. If course, after every change I have saved again the permalinks.
This should be an easy task but somehow it doesn't work.
https://developer.wordpress.org/reference/functions/add_rewrite_rule/
Does anyone of you know how can I make this work?
Thank you.
Regards,
AG
I am assuming that the details page you created has the slug company/details. Here's what you need to do to make it work-
1. Add the custom rewrite rules in functions.php file:
function theme_custom_rewrites() {
add_rewrite_tag("%companyname%", "([a-z0-9\-_]+)");
add_rewrite_rule('^company/details/([a-z0-9\-_]+)/?$', 'index.php?pagename=company/details&companyname=$matches[1]', 'top');
}
add_action('init', 'theme_custom_rewrites');
It registers a new rewrite tag/query var named companyname to be used later and registers a custom rewrite rule for the specific URL structure you want (/company/details/company_name).
2. Get the company name on the template file and use it: After you have added the above code and saved the permalinks, you can get the companyname just by using the get_query_var() function.
$companyname = get_query_var( 'companyname' );
Hope it helps. Thanks.
Thank you very much for your fast reply. It worked.
Of course, I had to change the link on the listing page to:
<?php echo stripslashes($value->company_name); ?>
I have removed the query from the link and it looks like this now:
https://www.website.com/company/details/new-company-name/
What I don't understand, is how does WP know which is the query, since I removed it from the link.
I can see the same data if I access
https://www.website.com/company/details/?companyname=new-company-name
or
https://www.website.com/company/details/new-company-name/
But, basically, this part (?companyname=) doesn't exist anymore in the link, since I changed it.
I have no query now in my plugin, but somehow everything works properly. :)
I did not declare it somewhere. It's completely gone and it works.
How does this code know that the query exists and it's retrieving the slug from the database?
$companyname = get_query_var( 'companyname' );
I only have this code now:
<?php echo stripslashes($value->company_name); ?>
So, no query in URL.
Thank you for your time.
Regards,
AG

Wordpress plugin URL rewrite

I have a wordpress plugin which enables me to add events to my website.
However the url structure is e.g.
domain.com/events/cat/event-name
I was looking into the plugin, however I was not able to locate the way how the plugin reacts to that request.
Thus comes my questions:
What different ways are there for a plugin to be called via a certain url structure (like above e.g. all urls which contain "/events/cat" belong to the plugin) ?
I was looking at my .htaccess file but it was unchanged, also i was looking if the plugin uses a
add_action('parse_request', 'handler_action');
But I couldnt find anything. Are there any other ways the plugin could be using?
Thanks a lot!
Its probably using a custom post type using register_post_type function,
this will then build a new URL rewrite rule
The other possible method is by using add_rewrite_rule
something like
add_action('init', 'your_plugin_rules');
function your_plugin_rules() {
add_rewrite_rule( "events/cat/(.+)/?$", 'index.php?events=$matches[1]', "top");
}
if you check and print the value of $wp_rewrite you can see all the rewrite rules
e.g.
add_action('wp_head', function() {
global $wp_rewrite;
echo '</pre>', print_r( $wp_rewrite, 1 ), '</pre>';
});

Custom post type archive root level theming

I'm stuck with a theming question. I have a Custom Post Type (Products) and a Custom Taxonomy (Product Types).
The CPT Archive checks if there are any direct Taxonomy children and if yes, displays them. If not, shows the products. So far, so good. Works fine. (Like a very basic shop system but without any plugin.)
But now I need to change layout of only the root level of the CPT Archive, where there are only child taxonomies visible. This must not affect any other level.
I have no real idea how to go for this.
Which are the filters I am searching for ("if this is the root level of the archive, show....")?
Please create a file in your theme folder with the name archive-custom-post-type.php, like if chef is a custom post type archive-chef.php will be the archive page.
Hope it helps.
In case anybody ever wonders the same, the solution was quite easy actually ;-)
I decided to read out the current wordpress URL for the archive and some research later I found the perfect solution here:
https://roots.io/routing-wp-requests/
Add this function to the functions.php:
function get_current_url() {
// Get current URL path, stripping out slashes on boundaries
$current_url = trim(esc_url_raw(add_query_arg([])), '/');
// Get the path of the home URL, stripping out slashes on boundaries
$home_path = trim(parse_url(home_url(), PHP_URL_PATH), '/');
// If a URL part exists, and the current URL part starts with it...
if ($home_path && strpos($current_url, $home_path) === 0) {
// ... just remove the home URL path form the current URL path
$current_url = trim(substr($current_url, strlen($home_path)), '/');
}
return $current_url;
}
in the archive-cpt.php, a simple if else statement did the job.

Wordpress custorm URL variables causes strange redirect

I'm trying to have custom variables in my URL for Wordpress site. I have read up as much as I could find on the subject and so far have the following in my functions page:
function add_query_vars($aVars) {
$aVars[] = "mrdrct";
return $aVars;
}
// hook add_query_vars function into query_vars
add_filter('query_vars', 'add_query_vars');
And the following on my header page:
if(isset($wp_query->query_vars['mrdrct'])) {
$mVar = $wp_query->query_vars['mrdrct'];
echo "variable is $mVar <br />";
}
Just to test out if things are being passed correctly and they are. However, when I use a link with the url variable in it - say www.mydomain.com/?mrdrct=myVarable - I am not directed to my homepage of my Wordpress site which is set to a static page with a template on it - I am instead directed to a page with my latest posts on it. I cannot figure out why this is happening - any ideas? Hopefully I've explained this well enough.
Thanks.
When WP sees a query string (? after the URL) it will attempt to display matching posts using it's rewrite rules. If no posts match it will show a 404 error - I would guess you do not have a 404.php file, so WP is showing the default which is index.php (see the Wordpress Template Hierarchy for more details on that).
I'm not 100% sure what you want to achieve, but I'd suggest that you need to look at changing the query when $wp_query->query_vars['mrdrct'] is set. See the WP Codex for query_posts() for a good place to start, if you are not already familier with it.

WordPress plugins - don't print the comments on a post page

I'm making a plugin where I want the comments in a single post page not to be printed at all. I need to query the database myself and print my own html with the results.
How can I make WordPress to not print the comments, without disabling them?
Thank you
EDIT:
as a suggestion, I am using:
apply_filters('comments_template', array($this,'comments_template'), 10, 1);
function comments_template($template){
$template = '';
return $template;
}
nothing happens, what am I doing wrong?
You could use the comments_template filter to make WordPress use your plugin's template file rather than the current theme's.
EDIT: based on your edited code: unfortunately you need to have an actual file, the path to which you return in $this->comments_template()...
class MyPlugin{
//add the filter somewhere...
function comments_template($template){
return dirname(__FILE__) . "/my_comments_template.php";
}
}
The file plugin_dir/my_comments_template.php must exist, otherwise WP falls back on the default theme's comments.php. See wp-includes/comment-template.php on lines 911-917.
In plugin_dir/my_comments_template.php you could call `MyPlugin::do_comments() or something like that. I don't know any other way around this. Let me know if you find a better way.
Cheers, Chris

Resources