Set custom pages instead of category/archive pages - php

I'm trying to set custom pages instead of the default category/archive pages of Wordpress.
I've copied the following script into the theme function.php, I mention that the site uses The7 Theme.
function loadPageFirst() {
// get the actual category
$actualCategory = get_category( get_query_var('cat') );
// get the page with the same slug
$matchingPage = get_page_by_path( $actualCategory->slug );
// If no match, load the normal listing template and exit (edit if you are using a custom listing template, eg. category.php)
if (!$matchingPage) {
include( get_template_directory() . '/archive.php');
die();
}
// Make a new query with the page's ID and load the page template
query_posts( 'page_id=' . $matchingPage->ID );
include( get_template_directory() . '/page.php');
die();
}
add_filter( 'category_template', 'loadPageFirst' );
I took it from here, it's bencergazda's solution.
Now, after the script, if I create a page, which has the same url as a category page it automatically replaces it.
The problem is that the script is limited to the main (parent) category.
I want to create a child page (let's say example.com/cars/european/german) that automatically replaces the same child category page.
My question is how to modify the script to include category children.

Run a try with this:
function loadPageFirst() {
// get the actual category
$actualCategory = get_category( get_query_var('cat') );
// get the page with the same slug
$matchingPage = get_page_by_path( $actualCategory->slug );
// If no match, load the normal listing template and exit (edit if you are using a custom listing template, eg. category.php)
if (!$matchingPage) {
include( get_template_directory() . '/archive.php');
die();
}
// Make a new query with the page's ID and load the page template
global $post; $post->ID = $matchingPage->ID;
query_posts( 'page_id=' . $matchingPage->ID );
include( get_template_directory() . '/page.php');
die();
}
add_filter( 'category_template', 'loadPageFirst' );

You can easily do this by using templates. Use a child theme and make a template called category-$slug.php and replace $slug for the slug you want to make a page for. You can also just make a category.php. For more options check this template hierarchy.

Related

WordPress Pages - Adding subdirectory to permalink for specific pages

Currently, I have my permalink structure set up such as https://example.com/blog/%postname%/ which makes it so that whenever a blog post is loaded, the URL shows /blog/. I would also like to add the subdirectory /try/ for specific pages. I have tried to use a plugin to add categories to pages so I can create a category and add it that way, but it seems that this is not possible because the "Custom Structure" is already set as noted above.
Does anyone know of a way to add a subdirectory /try/ to specific pages for a WordPress website so the URL for certain pages would be such as https://example.com/try/page-title
Thanks.
First we have to add rewrite_rule
add_rewrite_rule(
'^try/([^/]+)/?',
'index.php?name=$matches[1]',
'top'
);
Then we need to use the post_link filter to change the link format for certain posts
add_filter( 'post_link', 'custom_post_permalink', 10, 4 );
function custom_post_permalink( $link, $post = 0 ) {
$post_cur_id = $post->ID;
$post_cur_slug = $post->post_name;
//array of post_ids with try in permalink
$try_array = array(1,7,22,78);
if(in_array($post_cur_id, $try_array)) {
$slug = '/try/' . $post_cur_slug . '/';
$link = home_url($slug, 'https');
}
return $link;
}
The array $try_array should contain post_id's in which we change the link format

Dynamic meta titles for pages with URL parameters?

I've got a page called /team-page/?id=x that's built in WordPress
The URL parameter of "id" determines the content that will dynamically show on that page. However, my meta title for that page is statically set. Is there a way I can dynamically set the meta title based on the page content? Each variation of /team-page will have a unique H1 - ideally, I'd love to just grab this H1 and set it as the meta title.
You can achieve it with document_title_parts filter. It takes $titles as parameter, which consist of two parts - title and site (except for front page - instead of site it's tagline)
So try this
add_filter( 'document_title_parts', 'custom_title' );
function custom_title( $title ) {
// Just to see what is $title
// echo '<pre>';
// print_r( $title );
// echo '</pre>';
// die();
$uri = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ); // get current uri without query params
// Change meta only on team-page.
if ( '/team-page/' === $uri ) {
// you can do here anything you want
$title['title'] = get_the_title() . ' and whatever string you want ' . $_GET['id'];
}
return $title;
}
Also don't forget to check and sanitize your $_GET['id'] if needed.
You're looking for get_query_var()
Retrieves the value of a query variable in the WP_Query class.
Source # https://developer.wordpress.org/reference/functions/get_query_var/
One small thing to understand is that get_query_var() only retrieves public query variables that are recognized by WP_Query.
So we need to register our variable first. This is considered best practice. Simply using $_GET['id'] is considered to be unsafe within the Wordpress ecosystem.
add_filter( 'query_vars', 'wpso66660959_query_vars' );
function wpso66660959_query_vars( $qvars ) {
$qvars[] = 'ref';
return $qvars;
};
Also you should use something other than id as it is already used by Wordpress to handle the WP_Query. I've used ref (reference) but you can choose whatever as long as it doesn't impact Wordpress core.
then we can simply built our custom title.
<?= '<title>' . get_the_title() . ' | Order N° ' . get_query_var( 'ref', 'undifined' ) . '</title>'; ?>
Note that, if your theme is using Wordpress to set your pages title, you might need to set some sort of conditional statement around add_theme_support( 'title-tag' );, in your function.php.
Something like...
//...
if ( ! is_page( 'team-page' ) )
add_theme_support( 'title-tag' );
The title-tag is usually included in your theme options.

Loading Templates from a plugin in WordPress

I'm trying to make my first plugin and I got stuck. Here is the idea.
When my plugin is activated it will create one post type and two taxonomies for that post type (in my case the post type name is 'Ads').
Also, I created two template pages, one to display the listing of all ads post type articles and the other for a single page for the same post type.
Now my problem is how to tell WordPress to look for the templates from a plugin folder rather than the theme folder when the plugin is active.?
Is it something I can do in the plugin file or I have to create another file for this purpose?
This should do what you are looking for:
First, this hook to tell WordPress which is your single CPT template in your plugin
From this answer you get the single_template hook and how to load it.
Define a constant to replace "plugin_dir_path( FILE )" if you use it elsewhere in your plugin, like this:
define('YOUR_PLUGIN_DIR_PATH', trailingslashit(plugin_dir_path( __FILE__ )) );
https://wordpress.stackexchange.com/questions/17385/custom-post-type-templates-from-plugin-folder
function load_single_ad_template( $template ) {
global $post;
if ( 'ads' === $post->post_type && locate_template( ['single-ads.php'] ) !== $template ) {
/*
* This is an 'ads' post
* AND a 'single ad template' is not found on
* theme or child theme directories, so load it
* from our plugin directory from inside a /templates folder.
*/
return YOUR_PLUGIN_DIR_PATH . 'templates/single-ads.php';
}
return $template;
}
add_filter( 'single_template', 'load_single_ad_template', 10, 1 );
And then for the ads archive template, the 'archive_template' hook, like this:
function load_archive_ads_template( $archive_template ) {
global $post;
if ( is_post_type_archive ( 'ads' ) ) {
$archive_template = YOUR_PLUGIN_DIR_PATH . 'templates/archive-ads.php';
}
return $archive_template;
}
add_filter( 'archive_template', 'load_archive_ads_template', 10, 1 ) ;
Official documentation:
https://developer.wordpress.org/reference/hooks/type_template/
https://codex.wordpress.org/Plugin_API/Filter_Reference/archive_template
This is untested, but should work, however, let me know.

WordPress category based template

I have a task to create a template which is specific to the category. So Lets say I have 10 categories but I want to create a specific template for lets say 3 of them. So if the category is a,b or c I will apply a certain template.
And then when I create a post and attach it to the specific category I need to show that specific template associated to the category.
Any headers?
The Advanced Custom Fields https://www.advancedcustomfields.com/ plugin should allow you to show different templates based off categories. It has some pretty fancy functionality, but can't remember if it can do exactly this.
There is a free version, so give it a try. Let me know how you go ;)
Delete everything in single.php
Insert the ‘switching’ code (see below)
Create 3(three) new templates with unique names. like : single-a,single-b,single-c.
On the server, the magical fairy dust in your modified single.php will automatically load the correct template when the page is requested
Please try below Code for the same.
if (in_category('21')) {include (TEMPLATEPATH . '/single-a.php');
}
else if (in_category('22')) {include (TEMPLATEPATH . '/single-b.php');
}
else if (in_category('23')) {include (TEMPLATEPATH . '/single-c.php');
}
else { include (TEMPLATEPATH . '/single-29.php');
}
There is single-a,single-b,single-c are 3 templates for different categories and your main code in it.
If you refer to Category_Templates
Wordpress will auto retrieve category files in the following format:
category-slug.php or category-ID.php
Let's say you have 3 categories, category a, category b, category c, to assign each of the template differently you can easily create category-a.php, category-b.php, category-c.php and place your desire template within the file and Wordpress will handle the rest.
Here you can use category_template
function wp_category_template( $template ) {
$cat = get_queried_object(); // get category object
if( 1 ) // check condition
$template = locate_template( 'template.php' ); // load template
return $template;
}
add_filter( 'category_template', 'wp_category_template' );
or as #shashi suggested you can use plugin custom-category-template
You have 3 options :
Option 1 : You can create 3 templates and name them according to the WordPress Template Hierarchy like this :
category-1.php
category-2.php
category-3.php
Option 2 : Use PHP code in your functions file to load 1 template for 3 different categories :
add_filter( 'template_include', 'custom_category_template', 99 );
function custom_category_template( $template ) {
if ( is_category(array( 1,2,3 ) ) ) {
$new_template = locate_template( array( 'custom.php' ) );
if ( '' != $new_template ) {
return $new_template;
}
}
return $template;
}
Use the in_category or is_category conditional tag depending on whether you want to load the template for posts in specific categories or only for the category archive page.
Option 3 : You can use the code in option 2 with the category_template filter :
add_filter( 'category_template', 'custom_category_template' );
function custom_category_template( $template ) {
if ( is_category(array( 1,2,3 ) ) ) {
$template = locate_template( 'custom.php' );
}
return $template;
}
Assumes your category i.d's are 1, 2 and 3. Swap out these to match your installations category i.d's

how to disable the comments for specific category in wordpress?

How can i disable the comments form for a specific category in Wordpress.
And i mean with that every post the user will publish it in this category will not has a comment form content.
Rather than doing this in functions.php, you could create two template files. The first template file is your standard theme template, the second would be identical, except it wouldn't contain the comment code section.
Simply name the template file that doesn't have the comment code block category_{id}.php and upload to your theme folder. The ID is the ID of the category you want to disable comments on.
More information on category specific templates here https://developer.wordpress.org/themes/basics/template-hierarchy/#category
More information about the comment template here https://codex.wordpress.org/Function_Reference/comments_template
If you still want to do this via functions.php, see this blog post http://spicemailer.com/wordpress/disable-hide-comments-posts-specific-categories/ which uses the following code snippet
add_action( 'the_post', 'st_check_for_closed' );
function st_check_for_closed()
{
global $post;
$my_post_cat = wp_get_post_categories($post->ID);
$disabled_cat = array( "1", "3"); // this is he array of disabled categories. Feel free to edit this line as per your needs.
$my_result = array_intersect($my_post_cat,$disabled_cat);
if (empty ( $my_result ) )
{
return;
}
else {
add_filter( 'comments_open', 'st_close_comments_on_category', 10, 2 );
add_action('wp_enqueue_scripts', 'st_deregister_reply_js');
}
}
function st_deregister_reply_js()
{
wp_deregister_script( 'comment-reply' );
}
function st_close_comments_on_category ($open, $post_id)
{
$open = false;
}

Categories