If page has posts in certain category - wordpress - php

I have a client built site that I am adding some functionality too - I don't usually develop using Wordpress. They have built pages using Visual Composer to display posts from varying categories
If the post is within a certain category 'Deals' I want to do stuff … non-working code (in functions.php) below:
function deals () {
if ( in_category('Deals') ) {
echo '<style>.entry-thumb{display: none !important;}</style>';
}
}
Calling function from within child theme page template.
Any help would be great
thanks

You can check if current post is in category by using
if( has_category('Deals') ) {
// do stuff here
}
If $post global variable is set has_category('Deals') will be ok. Otherwise you will need to pass post ID as second parameter. https://developer.wordpress.org/reference/functions/has_category/
P.S. If you are calling it in a loop it looks like you are trying to echo the same inline css multiple times. This will hide all .entry-thumbs regardless of the category. So it may be better to add a class to your deal posts and then use something like .deal .entry-thumb{ display: none; } in your style.css.

You should try is_category() function like this:
function deals () {
if ( is_category('Deals') ) {
echo '<style>.entry-thumb{display: none !important;}</style>';
}
}

Related

Unable to dynamically modify content of a page in WordPress

I need to change some opengraph attributes on a specific page based on the query string.
I tried to use some filters based on a installed plugin in the functions.php:
function update_the_og_title($content) {
if(is_page('the-page')) {
// Modify the tags
} else{
// Do nothing
}
}
However, I soon found out the functions.php cannot detect a page using is_page(). What should I do?
How else can I dynamically modify the opengraph tags of a page in WordPress?
Thanks.
You can use is_page but not when functions.php is initially included. What you want to do is to run your code at a specific point in the WP process, using a hook:
function update_the_og_title() {
$id = get_the_id(); //
if(is_page($id)) {
// Get your content here, maybe from metadata?
// Modify the tags
} else{
// Do nothing
}
}
add_action('wp', 'update_the_og_title');
Wordpress action reference
You can get the page ID in a number of ways, including using the $post variable depending on your requirements.

How to hide child pages under specific parent from wordpress search result

I have been looking for a way to tweak my wordpress search results.
This is what I want:
In my site I have posts, pages & and custom post types. Now there are certain pages which in a child page of other page. For example, let's say there is a parent page called Services and there are 5 child pages under it named as ABC Service, XYZ Service and so one.
Now I want to return the following things only, in the wordpress search result:
All Posts
Pages (Not the Services Page and any child pages under it). So all page will show up in the search except the Services page and all the 5 child page which has parent page set up as Services.
Other custom post types
This is what I did:
First I created a small function to check the sub pages:
function ism_is_subpage() {
$post = get_post();
if ( is_page() && $post->post_parent ) {
return $post->post_parent;
} else {
return false;
}
}
after this I have created a wordpress pre_get_posts filter call to pass it though. Like this:
add_filter('pre_get_posts', function( $query ) {
if (!$query->is_admin && $query->is_search) {
$query->set('post_type', array('post', 'page', 'other-post-type1'));
}
return $query;
});
But the problem is no matter how I call the ism_is_subpage(), I am not getting my desired result.
Can any of you please help?
If you know the page id you could do something like this:
add_filter('pre_get_posts', function( $query ) {
if (!$query->is_admin && $query->is_search) {
$query->set('post_type', array('post', 'page', 'other-post-type1')); //this line to specify post types as it is already in your question
$query->set('post_parent__not_in', array($post_id));
$query->set('post__not_in', array($post_id));
}
return $query;
});
Check Post and Page parameters and keep in mind that pre_get_posts hook is called after the query variable object is created, but before the actual query is run.
EDIT
First $query->set(.....) line as it was in your question does post type filtering, you have to add all post types that you want to search and dont forget default post types like 'nav_menu_item', etc. And yes. You have to put post ID (ID of your parent page) for example 44.

How to hide plugins style sheets in wordpress

i want to hide few plugins style sheets to reduce load on our Index page and categories pages. Actually we want to display plugin style sheet only on Post not on other pages.
we have used following code in plugin, but it doesn't work. please help how to use it.
if( is_single() || is_singular('post') ) wp_enqueue_style('savrix-style.css');
If you are modifying your own plugin I see no reason your code wouldn't work. The is_single() condition is not needed, and will result in the stylesheet being loaded on custom post types and other singles that you don't intend.
However your wp_enqueue_style call is incomplete, so unless you have a wp_register_style call somewhere else defining the handle and URL of the stylesheet you need to change it to something along these lines:
if (is_singular('post')) {
wp_enqueue_style('savrix-style', plugins_url('savrix-style.css', __FILE__);
}
However, I get the impression that you are actually trying to remove a stylesheet included by a thirdparty plugin. It is generally a bad idea to modify a third-party plugin, as your modifications will be lost on the next update... it is very difficult to maintain that sort of modifications in the long run.
Instead make a new plugin and modify whatever you need from there.
What you want to achieve can be accomplished by:
Create a new folder in the wp-content/plugins folder, fx. my_load_reducer.
Inside that folder create a new file called my_load_reducer.php
Paste this in the file:
<?php
/*
Plugin Name: My Load Reducer
Description: Removes unneeded and unwanted stylesheets from other plugins
Version: 0.1
*/
//Use a class to avoid conflicts
class my_load_reducer {
function __construct() {
//Hook into wp_enqueue_scripts with a high priority
add_action( 'wp_enqueue_scripts', array($this, 'deregister_styles'), 1000 );
}
function deregister_styles() {
//Check that current post is not a single post
if (!is_singular('post')) {
//deregister the stylesheet - this removes the twentyfifteen
//main stylesheet - obviously you need to substitute the handle
//of the stylesheet you actually want to remove
wp_deregister_style( 'twentyfifteen-style' );
}
}
}
//Instantiate the class
$my_load_reducer = new my_load_reducer();
Activate the plugin through the wordpress admin.
You can remove perticular plugin css on selected page.
below code is remove plugin css to other pages and display only on post pages:
/*disable loading plugin css to page and load on post page*/
add_action('wp_print_styles', 'my_deregister_styles', 99999);
function my_deregister_styles()
{
if(!is_single())
{
wp_dequeue_style('plugin-css-handle');
wp_deregister_style('plugin-css-handle');
}
}
where 'plugin-css-handle' is perticular plugin's css handle which you want to remove.

Wordpress URL Routing, Multiple permalinks with different templates

This question is based on an unanswered question in Wordpress Development which has not gotten a solid answer.
I have a wordpress website which lists hotels. the url for a single hotel looks like:
/hotels/the-marriot-hotel
I also have a custom taxonomy for Locations, which allows me to browse the hotels in various locations, which works fine, the urls are like:
/Locations/Liverpool
For URL's like /hotels/* I would like to use a custom template, which I have done already and works fine.
The Problem
I also want to be able to drilldown the Locations taxonomy creating a breadcrumb type URL and also use a different template for the hotel page.
For Example, if a user is browsing /Locations/Liverpool and clicks the Marriot Hotel I would like it to click through to /Locations/Liverpool/the-marriot-hotel instead of /hotels/the-marriot-hotel and also use a slightly different template, which can also load a different sidebar and recommend other hotels in the area specific to the location slug in the URL
So basically I want two routes to a single post and a different template used based on the route used.
How would I go about implementing this?
What have I tried?
I've tried adding a new page and using a rewrite rule to point to it to be the locations hotel page.
I've tried adding a slug on the end of the /Locations/{location-slug} url and reading this in the page template and loading the hotel post instead of the list it doesn't seem to be working but also feels like a terrible hack anyway
An idea that I've had is to add a rewrite to the hotels/{slug} page and using code to detect the URL used and switch templates dynamically but I'm not sure this is the best approach
I have managed to get this working using the second method mentioned above (adding a rewrite to the locations landing page and checking for a query_var).
I will post the code below that I used but although this works and seems to be working very well, It does not feel like the best way of doing it. If someone know of a better way of doing this please post the answer.
I used this online post for reference.
Note: The listing page shows the list of hotels in the taxonomy in a side column down the side and shows the currently selected or a random one in the main content area. Which will explain how I am using the loop below.
function prefix_locations_rewrite_rule() {
add_rewrite_rule( 'Locations/([^/]+)/([^/]+)', 'index.php?locations=$matches[1]&hotel=$matches[2]', 'top' );
}
function prefix_register_query_var( $vars ) {
$vars[] = 'hotel';
return $vars;
}
function prefix_url_rewrite_templates() {
if ( get_query_var( 'hotel' ) && is_singular( 'hotel' ) ) {
add_filter( 'template_include', function() {
return get_template_directory() . '/taxonomy-locations.php';
});
}
}
add_action( 'template_redirect', 'prefix_url_rewrite_templates' );
add_filter( 'query_vars', 'prefix_register_query_var' );
add_action( 'init', 'prefix_locations_rewrite_rule' );
In my template file for the hotels landing page:
$hotelSlug = get_query_var( 'hotel', false);
if ( have_posts() ) {
while (have_posts()) : the_post();
if ($post->post_name == $hotelSlug) {
break;
}
endwhile;
}
This bit of code will iterate over the posts and if the hotel slug matches the query var it will break there so that the current post is the one we wanted.
We could just use a query here but as I already have a list of posts within the taxonomy I thought I'd just iterate over it. Below this I check to see if a specific hotel has been selected otherwise I show a random one from the list.
I am still to add additional logic and error handling to this code, I hope it helps someone with a similar issue

Can Wordpress functions be modified?

I'm using the wp_list_bookmarks() function in wordpress to get links that have been added in the Wordpress back-end, things like blogroll etc.
My problem is that I need the list to come out in a certain way so that I can put it into columns, with about 5 links in each column.
By default it's just one big list. Is there a way that I can use PHP to alter the way this function posts the links so that I run a counter, and then after 5 links close off the current list and start a new one for the next column?
I basically need something like this:
<ul class="column-1">
<li>link1</li>
<li>link2</li>
<li>link3</li>
<li>link4</li>
<li>link5</li>
</ul>
<ul class="column-2">
<li>link6</li>
<li>link7</li>
<li>link8</li>
<li>link9</li>
<li>link10</li>
</ul>
// etc...
Thank you in advance.
You can use Wordpress's get_bookmarks() function and then tailor the output to your liking. See here for an example:
<?php
$bookmarks = get_bookmarks( array(
'orderby' => 'name',
'order' => 'ASC',
'category_name' => 'Related Sites'
));
// Loop through each bookmark and print formatted output
$column = 1;
$counter = 1;
echo "<ul class='column-$column'>";
foreach ( $bookmarks as $bm ) {
if ($counter >= 5)
{
$column++;
$counter = 1; // reset the counter
echo "</ul><ul class='column-$column'>";
}
printf( '<li><a class="relatedlink" href="%s">%s</a></li>', $bm->link_url, __($bm->link_name) );
$counter++;
}
echo "</ul>";
?>
Reference: http://codex.wordpress.org/Template_Tags/get_bookmarks#Examples
According to wordpress's Plugin API:
Besides the hooks (actions and filters) described above, another way for a plugin to modify WordPress's behavior is to override WordPress functions. In fact, there is a small set of functions WordPress intends for plugins to redefine.
Unfortunately wp_list_bookmarks isn't on their list of functions that are considered "pluggable".
Maybe you can find something else that will fit your needs in the API?
You can hook into wp_list_bookmarks() from a plugin (that you need to write). That plugin can then manipulate the normal HTML that comes from the wp_list_bookmarks() function and return that manipulated HTML back to it, to be echoed or returned as normal.
The idea is to create (and activate!) a simple plugin like:
<?php
/*
Plugin Name: Diggersworld Bookmarks
Plugin URI: https://stackoverflow.com/questions/6089883/can-wordpress-functions-be-modified
Description: Example plugin to customise output from wp_list_bookmarks
Version: 0.0
*/
function diggersworld_list_bookmarks($html)
{
// Do your transformation here
return '<p>Mmm pie.</p>';
}
add_action('wp_list_bookmarks', 'diggersworld_list_bookmarks');
?>
Save this as a file in your plugins folder, and activate it from within the Wordpress admin panel. You will see that where your bookmarks used to be placed, the Mmm pie. text is there instead. Modify that sample plugin to return your desired HTML using whatever method you like.
Since this is tying into a hook inside the wp_list_bookmarks() function, your templates should call wp_list_bookmarks() as normal.
Of course, the body of the plugin function could use code similar to that in thesocialgeek's answer.

Categories