How to achieve SEO friendly urls with Wordpress and custom parameters - wordpress

I am having a big problem where I cannot use the Linkedin Share button.
One of the reasons is the non friendly URLs I am using.
Basically I have built a plugin for wordpress which shows me jobs.
It is working perfect show the jobs and everything but the link looks like this
www.recruitmentagency.com/job/?id=250
and I want it to look like
www.recruitmentagency.com/job/250
or
www.recruitmentagency.com/job/job-id/250
I tried to add rewrite rules to htaccess with no luck
RewriteRule ^job/([0-9]+)/$ job/?id=$1
RewriteRule ^job-id/([0-9]+)/$ /?id=$1
and none of them worked.
Any solution will be greatly appreciated.

I tried to use the inbuilt system and it is partially working.
However I don't like the way it is doing it so.
Instead of getting the job like
$job_id=$_GET['id'];
I am getting it like
$job_id=wp_query->query_vars['page'];
when the page is load like
www.recruitmentagency.com/job/250
I can't even understand why my supposed job-id is appearing as a page, but I am using it since I need this to work.

I was also facing the same issue. after long time I have reached the below solutions:
add_filter('rewrite_rules_array','job_rewrite_rules_array');
function job_rewrite_rules_array($rules){
$job_page = get_post(123);
$job_rules = array();
if( is_object($job_page) ){
$job_slug = $job_page->post_name;
$job_rules[$job_slug.'/([^/]*)$'] = 'index.php?pagename='.$job_slug.'&jobid=$matches[1]';
}
return $job_rules + $rules;
}
//Bind Query Var
add_filter('query_vars','job_query_vars');
function job_query_vars($vars){
array_push($vars, 'jobid');
return $vars;
}
Execute job_rewrite_flush just one time
function job_rewrite_flush(){
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
add_action('init','job_rewrite_flush');
Now access the param as: $jobid= get_query_var( 'jobid', 1 )
I think the above script work as per your requirement.

Related

How to change members per page in BuddyPress members directory

In BuddyPress, it shows 20 members per members directory page. I want to list 24 members per page with a pagination and sorting must work perfectly. I tried:
bp_has_members(bp_ajax_querystring('members').'per_page=24'))
It works but pagination and sorting are not working correctly.
For those like me wondering how to do this nowadays and ending here after searching with their fav engine, the proper way is to use a filter in bp-custom.php or the functions.php of your theme.
Cf. https://codex.buddypress.org/developer/using-bp_parse_args-to-filter-buddypress-template-loops/
For the member loop it would be something like :
function my_bp_members_per_page( $retval ) {
$retval['per_page'] = 24;
return $retval;
}
add_filter( 'bp_after_has_members_parse_args', 'my_bp_members_per_page' );
Bonus : this will still work if you use cache like WP Rocket.
Former method doesn't work with cache and logged in user.
You need an '&' for each additional argument.
Try:
bp_has_members(bp_ajax_querystring('members').'&per_page=24'))
To modify this file, you make a copy of it and put it into your child-theme
/your-child-theme/buddypress/members/members-loop.php

How bad is $wp_rewrite->flush_rules() on 'init' action hook?

According to the Codex:
[...] This function can be extremely costly in terms of performance. It should be used as sparingly as possible - such as during activation or deactivation of plugins or themes. Every attempt should be made to avoid using it in hooks that execute on each page load, such as init.
Ok, so, I know it shouldn't be used in every page load and I'm not, but I still need a very conditional rewrite rule on this project.
I have these 2 url structures:
- example.com/products/tables/fancy-computer-table //This is a product url, here I expect the normal behavior from wp.
- example.com/products/tables/office //This should be some kind of a filter, where the site gets all the tables related to the office department. Note how both URL structure matches.
To make it work, I narrowed it down to these very specific URLs, using some regex. If matched, I'll run 2 queries to verify if the url I'm in is for the filter I want that rule to apply, or if it's a product url. In the latter, I want wordpress to behave normally. But I have to flush the rules either way, whether it's a product or it's the category and the filter, so that both pages work properly and dinamically.
I do all this to narrow down the use of this function to the least possible, but the Codex doesn't really tell me how bad it does affect the performance, or why.
I'm passing the parameter on that function as false by the way, so it doesn't rewrite my htaccess file, but I'm not sure where that rewrite rule option is stored, if it's on the memory somewhere, or on the database, wish they would provide some clarification on that.
Thanks in advance for reading this question. Any pointers are appreciated here, even if you want to point me to some other way of doing this. :)
EDIT: Posting some code here so you guys can actually understand what I mean and let me know if this maybe this could be bad practice... maybe a suggestion on how to do it better.
<?php function custom_rewrite_products()
{
// regex to match either "products/tables/fancy-computer-table" or "products/tables/office"
preg_match('#products\/([^\/]+)\/([^\/]+)\/?#', $_SERVER['REQUEST_URI'], $url_matches);
if(is_array($url_matches)) {
$query_category = new WP_Query('category_name='.$url_matches[1]);
$query_category->get_posts();
$args = array(
'post_type' => 'filters',
'name' => $url_matches[2]
);
$query_post = new WP_Query($args);
$query_post->get_posts();
if($query_category->have_posts() && $query_post->have_posts()) {
$category_ID = '';
$filter = '';
$category_ID = '' . $query_category->query_vars['cat'] . '';
$filter = '' . $query_post->query_vars['name'] . '';
$string = "index.php?cat={$category_ID}&filter={$filter}";
add_rewrite_rule('products/([^/]+)/([^/]+)/?$', $string, 'top');
}
global $wp_rewrite;
//Call flush_rules() as a method of the $wp_rewrite object
$wp_rewrite->flush_rules(false);
}
}
add_action('init', 'custom_rewrite_products');
I still don't understand why, but the flush is needed here, so the $category_ID and $filter variables actually get passed to the rewrite rules. If I take it out, the rewrite just goes to the index page, the place where the values should be are empty.
In case you're wondering, I created the filters on a custom post type and they are related to each post by using a custom field, since they're like four or five and they're present on every category on this project. As you can see, I already have a category/subcategory structure and I didn't find it smart to create these filters once again by hand inside each main category.
There is a 'rewrite_rules' record in the 'wp_options' table that includes all the rewrite rules. When calling flush_rules(), WordPress will clear this record and regenerate all the new rules, including the ones you're not changing.

how to change form action url for contact form 7?

I'm using Contact Form 7 in a wordpress site with multiple forms.
I need to direct one form to a different form action url than the others.
I found the reply below for a previous thread but I'm not sure how to go about it.
Can someone specify what exact code needs to be included in "additional settings"
and what the code in functions.php would look like?
Thanks for your help!
reply from diff. thread, which I don't completely understand...
*Yes, you have to change the "action" attribute in the form using this Filter Hook wpcf7_form_action_url. (what would be the code?) You could add the hook into your theme's functions.php and then just process the form data in your ASP page.(code?) *
Since you're not familiar with PHP code at all, I'll give you a bit of a crash course in coding within the Wordpress API.
First off, you need to know the difference between functions and variables. A variable is a single entity that is meant to represent an arbitrary value. The value can be anything. A number, somebody's name, or complex data.
A function is something that executes a series of actions to either send back - or return - a variable, or alter a given variable.
<?php
$a = 1; //Number
$b = 'b'; //String *note the quotes around it*
$c = my_function(); //Call to a function called my_function
echo $a; //1
echo $b; //b
echo $c; //oh, hello
function my_function()
{
return 'oh, hello';
}
?>
Wordpress utilizes its own action and filter system loosely based on the Event-Driven Programming style.
What this means is that Wordpress is "listening" for a certain event to happen, and when it does, it executes a function attached to that event (also known as a callback). These are the "Actions" and "Filters". So what's the difference?
Actions are functions that do stuff
Filters are functions that return stuff
So how does this all fit in to your problem?
Contact Form 7 has its own filter that returns the URL of where information is to be sent by its forms.
So lets look at the basics of a Filter Hook
add_filter('hook_name', 'your_filter');
add_filter is the function that tells Wordpress it needs to listen
for a particular event.
'hook_name' is the event Wordpress is listening for.
'your_filter' is the function - or callback - that is called when the 'hook_name' event is fired.
The link to the previous thread states that the hook name you need to be using is 'wpcf7_form_action_url'. That means that all you have to do is make a call to add_filter, set the 'hook_name' to 'wpcf7_form_action_url', and then set 'your_filter' to the name of the function you'll be setting up as your callback.
Once that's done, you just need to define a function with a name that matches whatever you put in place of 'your_filter', and just make sure that it returns a URL to modify the form action.
Now here comes the problem: This is going to alter ALL of your forms. But first thing's first: See if you can get some working code going on your own. Just write your code in functions.php and let us know how it turns out.
UPDATE:
The fact that you were able to get it so quickly is wonderful, and shows the amount of research effort you're putting into this.
Put all of this in functions.php
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url()
{
return 'wheretopost.asp';
}
As mentioned before, that will affect ALL of your forms. If this is only supposed to affect a form on a given page, you can do something like this:
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url($url)
{
global $post;
$id_to_change = 1;
if($post->ID === $id_to_change)
return 'wheretopost.asp';
else
return $url;
}
All you would need to do is change the value of $id_to_change to a number that represents the ID of the Post/Page you're trying to affect. So if - for example - you have an About Page that you would like to change the Action URL, you can find the ID number of your About Page in the Admin Dashboard (just go to the Page editor and look in your URL for the ID number) and change the 1 to whatever the ID number is.
Hope this helps you out, and best of luck to you.
Great answer #maiorano84 but I think you should check form ID instead of Post. Here is my version.
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url($url)
{
$wpcf7 = WPCF7_ContactForm::get_current();
$wpcf7_id = $wpcf7->id();
$form_id = 123;
return $wpcf7_id == $form_id? '/action.php' : $url;
}
Another thing you might need to disable WPCF7 AJAX. That can be disabled by placing the following code in your theme functions.php
apply_filters( 'wpcf7_load_js', '__return_false' );
You can add actions after a successful submission like the documentation says
Adding a filter will work in the sense that it will change the action on the form but unfortunately it will also break the functionality of the plugin. If you add the filter like other answers suggest the form will keep the spinner state after submission.
You can make the form do something else on submit by using advanced settings such as:
on_submit: "alert('submit');"
more details about advanced settings here.
According to #abbas-arif, his solution works great, but have a limitation. This solution change the form's action on all forms present in post with that ID.
A better solution should be to use directly the form's ID. To get it, whit wordpress >5.2, you can use:
add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url($url)
{
$cf7forms = WPCF7_ContactForm::get_current();
$Form = $cf7forms -> id;
switch($Form){
case 1:
return 'destination like salesforce url 1...';
case 2:
return 'destination like salesforce url 2...';
case 3:
return 'destination like salesforce url 3...';
default:
return $url;
}
}

Rewrite wordpress url

I have a url like this
xxxxx.com/?s=&cp_state=Porto&refine_search=yes
and I try to make a url like this
xxxxx.com/Porto
Already tried to use this code:
function search_url_rewrite_rule() {
if ( is_search() && !empty($_GET['s'])) {
wp_redirect(home_url("/search/") . urlencode(get_query_var('s')));
exit();
}
}
add_action('template_redirect', 'search_url_rewrite_rule');
But this code gives me a url like this
xxxxx.com/search/
Could you help me please?
I can't swear this will work but you're looking for something like this:
add_rewrite_rule('([^/]*)/?','index.php?s=&cpstate=$matches[1]&refine_search=yes','top');
I doubt the wisdom of rewriting based on the first segment in the URL, in case you want to switch over to pretty links for the rest of the site later on you will get a lot of odd results. For example example.com/blog would search for blog, example.com/search for search for search and so on... if you want something else you can just edit the regexp so that it fits what you want.
Read more here: http://codex.wordpress.org/Rewrite_API/add_rewrite_rule

Wordpress URL rewrite not working/registering

I've been trying to get my head around Wordpress URL rewrites, but I'm having no luck.
What I want to do:
I building a custom plugin where a user can build products from various options. The options collectively build a code which refers to the unique product the customer has built.
The code might be something like 140-3-WPA-ABC-2.
The plugin will appear on a single dedicated page:
http://wordpress-site/configurator/
I want a customer with a prexisiting code to be able to enter it into the url like this:
http://wordpress-site/configurator/140-3-WPA-ABC-2/
Whereupon, the plugin gets the variable, and uses it to build the correct product.
Problem
It should be fairly simply but I can't get anything to work using the Wordpress URL rewriting rules, I can't even get anything to seemingly get registered as a Wordpress query var.
I've been trying the following in the main plugin initialisation code:
add_filter( 'query_vars', 'conf_query_vars' );
add_action( 'init', 'cong_rewrites' );
function conf_query_vars($query_vars){
$query_vars[] = 'product_code';
return $query_vars;
}
function conf_rewrites(){
add_rewrite_rule(
'configurator/([^/]+)/?$',
'index.php?product_code=$matches[1]',
'top'
);
}
If I then try and open http://wordpress-site/configurator/140-3-WPA-ABC-2/ I get a page not found error. Echoing query_vars seems to show the variable 'product_code' is not created.
ps I've tried flushing the rewrite cache. Apologies for cross-posting to Wordpress.stackexchange.com - but seems programming question better here?
Try this, I had the same problem.
add_action('init', function() {
add_rewrite_endpoint('sponsor', EP_ALL);
});
add_filter('request', function($args) {
print_r($args);
return $args;
});
I think you should just integrate the function add_rewrite_endpoint.

Resources