Manipulate slugs and urls on wordpress - php

Is there an away to create "virtual" slugs on wordpress?
For example:
I create a custom post type named "year" and the slug is /year/. This custom post type was only created to generate the slugs(/year/). I don't have any post inside this custom post type.
I want to type url /year/1988/ and the Wordpress call the single.php file.
If I do it today the wordpress will return 404 because 1988 needs to be a post inside the custom post type(year).
I need some .php code or .htaccess to do something like: If type something after /year/ its load the single file because I can't create a conditional for each year, 1901, 1902, 1903 ... and I will take this information and make the necessary query.

If you need this to work on your home page only (ie. mysite.org/years/1988) you can add a custom rewrite tag and rule:
add_filter( 'init', function() {
add_rewrite_tag( '%years%', '([^&]+)' );
// Match the front page and pass years value as a query var.
add_rewrite_rule( '^years/([^/]*)/?', 'index.php?years=$matches[1]', 'top' );
});
Then use the new query var to load a different template:
add_filter( 'template_include', function( $template ) {
if ( get_query_var( 'years' ) ) {
$new_template = locate_template( array( 'single.php' ) );
if ( !empty( $new_template ) ) {
return $new_template;
}
}
return $template;
});
I tried to use year, but it wouldn't work, I think it's a reserved query var used by Wordpress. And don't forget to flush your toilet, I mean rewrite rules ;).

Related

Need to change Custom Page name in WordPress from "services" to "products"

Have a wordpress Website in development a theme which has following url for a services
url for custom page type :
localhost/website/service/mechanical-engineering/
localhost/website/service/automotive-parts-systems/
need to change it to :
localhost/website/product/mechanical-engineering/
localhost/website/product/automotive-parts-systems/
I am not able to change it in permalinks, also i am a designer and know little about php
Have tried changing page name and tags in permalinks
also not able to find any plugin which can do this
You can change your post type slug using register_post_type_args filter.
try out these code in your theme functions.php.
function change_post_types_slug( $args, $post_type ) {
/*item post type slug*/
if ( 'service' === $post_type ) {
$args['rewrite']['slug'] = 'product';
}
return $args;
}
add_filter( 'register_post_type_args', 'change_post_types_slug', 10, 2 );
Then save permalink Settings => permalink => save.

WordPress query string to change SEO friendly URL

I want to create SCO friendly URL in the WordPress. Also, I have added a hook in my functions.php file as below code but not working.
My URL:http://bddlabs.com/webinar01/?id=pzlyglhbepotwpvbigdatadim_data&storyid=Story_997e9391-71d7-4fac-804b-de891c7aa595
I want http://bddlabs.com/webinar01/pzlyglhbepotwpvbigdatadim_data/Story_997e9391-71d7-4fac-804b-de891c7aa595
Is it possible? I am not sure about it. URL query string is coming from the third party, URL query string is coming from the third party, page content render based on query string.
Below code added landing-page-15.php it WordPress theme base page template
function fb_change_search_url_rewrite() {
if ( ! empty( $_GET['storyid'] ) ) {
wp_redirect( home_url( "/webinar01/" ) . urlencode( get_query_var( 'storyid' ) ) );
load_template( realpath(__DIR__ . '/..') . '/landing-page-15.php' );
exit();
}
}
add_action( 'template_redirect', 'fb_change_search_url_rewrite' );
//additional rewrite rule + pagination tested
function rewrite_search_slug() {
set_query_var('storyid', $_GET['storyid']);
add_rewrite_rule(
'find(/([^/]+))?(/([^/]+))?(/([^/]+))?/?',
'index.php?id=$matches[2]&storyid=$matches[6]',
'top'
);
}
add_action( 'init', 'rewrite_search_slug' );
You may consider using WordPress builtin permalinks option located in Settings tab.
Set %category%/%postname%/ so that permalink should work as per your requirements.
When posting new content, select a sub category and put post title the same you want to appear in your permalink.
Hope it answers your question.
Wordpress can do this by default. https://codex.wordpress.org/Using_Permalinks

Wordpress - Customise Search Query

I'm running the latest Wordpress with WooCommerce
I'm trying to customise my search results when I use the search bar in the header of my site.
This is how the results appear when doing a normal search:
http://www.sunshinetrading.com/snowmasters/?s=snow
This is how they should appear, when I search through WooCommerce.
http://www.sunshinetrading.com/snowmasters/?s=snow&post_type=product
What I need to do is automatically append &post_type=product onto every search query launched from the header.
My attempts at a solution:
I added this to my child theme's functions.php file, to try and append the query which would fix everything.
// Search WooCommerce
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
echo esc_url( add_query_arg( 'post_type', 'product' ) );
$query->set('post_type', 'product');
}
}
}
add_action('pre_get_posts','search_filter');
However, when I do this, and do a search, what the URL should be appears briefly as text on the page, before the website proceeds to load exactly the same page as before.
What am I doing wrong? Maybe I could solve this problem by editing the .htaccess file. I've added the following ...
# REWRITE SNOWMASTERS SEARCH
RedirectMatch 302 snowmasters.com.au/?s=(.*) http://snowmasters.com.au/?s=$1&post_type=product
This should redirect http://snowmasters.com.au/?s=snow to http://snowmasters.com.au/?s=snow&post_type=product
But it's not working?
I would appreciate your help Stack Overflow community :)
Thanks
Did you try this function already?
add_query_arg( 'post_type', 'product', 'http://www.sunshinetrading.com/' );
You can also register you query string var in wordpress like this:
function add_query_vars_filter( $qVars ){
$qVars[] = "post_type";
return $qVars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
This is from the codex: https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars

How to Create Author archive page for custom post types

My WordPress site uses one default "post" and "books" custom post. I have two different archive page design for different post types (ile. author.php and books-archive.php).
Now, I want to create a custom user profile page with two links, "All Posts by user" and "All books by user". My current user archive page looks like as follows;
xxxxxxx.com/author/nilanchala
Can someone help me how to create two author archive pages filtered by post types? One for "Post" and other for "Books"?
Please do not suggest any plugin.
This is just an example and you should modify it the way you want, we will be using a custom query and rewrite rule to build the url
First thing you need to do is to create rewrite rule for the two custom query you want to display.
example, you have to reset the permalink in order for the new rewrite rule to take effect,
this is better to be created in a class and in a custom plugin so you can simply call flush_rewrite_rules() function
during plugin activation to reset the permalink.
function _custom_rewrite() {
// we are telling wordpress that if somebody access yoursite.com/all-post/user/username
// wordpress will do a request on this query var yoursite.com/index.php?query_type=all_post&uname=username
add_rewrite_rule( "^all-post/user/?(.+)/?$", 'index.php?query_type=all_post&uname=$matches[1]', "top");
}
function _custom_query( $vars ) {
// we will register the two custom query var on wordpress rewrite rule
$vars[] = 'query_type';
$vars[] = 'uname';
return $vars;
}
// Then add those two functions on thier appropriate hook and filter
add_action( 'init', '_custom_rewrite' );
add_filter( 'query_vars', '_custom_query' );
Now that you have build a custom URL you can then load a custom query on that custom url by creating a custom .php file as template and using template_include filter to load the template if the url/request contains query_type=all_post
function _template_loader($template){
// get the custom query var we registered
$query_var = get_query_var('query_type');
// load the custom template if ?query_type=all_post is found on wordpress url/request
if( $query_var == 'all_post' ){
return get_stylesheet_directory_uri() . 'whatever-filename-you-have.php';
}
return $template;
}
add_filter('template_include', '_template_loader');
You should then be able to access yoursite.com/index.php?query_type=all_post&uname=username or yoursite.com/all-post/user/username
and it should display whatever you put on that php file.
Now that you have the custom url and custom php file, you can start creating your custom query inside the php file to query post type based on user_nicename/author_name,
e.g.
<?php
// get the username based from uname value in query var request.
$user = get_query_var('uname');
// Query param
$arg = array(
'post_type' => 'books',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
'author_name' => $user;
);
//build query
$query = new WP_QUery( $arg );
// get query request
$books = $query->get_posts();
// check if there's any results
if ( $books ) {
echo '<pre>', print_r( $books, 1 ), '</pre>';
} else {
'Author Doesn\'t have any books';
}
I'm not sure why you need to build a custom query for all post as the default author profile loads all the default posts.

How to pass extra variables in URL with WordPress

I am having trouble trying to pass an extra variable in the url to my WordPress installation.
For example /news?c=123
For some reason, it works only on the website root www.example.com?c=123 but it does not work if the url contains any more information www.example.com/news?c=123. I have the following code in my functions.php file in the theme directory.
if (isset($_GET['c']))
{
setcookie("cCookie", $_GET['c']);
}
if (isset($_SERVER['HTTP_REFERER']))
{
setcookie("rCookie", $_SERVER['HTTP_REFERER']);
}
Any Ideas?
To make the round trip "The WordPress Way" on the "front-end" (doesn't work in the context of wp-admin), you need to use 3 WordPress functions:
add_query_arg() - to create the URL with your new query variable ('c' in your example)
the query_vars filter - to modify the list of public query variables that WordPress knows about (this only works on the front-end, because the WP Query is not used on the back end - wp-admin - so this will also not be available in admin-ajax)
get_query_var() - to retrieve the value of your custom query variable passed in your URL.
Note: there's no need to even touch the superglobals ($_GET) if you do it this way.
Example
On the page where you need to create the link / set the query variable:
if it's a link back to this page, just adding the query variable
<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c ) )?>">
if it's a link to some other page
<a href="<?php echo esc_url(
add_query_arg( 'c', $my_value_for_c, site_url( '/some_other_page/' ) )
)?>">
In your functions.php, or some plugin file or custom class (front-end only):
function add_custom_query_var( $vars ){
$vars[] = "c";
return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );
On the page / function where you wish to retrieve and work with the query var set in your URL:
$my_c = get_query_var( 'c' );
On the Back End (wp-admin)
On the back end we don't ever run wp(), so the main WP Query does not get run. As a result, there are no query vars and the query_vars hook is not run.
In this case, you'll need to revert to the more standard approach of examining your $_GET superglobal. The best way to do this is probably:
$my_c = filter_input( INPUT_GET, "c", FILTER_SANITIZE_STRING );
though in a pinch you could do the tried and true
$my_c = isset( $_GET['c'] ) ? $_GET['c'] : "";
or some variant thereof.
There are quite few solutions to tackle this issue. First you can go for a plugin if you want:
WordPress Quickie: Custom Query String Plugin
Or code manually, check out this post:
Passing Query String Parameters in WordPress URL
Also check out:
add_query_arg
Since this is a frequently visited post i thought to post my solution in case it helps anyone. In WordPress along with using query vars you can change permalinks too like this
www.example.com?c=123 to www.example.com/c/123
For this you have to add these lines of code in functions.php or your plugin base file.
From shankhan's anwer
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'c'; // c is the name of variable you want to add
return $vars;
}
And additionally this snipped to add custom rewriting rules.
function custom_rewrite_basic()
{
add_rewrite_rule('^c/([0-9]+)/?', '?c=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');
For the case where you need to add rewrite rules for a specifc page you can use that page slug to write a rewrite rule for that specific page. Like in the question OP has asked about
www.example.com/news?c=123 to www.example.com/news/123
We can change it to the desired behaviour by adding a little modification to our previous function.
function custom_rewrite_basic()
{
add_rewrite_rule('^news/([0-9]+)/?', 'news?c=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');
Hoping that it becomes useful for someone.
add following code in function.php
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'var1'; // var1 is the name of variable you want to add
return $vars;
}
then you will b able to use $_GET['var1']
<?php
$edit_post = add_query_arg('c', '123', 'news' );
?>
Go to New page
You can add any page inplace of "news".
One issue you might run into is is_home() returns true when a registered query_var is present in the home URL. For example, if http://example.com displays a static page instead of the blog, http://example.com/?c=123 will return the blog.
See https://core.trac.wordpress.org/ticket/25143 and https://wordpress.org/support/topic/adding-query-var-makes-front-page-missing/ for more info on this.
What you can do (if you're not attempting to affect the query) is use add_rewrite_endpoint(). It should be run during the init action as it affects the rewrite rules. Eg.
add_action( 'init', 'add_custom_setcookie_rewrite_endpoints' );
function add_custom_setcookie_rewrite_endpoints() {
//add ?c=123 endpoint with
//EP_ALL so endpoint is present across all places
//no effect on the query vars
add_rewrite_endpoint( 'c', EP_ALL, $query_vars = false );
}
This should give you access to $_GET['c'] when the url contains more information like www.example.com/news?c=123.
Remember to flush your rewrite rules after adding/modifying this.
to add parameter to post urls (to perma-links), i use this:
add_filter( 'post_type_link', 'append_query_string', 10, 2 );
function append_query_string( $url, $post )
{
return add_query_arg('my_pid',$post->ID, $url);
}
output:
http://yoursite.com/pagename?my_pid=12345678
This was the only way I could get this to work
add_action('init','add_query_args');
function add_query_args()
{
add_query_arg( 'var1', 'val1' );
}
http://codex.wordpress.org/Function_Reference/add_query_arg
In your case, Just add / after url and then put query arguments. like
www.example.com/news/?c=123 or news/?c=123
instead of
www.example.com/news?c=123 or news?c=123

Categories