WordPress plugins - don't print the comments on a post page - wordpress

I'm making a plugin where I want the comments in a single post page not to be printed at all. I need to query the database myself and print my own html with the results.
How can I make WordPress to not print the comments, without disabling them?
Thank you
EDIT:
as a suggestion, I am using:
apply_filters('comments_template', array($this,'comments_template'), 10, 1);
function comments_template($template){
$template = '';
return $template;
}
nothing happens, what am I doing wrong?

You could use the comments_template filter to make WordPress use your plugin's template file rather than the current theme's.
EDIT: based on your edited code: unfortunately you need to have an actual file, the path to which you return in $this->comments_template()...
class MyPlugin{
//add the filter somewhere...
function comments_template($template){
return dirname(__FILE__) . "/my_comments_template.php";
}
}
The file plugin_dir/my_comments_template.php must exist, otherwise WP falls back on the default theme's comments.php. See wp-includes/comment-template.php on lines 911-917.
In plugin_dir/my_comments_template.php you could call `MyPlugin::do_comments() or something like that. I don't know any other way around this. Let me know if you find a better way.
Cheers, Chris

Related

Single Post Template Override for Custom Post Type

I've got kind of a unique scenario that I'm trying to nail down. I'm working on a new template for a custom post type that already exists. Basically, we're replacing the single-customposttype.php file with a new one. All of that is going swimmingly, except one thing - they have one post in that custom post type that they want to keep the OLD template on.
So there's a NEW single-customposttype.php file that will work as the default single template for that CPT.
But I need ID #93 to use the OLD single-customposttype.php template. I hoped just doing single-customposttype-93.php might do the trick, but it doesn't. What's the best way to apply the other template to only one post id?
Thanks in advance!
I deal with custom template loading all the time, it's really pretty simple! Really, all you need to do is hook into the template_include hook, and override the template based on whatever conditions you want.
That hook takes a single argument, the $template file to load. You can then use any conditionals you want and force a separate file to load instead.
add_filter( 'template_include', 'custom_template_include', 99 );
function custom_template_include( $template ){
// For ID 93, load in file by using it's PATH (not URL)
if( get_the_ID() === 93 ){
// Note the file name can be ANYTHING, the WP auto-template names don't matter here
$file = get_stylesheet_directory() . '/post-id-93-custom-template.php';
// It's generally good to see if the file exists before overriding the default
if( file_exists( $file ) )
$template = $file;
}
// ALWAYS return the $template, or *everything* will be blank.
return $template;
}
It's really that simple! Inside the custom PHP file, you have access to all of the WordPress functions and such as you would with a default template.
Generally you'll want to use the file_exists() function on the template, just to make sure it's found, otherwise you'll be passing along a file that doesn't exist, and that page will not load. By checking if it exists, it will still fall back to the old template if it's not found (deleted/renamed/moved, etc)
Also, you always need to have return $template at the end, otherwise anything that uses WordPress' template system will break.
I made a quick example on a demo site:
https://xhynk.com/content-mask/policies/cookie-policy/
https://xhynk.com/content-mask/policies/use-another-template/
The policies are a custom post type, and the cookie policy loads normally. The other one is modified with the same code as above (with the name/ID changed to match), and it's loading in a simple .php file with that content in it.

Wordpress add rewrite rule doesn't work for me

I'm developing a plugin that creates 2 pages: one listing page and one details page.
I don't use custom types. I have created a table into the database where I save the company details and also a slug for the details page.
It's working properly but I have a problem with the URLs. They are not pretty.
On the listing page I use this code to create the link:
<?php echo stripslashes($value->company_name); ?>
The generated link looks like this:
https://www.website.com/company/details/?companyname=new-company-name
I use the query because I need it on the details page, where I use this code:
$company_slug = $_GET['companyname'];
$company_details = $wpdb->get_row("SELECT * FROM $table_company WHERE company_slug = '$company_slug'");
This is how I retrieve the company details from sql and it also works just fine.
I have created manually in Wordpress the details page.
The problem is that I want the details URL to look pretty, like this:
https://www.website.com/company/details/new-company-name/
Generating it like this it's easy but when I click, I get a 404, since the query from URL is missing.
I was thinking it's easy to create directly the pretty URL and on the details page to parse the URL and get the company slug. It didn't work. I get a 404 maybe because the page doesn't physically exist.
So, I've done some research about URL rewrite and I have found some examples but none worked.
I have found tried this code also:
add_filter('query_vars', function($vars) {
$vars[] = "companyname";
return $vars;
});
function custom_rewrite_rule() {
add_rewrite_rule('^companyname/?([^/]*)/?','company/details/?companyname=$matches[1]','top');
}
add_action('init', 'custom_rewrite_rule', 10, 0);
I've read that I shouldn't use matches if I use a custom URL instead of index.php, so I have also tried without matches:
add_rewrite_rule('^companyname/?([^/]*)/?','company/details/?companyname=$1','top');
No results. If course, after every change I have saved again the permalinks.
This should be an easy task but somehow it doesn't work.
https://developer.wordpress.org/reference/functions/add_rewrite_rule/
Does anyone of you know how can I make this work?
Thank you.
Regards,
AG
I am assuming that the details page you created has the slug company/details. Here's what you need to do to make it work-
1. Add the custom rewrite rules in functions.php file:
function theme_custom_rewrites() {
add_rewrite_tag("%companyname%", "([a-z0-9\-_]+)");
add_rewrite_rule('^company/details/([a-z0-9\-_]+)/?$', 'index.php?pagename=company/details&companyname=$matches[1]', 'top');
}
add_action('init', 'theme_custom_rewrites');
It registers a new rewrite tag/query var named companyname to be used later and registers a custom rewrite rule for the specific URL structure you want (/company/details/company_name).
2. Get the company name on the template file and use it: After you have added the above code and saved the permalinks, you can get the companyname just by using the get_query_var() function.
$companyname = get_query_var( 'companyname' );
Hope it helps. Thanks.
Thank you very much for your fast reply. It worked.
Of course, I had to change the link on the listing page to:
<?php echo stripslashes($value->company_name); ?>
I have removed the query from the link and it looks like this now:
https://www.website.com/company/details/new-company-name/
What I don't understand, is how does WP know which is the query, since I removed it from the link.
I can see the same data if I access
https://www.website.com/company/details/?companyname=new-company-name
or
https://www.website.com/company/details/new-company-name/
But, basically, this part (?companyname=) doesn't exist anymore in the link, since I changed it.
I have no query now in my plugin, but somehow everything works properly. :)
I did not declare it somewhere. It's completely gone and it works.
How does this code know that the query exists and it's retrieving the slug from the database?
$companyname = get_query_var( 'companyname' );
I only have this code now:
<?php echo stripslashes($value->company_name); ?>
So, no query in URL.
Thank you for your time.
Regards,
AG

wp_redirect not working in custom plugin

I am trying to create custom plugin in wordpress.
We want to create a case like if user is not logged in to the system then user should be redirected login page. I tried wp_redirect and wp_safe_redirect but it is not working. here is my code.
if (isset($_SESSION['game_login'])) {
//Do Something
}else{
wp_redirect('login');
exit():
}
I am getting this warning
Cannot modify header information - headers already sent by (output started at wp-includes/class.wp-styles.php:225) in wp-includes/pluggable.php on line 1216
can someone suggest me in this scenario?
You shouldn't just start output buffers wherever unless you're specifically delaying the final output, such as modifying content on the template_redirect, using add_shortcode, or any numerous scenarios where you intend to buffer the output.
The code in your example should be encapsulated in a function and hooked to one of WordPress' many Action Hooks. Typically this kind of function is added on the plugins_loaded or init hooks.
add_action( 'init', 'redirect_anonymous_users' );
function redirect_anonymous_users(){
if( isset( $_SESSION['game_login'] ) ){
// Do Something
} else {
wp_redirect('login');
exit();
}
}
There may be several reasons causing this issue.
Try this points and hope this may have a fix
Remove blank space from files that are showing error after php ?> tag at end of file, But in your case
it is from core file, So don't modify anything in terms of code just try to remove blank space at the
ending of those files. Also remove blank space from bottom of files
wp-config.php and functions.php
If the above point does not work add this code to your wp-config.php file
ob_start();
error_reporting(0);

BuddyPress: Modify Name field template in Register form

The registration form in the Buddypress auto generates html for the dynamic fields (such as name). How can I modify the label text (for example replace "(required)" with an * (asterisk).
If you're looking to make that type of change to BuddyPress profile fields, you can use these filters:
add_filter( 'bp_get_the_profile_field_name', function ($field_name){
if($field_name === 'Name') {
return 'Your Name';
}
return $field_name;
});
add_filter( 'bp_get_the_profile_field_required_label', function($string, $id) {
return '*';
});
If you're looking to make changes to those account fields on the left, it looks like you'll need to use a template file copied from BuddyPress into your theme. A bit more intrusive, but will work.
Copy this: buddypress/bp-templates/bp-legacy/buddypress/members/register.php
To here: /your-theme/buddypress/members/register.php
Hope this helps a bit! Customizing BuddyPress & WordPress markup can get stringy real fast, so I'd recommend tracing the code back to a filter or action if you can find one. If not, look for a template file you can bring into your own theme.
If I did not undestand you wrong, It depends if you want to do it in the client (with Javascript for example) or from the server (with the back-end languaje). But the common languajes have a replace() method that takes two arguments, usually strings with the text you want to replace and the one you want to replace it with.
This page explains the replace method:
https://www.w3schools.com/jsref/jsref_replace.asp
Hope it help

Displaying code snippets in WordPress

Ok, not technically a programming question but I want a plugin for my WordPress blog that displays code snippets.
Can anyone here recommend a good one? Also, do you guys know which one Jeff uses on codinghorror. That one looks really good.
Thanks.
wordpress.com claims to use Alex Gorbatchev’s syntaxhighlighter Google Code project.
I guess you might be interested in run-this - there is a wordpress plugin to allow your readers to run your snippets in the browser.
For WP-Snippets, I use Prettify.
You should probably use a plugin for escaping characters to be able to display code without having to do it yourself, or your code wont be displayed. Or just put this in functions.php in your theme folder to do this automatically:
function bbcode( $attr, $content = null ) {
$content = clean_pre($content); // Clean pre-tags
return '<pre"><code>' .
str_replace('<', '<', $content) . // Escape < chars
'</code></pre>';
}
add_shortcode('code', 'bbcode');
And then wrap your code with [code]<?php echo 'hello world!'; ?>[/code]
Source: Code in posts

Resources