Get part of PHP file from URL - php

Is it possible to take a specific part of code from one php file. For a project I have 12 page templates. So in WordPress when I make a new page and want to select a page template, a long list will appear with 12 months.
Here an example of couple months.
Januari, Fabruari, Maart, April etc..
So the question will be, is it possible to place all php code in one page template. And when you go to a specific url it takes a look to the end of the domain and based on that one part of php code..
Example:
www.domain.com/januari
Takes the part from the url /januari
This is Januari
www.domain.com/februari
Takes the part from the url /februari
This is Februari
In future there will be a lot of page templates so it will look really messy. It should be cleaner if there will be one page template "Months" with all content in it. Hope you understand the problem!
Thanks!

You can use the global $_SERVER['REQUEST_URI'] to identify which path was used to get to your PHP script. Then you can print the specific parts based upon if conditions or a switch case:
For the url www.domain.com/januari $_SERVER['REQUEST_URI'] will be /januari, for www.domain.com/februari ir will be /februari, etc...
switch($_SERVER['REQUEST_URI']) {
case '/januari':
//January code here
break;
case '/februari':
//February code her
break;
//...
}
But note, that for the URL www.domain.com/januari?some=get&params $_SERVER['REQUEST_URI'] will be /januari?some=get&params.

You don't need to use any PHP methods for that.
Just use the concept of Page Slug in Wordpress.
here is the code which gives you the slug of current opened page.
<?php
global $post;
$post_slug = $post->post_name;
switch ($post_slug) {
case 'january':
// page for January
get_template_part('template-parts/january');
break;
case 'februari':
// page for februari
get_template_part('template-parts/februari');
break;
... and so on
}
By getting slug into variable '$post_slug' you can apply your conditional statements to compare the value with your paremeters.
OR also you can prefer is_page() method of wp to compare current page with your params.

There are a number of approaches to this problem. My approach will let you keep separate PHP files for each month but only one Page Template will be used.
Let's say page-template-month.php is your template file. And your month specific files have the following structure
theme-root /
- template-parts /
- - january.php
- - february.php
...
Now, the approach to get your specific query term and build logic around it.
Using get_the_ID()
The above function returns the post/page ID and you can build your logic around that ID. Now, your page-template-month.php file will have the following snippet
switch( get_the_ID() ) {
case 5:
// let's assume it's the page for January
get_template_part( 'template-parts/january' );
break;
case 18:
// let's assume it's the page for February
get_template_part( 'template-parts/february' );
break;
}

You can with get the actual link with and cut it
$actualLink = "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$whatYouWant = substr($actualLink, strpos($actualLink, "/")[1]);
But why not use $_GET ?

Related

In Wordpress: How do I get Page Template “page ID” to match “URL ID”

I am new to PHP in general, so I’m not entirely sure what syntax to write.
I want to get the URL from the top browser (which will change when I click Next or Previous) example: (where the number after - # is the ID)
/gallery-1/, /gallery-2/, /gallery-3/,
Based on the Page URL I want to: Get the matching "page content" which is in it’s own directory file and titled (where the number after - # is the ID)
page-gallery/gallery-1.php
page-gallery/gallery-2.php
If the URL [ID#] && Filename[ID#] == the same/Match, I want to
display template name filename[#].With an exception of null for error (Else: Error).
get_template_part( 'page-gallery/gallery', '{MATCHING-ID#}' );
Wordpress has the following features that I know of (but don't know how to apply):
- get page uri (top-level-page/sub-page/current-page) where current-page is what I am trying to get + The ID. So I don't just want the current-page I want the current-page-[#].
- wp_parse_url (string $url) , is another feature that Wordpress has which may be helpful for breaking and splitting the url, but I'm not sure how to tell it to get the /current-page-# and if I'd have to compile an array to manually tell Wordpress of all the gallery-pages the site contains.
-Pagination - could be what I am attempting to do, where instead of breaking the gallery into multiple pages containing it all into a single page and using something like but the pages I have are very long in general and I would have to merge all my separate files back into one.
-Basename - in relation to getting filename directories that I might have to use basename. Not sure how to do this but imagine it would follow the same pattern as URL and getting/splitting the ID that I need.
My current code is:
while ( have_posts() ) : the_post();
//if URL-[ID#] && Template[#] ==
//Then Display Template[#] that == URL [ID#] else, error.
// <-- Not sure how to write this,
//and if I need an array of my template_parts.
get_template_part( 'page-gallery/gallery', '[Same # as URL]' );
endwhile; // End of the loop.
?>
<?php getPrevNext(); ?>
I know this is something simple, but I don't know how to write the syntax for it. Any help would be greatly appreciated.

giving custom argument vlue in 'q' variable

**also posted on druapl.stackexchange
https://drupal.stackexchange.com/questions/150500/giving-custom-argument-vlue-in-q-variable
**
apologies if question is ambiguous . the scenario is as follows:
in drupal 7 , we want to use a custom template page when a specific value is given for the q variable in url .
for example if we give http://localhost/drupal/?q=xyz/123 , we want to use a custom template page say page-xyz.tpl.php ..
have a hunch that hooks and template.php file may be the key components here but not sure what to exactly do..
any help appreciated.
you could implement theme_preproccess_page() (or node, or html) to control this in your template.php
function YOURTHEME_preproccess_page(&$vars) {
if (isset($_GET['q']) && $_GET['q'] == 'xyz/123') {
$vars['theme_hook_suggestions'][] = 'page_xyz';
}
}
that should work, but I would like to recommend not use the '?q=xyz' solution, but do an preproccess that should work to all your pages, like this.
function YOURTHEME_preproccess_page(&$vars) {
$title = strreplace(' ','_', $vars['node']->title);
//if you use the transliteration module, instead of strreplace
//use transliteration_get($vars['node']->title);
$vars['theme_hook_suggestions'][] = 'page_'.$title;
}
now that should work for every page that you want to make a custom template. Just add the file and clear the chaches. If you don't have the page template to the specific page, it's ok, drupal will use the default.

How to make different categories view from one php file

My title might seems unclear. I will describe what I want to do.Let's say the picture shown below is my index.php. If I click 0-100 in 'Select by price', it redirects me to another php file. The difference between this index.php and the '0-100' is just a mysql query that shows different products according to the price in the products box and same for all the others too. Now I realize that it is not a good way to do. And I tried to google my problem but as I am new in PHP i could not find the exact technological name to search in internet. Could you please help me how can I solve my problem or please share the link like my problem.
1. One way would be to use php get variables in the php file, and echo items if price lies between the variable value.
Your url would be something likeindex.php?low=0&high=100.
This gives you two variables, the lower limit on price and the higher limit on price.
While echoing the product you can check for condition,
if($price>=$_GET['low'] && $price<=$_GET['high']){
//then only show the item.
}
2. Another way would be to use javascript or jquery.
Where you can iterate over items and hide them if they do not belong to selected range client side itself. Hence, the page will have to be reloaded if user changes the price ranges.
You should use 'switch', very basic solution:
Click
<?php
if(!isset($_GET['price_from']) && !isset($_GET['price_to']))
{
redirect to index or something
}
switch($_GET['price_from'].'-'.$_GET['price_to'])
{
case '0-100':
echo 'Your content';
break;
case '100-300':
echo 'Your content';
break;
case '300-500':
echo 'Your content';
break;
default:
load index or something
}

How to use a custom post type archive as front page in WordPress?

I'd like to use a custom post type archive as a site's front page, so that
http://the_site.com/
is a custom post type archive displayed according to my archive-{post-type}.php file.
Ideally I would like to alter the query using is_front_page() in my functions.php file. I tried the following, with a page called "Home" as my front page:
add_filter('pre_get_posts', 'my_get_posts');
function my_get_posts($query){
global $wp_the_query;
if(is_front_page()&&$wp_the_query===$query){
$query->set('post_type','album');
$query->set('posts_per_page',-1);
}
return $query;
}
but the front page is returning the content of "Home" and seems to be ignoring the custom query.
What am I doing wrong? Is there a better way, in general, of going about this?
Note: I did post this in WordPress Answers but that community is comparatively tiny.
Posting the final solution as an answer (Isaac placed it as a comment) just for anyone still looking.
Isaac was on the right track with adding a filter via functions.php. What he did wrong was call is_front_page(), which doesn't work yet because we're in pre_get_posts and the query hasn't been executed yet.
We do have the current page ID however. So we can still solve this, by looking into the WordPress option register for an option called page_on_front, which returns the ID of the page the user set as frontpage.
(For an overview of all WordPress options, just visit <yourwordpressinstallation>/wp-admin/options.php in your browser.)
Which makes for the following solution as suggested by Ijaas:
add_action("pre_get_posts", "custom_front_page");
function custom_front_page($wp_query) {
// Compare queried page ID to front page ID.
if(!is_admin() && $wp_query->get("page_id") == get_option("page_on_front")) {
// Set custom parameters (values based on Isaacs question).
$wp_query->set("post_type", "album");
$wp_query->set("posts_per_page", -1);
// WP_Query shouldn't actually fetch the page in our case.
$wp_query->set("page_id", "");
}
}
You might have to alter a few conditional tags to make sure all plugins still work, depending on how heavily the query gets altered.
Hope this helps someone.
Update: as noted below, add !is_admin() to the if-statement to make sure the function only runs on the frontend. If you only want this action to run for the initial query, you could also add the main query check $wp_query->is_main_query().
In response to Robberts solution:
answered May 6 '13 at 12:04
adding && !isAdmin() to the if function other wise it replaces the post type query for all admin pages as well.
Just in case anyone has issues with this.
edit:
also adding && $wp_query->is_main_query() to the if statement stops it affecting widgets and the menu
so total code I have
if($wp_query->get("page_id") == get_option("page_on_front") && !isAdmin() && $wp_query->is_main_query()) {}
In order to get that query to work, you're going to have to add that code to a page template, create a page, set your template as the template for the page you just created, and then set that page as the home page in Settings => Reading in the admin area.
By the way, the is_front_page() function only returns true if you're on a page that's been set as the home page from the admin menu.
The other option would be to modify index.php, but if you did that, is_front_page() would always return false. In that case, you'd want to use is_home() instead.
I hope that helps.
Isaac, you are correct, I didn't thoroughly read your question and I made the assumption that you were looking to do this the "easy" way.
Anyway, I put your code on my test site and, indeed, it didn't work. I looked at my SQL log and it turns out that your code produces this in the query wp_posts.post_status = 'private'.
So, I tried adding the line $query->set('post_status', 'public'); to your function, and it worked just fine.
In summary, try this:
add_filter('pre_get_posts', 'my_get_posts');
function my_get_posts($query){
global $wp_the_query;
if(is_front_page()&&$wp_the_query===$query){
$query->set('post_type','album');
$query->set('posts_per_page',-1);
$query->set('post_status', 'public');
}
return $query;
}

How to include a custom string in a Wordpress permalink?

I am a bit confused about how WordPress's permalink works, especially beyond Wordpress's own usage. My permalinks are like:
%post_id%-%post_name%
But in single.php I want to put another link to page itself but with different query string. When it is clicked the permalink structure may look like:
%mystring%-%post_id%-%post_name%
I want to get the value from $_GET['action'], so:
$_GET['action'] = %mystring%
my plan is to interpret it like:
if('xx' == $_GET['action']){
//do xx stuff
} else if ('yy'==$_GET['action']){
//do yy stuff
} else {
//show the single post as a single.php always shows
}
that means, I want to parse the $_GET['action'] optionally. If I do not parse it even if it is available in query string, I want the page to be rendered correctly.
So to get this done, where should I actually work? Also how do I form the link for <a> tag? Usually we make link this way:
TEXT
but you already know, I need to add some text before the original permalink of post.
Thanks in advance.
Leave your permalink structure as it was and check out my answer on custom rewrite rules.
You could adapt the code like so;
function my_rewrite_rules($rules)
{
global $wp_rewrite;
// the key is a regular expression
// the value maps matches into a query string
$my_rule = array(
'(.+)/(.+)/?$' => 'index.php?pagename=matches[2]&my_action=$matches[1]'
);
return array_merge($my_rule, $rules);
}
add_filter('page_rewrite_rules', 'my_rewrite_rules');
function my_query_vars($vars)
{
// this value should match the rewrite rule query paramter above
// I recommend using something more unique than 'action', as you
// could collide with other plugins or WordPress core
$my_vars = array('my_action');
return array_merge($my_vars, $vars);
}
add_filter('query_vars', 'my_query_vars');
Now the page my_page should be available at http://example.com/whatever/my_page and http://example.com/my_page.
You can get the value of whatever using get_query_var('my_action').
Disclaimer
This may have undesired effects when viewing children pages or page attachments. You could get around this by passing an identifier in your rewrite, something to the effect of;
http://example.com/my_identifier/whatever/page
Note: You will need to edit the rewrite rule if you wish to do this. Every time you make changes to the code you will need to re-save your permalink structure to 'flush' the rules.

Categories