INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Why doesn't this function work when I know that the IP Address is "true"?
I am trying to append "DEV SRV:" to the page title (i.e. title tag) if the IP Address matches that of the dev server. I have tried this both in the functions.php file of my child theme and as a standalone plugin
add_filter('wp_title', 'dev_srv_title');
function dev_srv_title($title) {
$host = $_SERVER['SERVER_ADDR'];
if ($host =='0.0.0.0') {
return 'DEV SRV: '.$title;
}
return $title;
} | The issue was not persistent between multiple installations because there were multiple themes in use. The themes were creating the title tag in different ways.
Changed plugin based solution to inserting conditional banner content (and later a contextual feedback form) in wp_footer which is working regardless of theme (so far ) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, child theme, server, wp title"
} |
Random users always showing same 8 users
I am trying to display some random users on the page. It is changing the order of the users it is showing, but it is only showing the same users instead of randomizing from all users in the database.
So, it is currently showing 8 users, but always the same users, just in a different order. I have 100 users and it shouldn't always just show the same 8.
<?php $args = array(
'role__in' => array( 'member' ),
'exclude' => array( 37, 1 ),
'orderby' => 'rand'
);
$wp_user_query = new WP_User_Query($args);
$members = $wp_user_query->get_results();
?> | Actually, `rand` is not a valid argument for `orderby` in the WP_User_Query class (it is in the WP-Query class). So, it should default to `user_login`, giving you an alphabetical list. Also, you should get all users that fit the `member` and `exclude` criteria from this query, not just eight.
This suggests there is other code interfering with yours.
My suggestion would be to start with adding `'number' => 100` to `$args`. That should overrule any other code limiting the amount of results. You could then use `shuffle` to randomize the array returned or pick some random elements from the array with `array_rand`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, users, wp user query"
} |
Wordpress REST API V2: how to get list of all posts?
I need to get a list of all posts in a certain category. The number of posts is more than 100. I do not need the post's content. I need only id and slug.
` returns only 10 posts with content.
Is it possible to get all posts without content? | Out of the box and using the core available hooks and API, **you can't have more than 100 items per response on WordPress REST API** for performance reasons. For the second part of the question, _you may remove some fields from the response_ by using `_fields` parameter in your request as you can see in the examples of the handbook:
// option a: using comma separated fields names.
// option b: using array syntax.
And theoretically if you own the website, you could remove fields from the API response by using the `rest_prepare_{$this->post_type}` dynamic filter for the post(s) type(s) you want to change.
if(!function_exists('wpse_382314_post_filter_data')) :
function wpse_382314_post_filter_data($response, $post) {
$response->data['post_title'] = '';
$response->data['post_content'] = '';
}
}
add_filter('rest_prepare_post', 'wpse_382314_post_filter_data', 10, 3); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "rest api"
} |
If two first numbers exist in wp_meta_query value
I want to display a Custom post Type "Companies" filtered by zipcode.
In my CPT I have an ACF field called 'companies_zip_code', their values looks like this :
29200
29860
35000
22350
...
**I want to display only companies where their companies_zip_code begins with`29`**
So I write this WP_QUery :
$args = array(
'post_type' => 'companies',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'company_address_zip_code',
'value' => 29,
'compare' => 'LIKE',
)
)
);
$custom_query = new WP_Query($args);
With that I want to display only companies with zipcodes like this : `29200,29500,29860 etc..` But it does not work
Thanks for your help ! | You could try to use the REGEX compare option for the meta_query, like so:
'meta_query' => array(
array(
'key' => 'company_address_zip_code',
'value' => '^29@',
'compare' => 'REGEXP',
)
) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp query, advanced custom fields, meta query"
} |
Giving a new page an existing URL
Say I want to build a new page which will eventually replace an existing page. Rather then editing the existing page, I want to take my time and get it right, but when the new page is ready, I want it to have the URL of the original page.
How do I do that please? Presumably if I edit the just permalink to be the same as the exiting page, there will be two pages with the same permalink, which will cause problems? | The process to do this isn't probably as complex as you think.
1. Leave the existing page exactly as-is. Don't change its slug etc.
2. Create a new page draft
3. Create the new page content as you'd like it to have.
4. Once the new page is complete, and ready to go, go back to the original page and change its slug to _anything else_. (see below gif #1)
5. Go to the new page, and set its slug to the **original page slug** (that you changed in step #4)
6. Publish the new page.
.
If you want to keep the old page, decide on the slug you'd like to have and update it as necessary. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "permalinks"
} |
Restricting product quantity field to numbers only in Gravity Forms
How can i restrict the product quantity field to numbers only in Gravity Forms.
And how can we add some increment arrow to the quantity field?
like on this demo ? < | Thanks to David from Gravity Wiz.
He gave me the hint that i just need to enabled HTML5 on the Gravity Forms global settings page.
Can't believe i missed that setting. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin gravity forms"
} |
How is called this thumbnail slider feature
I am new to wordpress, and I am trying to create new website. I found really nice-looking theme, but when I installed and activated it, it looks very simple compared to the preview page. Is it due to that I have to pay to make my website look 100% similar as preview?
Anyway, how is this feature called, that you can see in the picture? There are 3 thumbnails, that are sliding after some time, and they are clickable. Could anyone share the name, and how can I implement it myself?
 change to page slug
i'm really new to wordpress php. which function should i use to replace is_account_page() in a code. here's what I'm trying to achieve before
if (is_account_page()){
do some code here
}
after
if (user on this page slug){
do some code here
}
what is the appropriate function I should use for the **user on this page slug** part | You could try to use the is_page() function - <
The function signature accepts one parameter - $page
> (int|string|int[]|string[]) (Optional) Page ID, title, slug, or array of such to check against.
Default value: ''
if ( is_page('account') ){
// do some code here
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, pages, page template, slug"
} |
Load user by specific role
I need to load only the subscribers
$args = array('role' => 'Subscriber');
$subscribers = get_users($args);
but with this, it returns also the users that are subscriber AND other role (I need to delete my subscribers only, but keep subscribers with other role)
How do I get this users ? | One possible way is by using the `role__not_in` parameter like so which excludes all other roles except `subscriber`:
// Include only the following role(s):
$roles_in = array( 'subscriber' );
$roles_not_in = array_diff(
array_keys( wp_roles()->get_names() ),
$roles_in
);
$args = array(
'role__not_in' => $roles_not_in,
);
$subscribers = get_users( $args );
But of course, if you know the exact roles that should be excluded, then just do `'role__not_in' => array( 'role', 'role2', 'etc' )`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, user roles"
} |
How to export posts and keep html tags in the title
If my post title is : `Hello <b>world</b>`
When exporting the posts with built-in Tools/Export, html tags are removed. I don't want that.
I have 9K posts to export with valuable styling in all titles, so even if it is not the best practice, these tags need to be kept.
In what file is the xml generated ?
Or is there some kind of hook for this ?
Thank you. | In the file `wp-admin/includes/export.php`
Within the post loop, line 545, simply replace
$title = apply_filters( 'the_title_rss', $post->post_title );
with
$title = $post->post_title; | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "export"
} |
How Can I save multiple records in same meta key?
I want to save multiple dates in meta key.
I have a three dates 2,3,4 and I want to save all these values in same meta key but as a different values.
For example:
dates(meta key) 2(meta value)
dates(meta key) 3(meta value)
dates(meta key) 4(meta value) | This should work out of the box, as long as the "unique" parameter of `add_post_meta()` is `false`.
add_post_meta($id, '_dates', 2, false);
add_post_meta($id, '_dates', 3, false);
add_post_meta($id, '_dates', 4, false);
then somewhere else
$dates = get_post_meta($id, '_dates', false);
Now `$dates` should be an array of your 3 values. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "custom post types, custom field, post meta, meta query"
} |
Help! ERROR: Cookies are blocked due to unexpected output on attempting to login to resolve an issue with my site
First-timer over here!
**Domain for the buggered website (you'll see what I mean!)** <
**URL I am using to try to login to WordPress backend to fix the issue** <
So, when I enter my username, password and then proceed to login, I get the following error message **" ERROR: Cookies are blocked due to unexpected output"**
;
… in your `wp-config.php`. You should _never_ set that to `true` on a live site.
So how to fix it? Two steps:
1. Access your site per FTP or SSH, and edit the `wp-config.php`, so `WP_DEBUG` is set to `false`.
2. Then log in, and update WordPress. Newer versions won't have this problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "login, errors"
} |
Will changing the 'Plugin Name' header in the next update of a plugin break anything?
I have a small plugin on wordpress.org with a few thousand downloads.
It has a typo in the Plugin Header, "Plugin Name". I want to fix this in the next update. Will changing the "Plugin Name" in the plugin header have any negative effects on the plugin? | I found out the answer: Changing the 'Plugin Name' does not effects the plugin. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugin development"
} |
Trying to load a responsive CSS media query using Custom Taxonmy
@media (max-width: 768px) {
.page-id-9334 .site-content {
display: flex;
flex-direction: column-reverse;
}
}
I am trying to load this CSS into Custom Taxonomy Pages...
My original question refers to a specific Page ID (and I edited my original question).
Anyways - based upon the replies below I thought that this would work but it throws an error, with or without the `<style>` CSS Opening Tags.
Can anyone else please shed some light on how I might be able to get this to work?
Thanks!
add_action( 'wp_head', function () {
if ( is_tax(country) ) {
<style>
@media (max-width: 768px) {
.site-content {
display: flex;
flex-direction: column-reverse;
}
}
</style>
}
} ); | Seems there are a few elements missing
First is the quotes in `is_tax(country)`, should be is_tax('country')
Second you are missing closing and opening PHP tags
When working with action that require html output you can do it in a few ways. For now we will stick with the method you wanted to use.
The final result would look like this
add_action( 'wp_head', function () {
if ( is_tax('country') ) {
?>
<style>
@media (max-width: 768px) {
.site-content {
display: flex;
flex-direction: column-reverse;
}
}
</style>
<?php
}
} ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, responsive"
} |
Meta Query relation “AND” not working
I want show (featured product) that instock, but this query just show in stock products.
$query = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 12,
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_stock_status',
'value' => 'instock',
),
array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
),
),
); | You mixed meta query and tax query
It should look like this
$query = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 12,
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => '_stock_status',
'value' => 'instock'
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured'
)
)
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp query, tax query"
} |
Rss error in first line of xml : not well-formed (invalid token)
I'm having a problem with my **rss feed**.
Validator.w3.org is not accepting it, saying **_not well-formed (invalid token)_ on line 1**.
It seems that the name of the website appearing between `<?xml ?>` and `<rss>` might be causing the problem.
Column 54 is the end of the site name.
, to determine which of the 50 are free, or which of the 50 are premium plugins? | Usually premium plugins that came with the purchase of a theme are updated via an external updater, not the wordpress built-in one. That could be one of the clues.
One obvious clue would be that the plugin has some kind of login/licence key system.
But when it comes to taking a look in the code, I'm afraid it's not an option cause the paid features can be implemented differently on every plugin. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins"
} |
find custom post type post by searching its custom field with my string
I have a custom post type called `series` and each post has a custom field named `originaltitle`. So in my code before I create a new post, I need to check if there is already a "series" with same `originaltitle` custom field value.
If it exists, then return that post ID. If not, then I can move on with my code.
Any help is appreciated. | You can find the post using `get_posts()` and the meta query (in my example, I used `meta_key` and `meta_value`) like so:
See the function reference for more details on the parameters (and other examples that might help you), but the `'fields' => 'ids'` means that the function will return only the post IDs and not full post object/data.
<?php
// Find a "series" post with the meta originaltitle set to a specific value.
$ids = get_posts( array(
'post_type' => 'series',
'post_status' => 'publish',
'posts_per_page' => 1,
'meta_key' => 'originaltitle',
'meta_value' => 'put value here',
'fields' => 'ids',
) );
$post_id = array_shift( $ids );
// Or you can do something like:
/*
if ( ! empty( $ids ) ) {
$post_id = $ids[0];
// run your code
}
*/ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, wp query, search, query posts, meta query"
} |
Keep salts when moving a site?
Should I keep the salts when moving a site to another server or should I create new ones and how do the passwords remain readable then? | You should change them.
Its good practice to periodically change your wordpress salts.
It will not affect the passwords in the database but it will log out all users. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "php"
} |
How I can change the required capability for an admin menu without editing the plugin file?
I need to change the capability required for an added admin menu page. By default the plugin added the capability manage_options which I need to change. How can I change this without editing the plugin file? | The functioning of the code below depends a lot on how the plugin in question was built.
add_action( 'admin_menu', 'change_capability' );
function change_capability() {
remove_menu_page(
$menu_slug,
);
add_menu_page(
$page_title,
$menu_title,
$new_capability,
$menu_slug,
);
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, user roles"
} |
Can't Export Custom Post Types With Export Tool In A Custom Theme
I have a custom theme and when I try to export the posts for the custom post type called 'news' via `Dashboard > Tools > 'News' > Download Export File` (image attached) I get a 403 'Forbidden' message on my localhost set up. On the live site I get a 404 error.
Does anybody know how to correct this issue?
Thanks in advance for an assistance.
 [NC]
RewriteRule .* - [F]
# END block author scans | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, 404 error, export"
} |
Redirect a WordPress Multisite url after it has been change to a new one
In the multisite dashboard network admin, you can edit a site and change its url.
For example, I have this url: multisite.com/old and I have change it to multisite.com/new
How can I make the multisite.com/old redirect to multisite.com/new so that users will not get lost and will not return an error? Current error is "Page not found / File not found".
I have tried adding this to my htaccess with no success
RewriteRule ^old/(.*)$ /new/$1 [R=301,NC,L]
And also this one
Redirect 301 /old/ | Solved:
I just had to remove the dash on the redirect code since I'm typing multisite.com/old without the last dash
Redirect 301 /old/
Redirect 301 /old | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, redirect"
} |
Change the default blog post post attribute template name from "default template" to something else
I have found this filter which allows me to change the default name but this changes it for pages and posts. I just want to change it for posts. Is this possible?
add_filter('default_page_template_title', function() {
return __('new default name for posts only', 'your_text_domain');
}); | Yes, and one way is by accessing the global `$post` variable and then check if it's for a post of the `post` type (or any custom post types). E.g.
add_filter( 'default_page_template_title', function ( $label ) {
global $post;
if ( 'post' === get_post_type( $post ) ) {
return __( 'new default name for posts only', 'your_text_domain' );
}
return $label;
} );
Or the other way is by checking if the current screen's ID is `edit-post` (or `edit-<post type>`), and you'd just need to change the above `if` condition to:
if ( 'edit-post' === get_current_screen()->id ) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, filters, page attributes"
} |
After wp_insert_post() custom post type does not show in the admin
I have an import script that uses wp_insert_post() to add events wordpress. The script works and is basically a foreach loop of array elements that calls the above function multiple times.
My issue is that in the admin for the event custom post type I see this:  {
function rlrsssl_options() {
return array();
}
add_filter('pre_option_rlrsssl_options', 'rlrsssl_options');
} | If you have code that _must_ run before plugins are loaded, place it in a Must Use Plugin. This is just a PHP file placed in `wp-content/mu-plugins/`. Be aware that Must Use Plugins are activated just by existing. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, filters, hooks"
} |
woocommerce: Customize email with item total count
i looking everywhere, but not found this functions, i need to calculate the total items in the report email new order,i think is (admin-new-order.php) so i need to see `the numbers total products` in the under row on subtotal or elsewhere
->cart->get_cart_contents_count(); ?>
OR
<?php echo(count(WC()->cart->get_cart())); ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, theme development, woocommerce offtopic"
} |
What is the right way to add PHP code to a certain part of a page
I know I can add PHP to the functions file. And I know I can make a plugin.
I basically need to make a calculator of sorts and send the values to an email signup.
What is the best way to achieve this. I think a plugin, but then how would I position the plugin at a place on an already existing page?
Sorry if this is a noob question, I really want to understand the correct way to achieve this before starting. | A plugin is just a file that gets loaded into WordPress, it doesn't have a _location_ on the page. In fact WordPress doesn't know which page it is yet when plugins are loaded. It may not even be a frontend page!
So if a plugin is just a place to put code such as hooks and filters, how do you embed code in a page?
There are several methods:
* blocks
* shortcodes
* widgets
* theme template files
You can register blocks/shortcodes/widgets in a plugin, whereas templates files are theme specific.
I recommend searching the site for how to create and use a shortcode, this will be the easiest option for you at the moment. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
Hide a div if the fiels is empty
I have a problem to hide a div when the input of a custom field is empty. This is the code I am using, it's fine when the field is not empty. But when the fireld empty, the div will show.
The field that displays the content is postintro2, the div I want to hide when empty is
<div class="single2-intro">
The complete codes is:
<?php { $postintro2 = get_post_meta ($post->ID, 'postintro2', $single = true);
if($postintro2 !== '')
echo '<div class="single2-intro">'.$postintro2.'</div>';
} ?>
Thanks for any helps. | Try:
$postintro2 = get_post_meta ($post->ID, 'postintro2', true);
if ( ! empty( $postintro2 ) ) {
echo '<div class="single2-intro">'.$postintro2.'</div>';
}
From the codex: get_post_meta | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, custom field"
} |
Add custom path to url to specific pages
Right now all pages path like `/faq/` or `/about/`. I need path like `/home/faq/` `/home/about`. I tried change url slug in edit page. But Wordpress change my `home/faq` to `home-faq`.
I installed plugin `Create And Assign Categories For Pages` And add custom categories, but paths don't changed.
How can I do this task? | If you want to change the permalink structure for all Pages (i.e. posts of the `page` type), you can use the `WP_Rewrite::$page_structure` property like so:
add_action( 'init', 'wpse_382911' );
function wpse_382911() {
global $wp_rewrite;
$wp_rewrite->page_structure = 'home/%pagename%';
}
Don't forget to flush the rewrite rules — just visit the permalink settings admin page (`wp-admin` → Settings → Permalinks).
But if you just want that structure for specific pages, then how about just using the parent-child feature whereby you'd create the `home` page and make the `faq` and `about` pages as children of the `home` page? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, url rewriting, paths"
} |
How to create a post using REST API with sending data as a JSON body?
I am able to create posts on my WordPress website using it's REST API with the below curl request format. Website uses basic auth plugin for the authentication process.
`curl --user "username:password" -X POST -i
However, my problem is I need to set custom fields of the post when creating a post using REST API. I tried to send data as a JSON body using the below command and it didn't work. It just returns all the posts without creating a new post and also without giving any error.
`curl --user "username:password" -X POST -i -d '{"title":"NEw tiitle"}'`
I have tried sending post creation requests to my website using the Postman service also and the same thing happened. Could anyone please help me to solve this problem? Thanks in advance! | That's strange, but nonetheless, you should know that whether you use cURL, PHP, JS, etc., if you're sending a JSON data, then you should set the `Content-Type` _header_ to `application/json`.
And via the cURL command line, you can use the `-H` option:
curl --user "username:password" -X POST \
-H "Content-Type: application/json" \
-i \
-d '{"title": "foo bar", "content": "test"}'
Also, if you're using Windows, you may need to use the **double quotes** instead of single quotes with the `-d` option. So the above would be: ( note I used the caret (`^`) symbol and not backslash )
curl --user "username:password" -X POST ^
-H "Content-Type: application/json" ^
-i ^
-d "{\"title\": \"Windows test\", \"content\": \"test\"}" | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "posts, rest api, json, curl"
} |
Use object in template part
I try to use a template part in my loop.
<?php
foreach ($categories as $category) {
get_template_part( 'temp-parts/loop/blcnr_loop');
}
?>
In the template part I call the object
<?php
echo $category->name;
?>
But this gives me an error " **Trying to get property 'name' of non-object** ". Is there a solution for this?
I tried this
foreach ($categories as $category) {
$categoryData = array(
'name' => 'theName'
);
get_template_part( 'temp-parts/loop/blcnr_loop', NULL, $categoryData);
}
And this in the template part
echo $categoryData['name'];`
But this returns NULL | As of WordPress 5.5 you can pass variables to template parts by passing them in an array to the third argument of `get_template_part()`:
foreach ($categories as $category) {
get_template_part( 'temp-parts/loop/blcnr_loop', null, [ 'category' => $category ] );
}
These variables will populate an `$args` variable accessible from the the template:
echo $args['category']->name; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, loop, oop"
} |
Apply function.php filter only if url not has /amp/
I applied a filter to remove theme styles and javascript in function.php, but I want this to happen only if the url not ends with /amp/ | What is `amp`? Is it tag or category or page? You should use standard wordpress functions like `is_page()` `is_category()` `is_tag()`.
You can also use `$wp->request`. It will return the request URI. If the address is `" it will return `slug1/slug2` then use `explode()` function to split it.
<?php $uri = $wp->request;
$slugs = explode("/",$uri);//variable $slugs will have array of slugs
//$slugs[count($slugs)-1] will return last slug
if($slugs[count($slugs)-1] != "amp") {
//Apply your filter filter here
}
?>
Remember $wp is a global variable so if you want to use it inside a function the must use the keyword `global` before it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, filters, paths"
} |
WP site after login keeps redirecting to looped url
My site Example.com keeps on redirecting to following url < | for most of the issues like this its a plugin conflict. in my case too it was a plugin. disabling one by one and troubleshooting will solve similar problems | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp admin, urls, wp redirect"
} |
How to get database connection details without longing to cpanel in WordPress?
I am creating a WordPress plugin and in my plugin i need to do some SQL statements ,in the site i am working on i have access to WP-admin but i cant get to the files to get database name and password from WP-config that i need in
mysqli_connect("host", "user_name", "password","database_name");
i believe there is a way to do that in PHP like all plugins in WordPress but i couldn't find out how ! | both answers were great and helped me a lot ,i used the following to get to wp-config file without really Knowing all database details
require_once('../wp-config.php');
include_once ('../wp-load.php');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD , DB_NAME); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, mysql, sql, wp config"
} |
var_dump and print_r cause white screen
My template is very simple:
get_header();
$new_p = get_posts(array('post_type' => 'post', 'numberposts' => 6));
get_footer();
whenever I put `var_dump($new_p);` or `print_r($new_p);` below `$new_p = get_posts(array('post_type' => 'post', 'numberposts' => 6));`, it gives me the white screen.
Why on Earth would it do it??
This code is OK, though:
var_dump(wp_get_recent_posts(array('post_type' => 'tdlrm_store_item', 'numberposts' => 8), OBJECT));
Any ideas? | Actually, memory was exhausted. Someone has copy-pasted an actual 2MB base64-encoded image into the post content, var_dump was trying to output it. Had to delete the image via PHPMyAdmin, because the WP editor won't open. Once it had been deleted, the problem was gone. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "get posts"
} |
Why my query 'REPLACE INTO...' does not work?
To insert or update data if data exists, I was using 'REPLACE INTO...' in a var `$query_string` like this :
dbDelta( $query_string );
For some reason, the row is not insert. Why ? | The reason is due to this code inside `dbDelta()` :
// Create a tablename index for an array ($cqueries) of queries.
foreach ( $queries as $qry ) {
if ( preg_match( '|CREATE TABLE ([^ ]*)|', $qry, $matches ) ) {
$cqueries[ trim( $matches[1], '`' ) ] = $qry;
$for_update[ $matches[1] ] = 'Created table ' . $matches[1];
} elseif ( preg_match( '|CREATE DATABASE ([^ ]*)|', $qry, $matches ) ) {
array_unshift( $cqueries, $qry );
} elseif ( preg_match( '|INSERT INTO ([^ ]*)|', $qry, $matches ) ) {
$iqueries[] = $qry;
} elseif ( preg_match( '|UPDATE ([^ ]*)|', $qry, $matches ) ) {
$iqueries[] = $qry;
} else {
// Unrecognized query type.
}
}
ths function `dbDelta()` does not support 'REPLACE INTO' and that calls in the `else` with `// Unrecognized query type.` comment. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "query, dbdelta"
} |
how to hide empty fields of post category description?
I am creating one website from scratch, where I have to display Category description, how to hide the div, if there is no description written in backend for the post category?
my codes are:
<div class="row">
<div class="col-sm-8 mx-auto py-5">
<?php echo nl2br($qo->description) ?>
</div>
</div>
I want to hide the entire row, if there is no description written in backend for the post category.
Thanks. | Wrap the div with a if condition like this. It should do the job!
<?php if($qo->description):?>
<div class="row">
<div class="col-sm-8 mx-auto py-5">
<?php echo nl2br($qo->description) ?>
</div>
</div>
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, categories, theme development, description"
} |
How can I show only 5 posts from the relationship?
**HI** I use plugin: Advanced Custom Fields
How can I show only 5 posts from the relationship?
This is the code:
<?php $c_lists = get_field( 'c_lists' ); ?>
<?php if ( $c_lists ) : ?>
<?php foreach ( $c_lists as $post_ids ) : ?>
<a href="<?php echo get_permalink( $post_ids ); ?>"><?php echo get_the_title( $post_ids ); ?></a>
<?php endforeach; ?>
<?php endif; ?>
Any help, please | You could use the key from the foreach
<?php
$c_lists = get_field('c_lists');
if ($c_lists) :
foreach ($c_lists as $key => $post_ids) :
if ($key > 4) break;
?>
<a href="<?= get_permalink($post_ids); ?>"><?= get_the_title($post_ids); ?></a>
<?php
endforeach;
endif;
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "query posts"
} |
Can WP plugins access files outside the installation folder?
If I have multiple WP installations in let's say /var/www. Can a plugin be developed to access files outside its own directory?
I want to host multiple installations for different customers in the same chroot. But those customers will have admin access to their instance. Can they theoretically develop a WP plugin to access the files (or even WP config, including DB credentials) of another WP installation?
For example, can the WP located at /var/www/wordpress-customer-1 access files located at /var/www/wordpress-customer-2 ?
Thanks! | > Can they theoretically develop a WP plugin to access the files (or even WP config, including DB credentials) of another WP installation?
Yes.
If your folders are owned by the same user, run as the same user in Apache/Nginx or have read/write access to each other, then it's possible.
Your installations are sandboxed at the server/host level, not the WP level.If your users have the ability to upload plugins or edit PHP, then they can easily upload a version of the `emergency.php` targeted at the other installs and reset the admin password. Likewise they could insert a PHP shell, or read the `wp-config.php` of the other install.
It's also much worse, if one of those sites gets hacked, all of them could be infected. You also have a more difficult time with backups
If you are concerned for security, you should fix this immediately. How you would fix that is server specific and not in the scope of this site. Consider asking on ServerFault | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "php, filesystem"
} |
Filter Post Title without affecting screen-reader-text
Let's consider this code:
add_filter('the_title', static function ($title) {
return $title. '-boom';
});
Works fine, and adds '-boom' near all the titles.
But, I also noticed that in some themes (Twenty Twenty, Twenty One and most likely many others) if a post contains the `<!--more-->` tag, this also affect the "continue reading" button, see image attached
.
So, to achieve this, we need to hook the `excerpt_more` and use a lower priority of the one used by the theme.
In my example, this
add_filter('the_title', static function ($title) {
return $title. '-boom';
});
adds `-boom` string in both text and excpert, and this
add_filter('excerpt_more', function ($more_link_element) {
$more_link_element = str_replace('-boom', '', $more_link_element);
return $more_link_element;
},9999,1);
removes it from the excpert | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, title, excerpt, read more"
} |
Copying My account/Login/Register button outside header
My client is looking for a way to have a Sign up/Login button outside the header menu area. For instance this website - < . The "sign up with email" forwards to a login form which is the same as woocommerce login form. If i do this with a simple button - even after registration or login, the button will show the original text (ex. "login/register"), but the My account/Login/Register will show the user login name (ex. "customer name1"). All in all i want to copy the exact button in the main body of my website. I know this is simple for you, but i am really struggling here. Thank you in advance! | You can try `wp_loginout()` function which will display Login or Logout text (based on whether the user is logged in or not) in an anchor tag. And, then you can apply CSS styling to make the anchor tag to appear like a button. Hope this logic helps you.
See here for reference. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp login form"
} |
How to call WooCommerce update cart function programatically
I am rendering WooCommerce Cart items in a custom html table wrapper by a form that points to a custom PHP file.
<form class="woocommerce-cart-form" action="/update-cart.php" method="POST">
...
<input type="submit" name="update_cart" value="Update cart">
</form>
When I click on update cart, I get redirected via POST to `update-cart.php` where I do some business related actions with the PHP `$_REQUEST`.
After doing those actions, I want to call to the WooCommerce original update action, but I am stucked.
This is what I have tried:
// Non of this has worked for me
do_action('woocommerce_update_cart_action_cart_updated'); // 1
WC()->cart->persistent_cart_update(); // 2
do_action('update_cart_action'); // 3
How should I call WooCommerce's update action?
Thank you. | The default form handler is a static method which you can call with
WC_Form_Handler::update_cart_action(); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, woocommerce offtopic"
} |
Application passwords not working on localhost?
I have to get following error on the `localhost`
"code":"application_passwords_disabled"
` returns a `false`, and the docs says:
> By default, Application Passwords is available to all sites using SSL or to local environments. Use ‘wp_is_application_passwords_available’ to adjust its availability.
So, to enable the Application Passwords:
* Enable SSL on your `localhost`,
* Or define `WP_ENVIRONMENT_TYPE` either as a global system variable or constant, and set its value to `local`:
// Example when defining it as a constant.
define( 'WP_ENVIRONMENT_TYPE', 'local' );
* Or use the `wp_is_application_passwords_available` hook like so:
add_filter( 'wp_is_application_passwords_available', '__return_true' ); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 1,
"tags": "errors, rest api"
} |
WP CLI Get all Enqueued Scripts and Styles
Normally, I would hook into the `wp_enqueue_scripts` action in order to gather a list of enqueue'd scripts and styles.
However, I have a very intensive process I need to run, thus instead of running it through the site itself, I am hooking into WP CLI.
How can I gather the scripts and styles without having the action `wp_enqueue_scripts` available to me in CLI? Or is there a CLI action that I am just not finding in the documentation for the WP CLI API? | You can't, and it doesn't make sense to do so.
Different pages/URLs enqueue different things, e.g. a WP Admin page won't enqueue the same styles and scripts, widgets might enqueue things conditionally, etc.
But in WP CLI those hooks don't run, and there is no page or frontend. So the question doesn't make sense at a fundamental level. It isn't enough to know the URL either, **you need to render the page to know which scripts and styles are enqueued**. There is no way to know in advance.
Could you render the page in WP CLI? _Unlikely_ , a CLI environment will be missing a lot of the environment that a browser request has. For example, there is no URL, no GET/POST, no current user, cookies, etc.
The closest you can get to this, is a `curl` request. Just know that the security policy you generate will be specific to that page, and will be missing other scripts and styles, e.g. things only enqueued for admins/logged in users/other pages/etc. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "hooks, actions, wp enqueue script, wp enqueue style, wp cli"
} |
Check If Post Was Published More Than 6 Months Ago Using get_the_date
Inside my `content-single` template, I have a conditional check that displays text based on how old the post is. The idea is to inform visitors that they might be reading "old" news.
Problem is; the `6+ months old` text is displayed on posts that are only days old, and I do not understand why.
**This is the code I am using:**
<?php
if ( strtotime( get_the_date() ) < strtotime( '-1 year' ) ) { ?>
<span class="old-post"> 6+ months old </span> /
<?php
}
?>
This is the format I am using in WP admin for date and time:
l \t\h\e jS \of F @ H:i
Please help me understand how to fix this. | The problem is that your date format is not a standard format that `strtotime()` understands. Instead just use `get_the_date()` with the format set to `'U'`, which returns the timestamp, and compare that to `strtotime( '-1 year' )`:
if ( get_the_date( 'U' ) < strtotime( '-1 year' ) ) {
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, single, date time"
} |
Listing all users by their avatars in wordpress
I want to list pictures of all avatars how do I do this | You can jump start by using following example. Here I'll be listing users and loop through them to display avatar and display name.
<?php
$blogusers = get_users();
// Array of WP_User objects.
foreach ( $blogusers as $user ) {
/* Here passing user email and avater size */
echo get_avatar( $user->user_email , 96 );
echo '<span>' . esc_html( $user->display_name ) . '</span>';
}
Read more about
1. get_users()
2. get_avatar() | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "avatar, gravatar"
} |
Getting an error. Need to add favicon in my child theme functions.php. What's wrong?
When I put this code in my functions.php
add_action('wp_head', 'my_favicon');
function my_favicon() {
echo "<link rel='shortcut icon' href=' " . get_stylesheet_directory_uri() .
'/images/favicon.ico'"'>";
}
I get
> [Message from webpage]: There has been a critical error on this website. Learn more about debugging in WordPress.
What's wrong with my code? | add_action('wp_head', 'my_favicon');
function my_favicon() {
echo "<link rel='shortcut icon' href='" . get_stylesheet_directory_uri() .
"/images/favicon.ico'>";
}
I think the problem was incorrect quotation marks on the string. Can you try this code. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "child theme, favicon"
} |
Return multiples taxonomies with wp_get_object_terms
I have a loop to display the posts of my Custom Post Type 'workshop'. Inside the loop I display the related terms of two taxonomies 'area' and 'group' using `wp_get_object_terms()`.
It works fine. However I'm struggling to control the order of the taxonomies when displayed. It should always be in first 'area' then 'group'.
The code to display the related taxonomies:
<?php $workshop_terms = wp_get_object_terms( $post->ID, array( 'area', 'group' ) );
if ( ! empty( $workshop_terms ) ) {
if ( ! is_wp_error( $workshop_terms ) ) {
foreach( $workshop_terms as $term ) {
echo esc_html( $term->name );
}
}
} ?>
Thank you. | `wp_get_object_terms()` accepts a third parameter which is an array of arguments") passed to `WP_Term_Query::get_terms` which runs the actual SQL queries for the specific term request, and one of the arguments is named `orderby` which accepts term fields like `name` and `taxonomy`.
So you can use that 3rd parameter and set the `orderby` to `taxonomy` (and `order` to `ASC`) like so:
$workshop_terms = wp_get_object_terms( $post->ID, array( 'area', 'group' ), array(
'orderby' => 'taxonomy',
'order' => 'ASC',
) );
Or the other way, is of course, call `wp_get_object_terms()` once for each of the taxonomies... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy, terms"
} |
Counting posts and trigger it
I am trying to figure out how i can install a code for the counting posts. I already have a code for the posts on the website. But i want to trigger it for example if there are no posts, the text should change to no posts found or if there is just one post the text should then be: we found 1 post.
Here is the code i made in the function.php
function wpb_total_posts() {
$total = wp_count_posts()->publish;
echo 'We found', "<strong>" . $total . "</strong>", 'jobs';
}
and this one i made in the loop
<div>
<h4 class="total-posts">
<?php wpb_total_posts(); ?>
</h4>
</div> | Modify your `wpb_total_posts` function like bellow:
function wpb_total_posts() {
$total = wp_count_posts()->publish;
if($total == 1){
echo 'We found', "<strong>" . $total . "</strong>", 'job';
}elseif($total > 1){
echo 'We found', "<strong>" . $total . "</strong>", 'jobs';
}else{
echo 'No posts found ';
}
}
Here I'm first checking if total amount of post is 1 or more and handling singular/plural accordingly. Lastly if there is no post then rendering "No post found" | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions"
} |
How would you add sequentially numbered labels to images in posts?
I'd like to add sequentially numbered labels to images in posts. Just a small number in the corner of each image to help when referencing them in my writing.
All of the images are wp-block-image (no galleries). The numbering should be simple +1 addition **based on the order of appearance** in the images for that post (top left = #1, next img = #2...)
The order isn't expected to change after the post is published - it's static content - but in draft stage the images are moved and will be out of order from their upload/inserted/filename/ID.
A few gallery plugins appeared in search that claim to have this feature, but I don't think they'll work with wp-block-images and my existing content. And I'd rather not use a plugin if it can be handled cleaner without it.
How would you add these labels correctly and efficiently? | No need for plugins or any change to the markup - you can do all of this in pure CSS with what is called counters, which do have broad browser support.
body {
counter-reset: imageLabel;
}
.wp-block-image::before {
counter-increment: imageLabel;
content: "#" counter(imageLabel);
}
This will already produce the number after the image, you can style the `::before` however you like and position it where it needs to be.
Beware that this might hurt the accessibility of the page, I'm unsure how well screen readers can interact with both `::before` and the CSS `content`. However, solving this will probably require you to create either a new block or edit the image block . | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, themes, css"
} |
Log out without confirmation request (nonce)
I have a Wordpress site with WooCommerce. I would like to add a Logout option to the Menu that logs out the user _without asking for confirmation_.
So I included a menu custom link with as URL: `/my-account/customer-logout/?_wpnonce=3d7c353c19&redirect_to=http%3A%2F%2Fwww.example.com`. However, the nonce changes every time, so it will still ask for confirmation to log out...
This post shares something about how to get rid of the confirmation request with php. But I'm not familiar with php. How should I use this in the URL field of the custom link? That is, how can I populate the custom url with the dynamic nonce? | I ended up solving it using the plugin Code Snippets and the following code snippet based on <
function change_menu($items){
foreach($items as $item){
if( $item->title == "Log Out"){
$item->url = wp_logout_url('/');
}
}
return $items;
}
add_filter('wp_nav_menu_objects', 'change_menu'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, login, nonce, logout"
} |
Redirect a page id url but not the page slug
My client is asking me to force a 404 `$wp_query->set_404();` if the URL is `example.com/page_id=342` but DON't redirect if the URL is `example.com/about` even though they are the same page. I have to do this in the `functions.php` file and not `.htaccess`.
I have tried:
add_action('init','add_get_val');
function add_get_val() {
if (isset($_GET['page_id'])) {
$param = $_GET['page_id'];
if($param == '342') {
global $wp_query;
$wp_query->set_404();
// status_header( 404 );
// get_template_part( 404 );
// exit();
}
}
}
The code as it stands does not work. But if I uncomment the `status_header()`, `get_template()`, and `exit()` it does. However, it does not give the same 404 page.
What am I doing wrong? | Try using the `pre_handle_404` hook instead:
add_filter( 'pre_handle_404', 'wpse_383506', 10, 2 );
function wpse_383506( $preempt, $wp_query ) {
if ( ! empty( $_GET['page_id'] ) &&
'342' === $_GET['page_id']
) {
// Throw a 404 error.
$wp_query->set_404();
// And prevent redirect to the page permalink (pretty URL).
remove_action( 'template_redirect', 'redirect_canonical' );
}
return $preempt; // always return it
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "redirect, 404 error"
} |
WordPress Admin bar missing from custom theme
I'm working on a WP site which has a custom theme built from scratch and I can't seem to figure out how to get the Admin Bar to appear when viewing the public site.
The themes footer.php file has the wp footer code in it: `<?php wp_footer(); ?>` just before the closing `</body>` tag. I've tried disabling all plugins and reverting back to default theme. The Admin bar appears when using the Twenty Twenty One theme so the issue is with this custom built theme for sure. Disabling plugins had no effect.
The theme is using ACF.
I have enabled admin bar from my WordPress profile settings.
WP_DEBUG doesn't throw any errors or notices.
How could I troubleshoot this further? | add_filter( 'show_admin_bar', '__return_true');
Add this at the end of functions.php | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, admin bar"
} |
How to remove click ads from fresh WordPress site?
I bought a hosting and domain from Godaddy, Installed WordPress. Now the site is showing ads on every page after clicking anywhere on the pages or in the admin section as well. I have tried manual WordPress install also, changed the cPanel password, FTP password. Removed all files before fresh install. It starts showing ads immediately after install. Please suggest a solution. | WordPress doesn't include ads of any kind, so there's no standard process for removing them.
Possible reasons you could be seeing ads are:
* Your host is adding them, possibly as a condition of a cheap/free hosting plan.
* You installed a pirated theme or plugin that contains malicious code.
* Your website has been hacked in some other way. This seems unlikely if you saw them right after installing.
* _You_ have been hacked, and you have malware on your computer that's displaying ads on web pages.
* Your ISP is injecting them.
This site is not an appropriate place for resolving any of those issues, so my suggestion would be to start by speaking to your host. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "virus"
} |
How to make custom total price reactive in navigation
I created navigation for my custom template and added total price inside the `<li></li>` elements and it show the price if I add product to the cart, but if I add another product to cart price not change automatically. If I want the price updated, I need to refresh the whole page.
Can someone help me to make this price updating automatically if I add products to cart? I'm very bad about ajax etc... but I want this to working like it should work.
<ul class="nav-link-right">
<li class="nav-link-price">
<?php if ( class_exists( 'Woocommerce' ) ) : ?>
<?php
// Get order total
$cart_total = WC()->cart->get_cart_subtotal();
?>
<span id="order-total-price"><?php echo $cart_total; ?></span>
</li>
</ul> | Using woocommerce `woocommerce_add_to_cart_fragments` filter you can do that.
Going by the `id` attribute that you currently have for the span that displays the cart total, you can use the following code
add_filter('woocommerce_add_to_cart_fragments', 'bt_update_cart_total');
function bt_update_cart_total ($fragments) {
$fragments['#order-total-price'] = '<span id="order-total-price">' . WC()->cart->get_cart_subtotal() . '</span>';
return $fragments;
}
Add this code to your functions.php file and thats it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, woocommerce offtopic, ajax, javascript"
} |
Removing extra large generated images disables all crops
function filter_image_sizes( $sizes) {
unset( $sizes['1536x1536']); // disable 2x medium-large size
unset( $sizes['2048x2048']); // disable 2x large size
return $sizes;
}
add_filter('intermediate_image_sizes_advanced', 'filter_image_sizes');
I check the uploads folder and only the original image is being added now. I check the docs and I don't think I see it removing all the crops because of it.
Am I doing something wrong? When removing those sizes, do I need to add back the default sizes? | add_filter( 'intermediate_image_sizes_advanced', function ( $sizes ) {
$allowed = [ 'thumbnail', 'medium', 'large', 'medium_large' ];
foreach ( $sizes as $name => $size ) {
if ( ! in_array( $name, $allowed ) ) {
unset( $sizes[ $name ] );
}
}
return $sizes;
} );
I ended up setting an array with the crops I would allow and then unset anything that wasn't there. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads, post thumbnails, media library, cropping"
} |
Using wp_editor tinyMCE in metabox cause form alert on leaving page
Using tinyMCE as wp_editor in a custom post type metabox create an alert when I try to submit or If I want to change location
 document is created and the WP. The site admin upload this file to the sites T&C directory.
When the admin uploads this pdf is there any event emitted that an external application could have a webhook listening to pick up the addition/upload of the new file. | Use the action `add_attachment`, and look at the MIME type, then do whatever you need:
add_action( 'add_attachment', function( $post_id ) {
if ( 'application/pdf' !== get_post_mime_type( $post_id ) ) {
return;
}
// Here you can update a static file, send a HTTP
// request to the other site or send an email.
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp api"
} |
don't call ajax if not plugin page
I created a plugin that uses ajax the problem is that the plugin requests are loaded on the whole site and not only on the plugin page I need to call the function only on the plugin page
plugin main code
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
define("Importer",plugin_basename(__FILE__));
define("PLUGIN_DIR",__DIR__);
require_once PLUGIN_DIR."/vendor/autoload.php";
if(is_admin()){
$moviewp = new \App\Bootstrap();
}
debug error every time I do something on the site using ajax
call_user_func_array() expects parameter 1 to be a valid callback, class 'App\Bootstrap' does not have a method 'process_moviewp_like' in C:\xampp\htdocs\clean\wp-includes\class-wp-hook.php on line 287
how do i exclude site ajax requests and separate them from the plugin? | You can check for WordPress's `DOING_AJAX` constant:
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
return;
}
...or use the related `wp_doing_ajax()` function:
if ( wp_doing_ajax() ) {
return;
}
However, I'd also double-check to make sure that `App\Bootstrap` has a method named `process_moviewp_like` as well, because that error doesn't look like something that would be limited to AJAX. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, ajax"
} |
WP_Debug not displaying anything
In `wp-config.php` I have included:
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
As I understand, this should display certain information on every page, also if there are no errors. However, nothing has changed. In addition, no file `public_html/debug.log` has been generated...
Any idea how to get into debug mode? | The constant to output errors to screen is actually
define( 'WP_DEBUG_DISPLAY', true );
`WP_DEBUG_LOG` would generate a debug.log in your _wp-content_ directory, not in your site root. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp config, debug"
} |
how can i remove js file from my footer in wordpress
i want to remove a specific js file from specific template. i have seen sone solutions and try them but got no result. following i am writing the code which i tried.
add_action('wp_enqueue_scripts','theme_slug_dequeue_footer_jquery');
function theme_slug_dequeue_footer_jquery() {
if ( is_page_template('property_list_half.php') ) {
wp_dequeue_script('directory-js');
wp_deregister_script('directory-js');
}
}
 {
if ( is_page_template('property_list_half.php') ) {
wp_dequeue_style( 'directory' );
}
}
add_action('wp_enqueue_scripts','theme_slug_dequeue_footer_jquery'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, jquery, wp enqueue script"
} |
How to hook code in <body>?
In the question How to add code to Header.php in a child theme?, a recommended solution is to create a plugin, then hook into `wp_head` action by using this code:
add_action('wp_head', 'wpse_43672_wp_head');
function wpse_43672_wp_head(){
//Close PHP tags
?>
ADD YOUR PLAIN HTML CODE HERE
<?php //Open PHP tags
}
Looking at header.php, I see that `<?php wp_head(); ?>` belongs to `<head>`, not `<body>`. So which function to use if I want to hook into the body? I don't see any `<?php wp_body(); ?>` in header.php, though I find there is `<?php wp_footer(); ?>` right before `</body>` in footer.php.
My goal is to add these code, in order to use the Off Canvas Sidebars plugin:
<body>
<?php do_action('website_before'); ?>
<!-- WEBSITE CONTENT -->
<?php do_action('website_after'); ?>
<?php wp_footer(); ?>
</body> | The action you are looking for is `wp_body_open()`. I do not know if you are writing your own theme or not but if you are using a pre-built theme, the author of your theme may not have included this support.
If properly supported in your theme, any function hooked to this action will be called immediately after the page opening `<body>` element.
WordPress reference: <
Additional theme reference: < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "hooks"
} |
Override a page template from a plugin in a child theme
I have a plugin which creates a custom post type "projects". In the plugin folder is a template file (single-project.php) where i would like to make some changes. But i'm wondering how i can override this file from the child theme i'm working on. I've tried to make a copy and place it in my child theme folder, but wordpress doesn't pick that one up. How can i achieve this without editing the file in the plugin folder (and risk lose my changes when the plugin is updated?) | Use the filter `template_include` to override a template path. Example:
add_filter( 'template_include', function( $template ) {
if ( ! is_singular() ) {
return $template;
}
if ( 'project' !== get_post_type() ) {
return $template;
}
// Now we can safefely
return get_stylesheet_directory() . '/single-project.php';
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types"
} |
Too few arguments to function WP_Widget::__construct(),
first time with custom widget. I'm trying to create it this way:
<?php
namespace App;
class My_Widget extends \WP_Widget {
function My_Widget() {
$widget_ops = [
'name' => 'My widget',
'description' => 'My description'
];
parent::__construct( 'My_Widget', 'My widget', $widget_ops );
}
}
function load_widget() {
register_widget( 'App\\my_widget' );
}
add_action( 'widgets_init', __NAMESPACE__ . '\\load_widget' );
And I get this error:
Too few arguments to function WP_Widget::__construct(), 0 passed in /srv/www/contraindicaciones.net/current/web/wp/wp-includes/class-wp-widget-factory.php on line 61 and at least 2 expected
What am I doing wrong? Thanks! | You're using an extremely outdated method of creating a widget. You should be using the `__construct()` function, not a named function, as the constructor, as documented.
namespace App;
class My_Widget extends \WP_Widget {
function __construct() {
$widget_ops = [
'name' => 'My widget',
'description' => 'My description'
];
parent::__construct( 'My_Widget', 'My widget', $widget_ops );
}
}
function load_widget() {
register_widget( 'App\\my_widget' );
}
add_action( 'widgets_init', __NAMESPACE__ . '\\load_widget' ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "widgets"
} |
Do WordPress' cron's clean up expired transients?
WordPress has a cron named "`delete_expired_transients`" as seen in the image below.
;
function my_custom_fn()
{
delete_expired_transients();
}
See also: delete_expired_transients() | Yes, `delete_expired_transients` is a cron event that runs once per day and the function `delete_expired_transients()` is automatically called when the cron event runs — see _wp-includes/default-filters.php_. So you do not need to call the function manually like you did in your `my_custom_fn()` function.
And if you use a plugin like WP Crontrol, you can easily view the cron events in your site and the actions (functions) that will be called when a specific cron event runs. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 7,
"tags": "functions, actions, wp cron, transient"
} |
How Can I fix Woocommerce Billing Address Field?
I am trying to fix the Woocommerce billing address field in my Wordpress website. This field is inside the "my account" tab. It looks weird and I do not know how can I fix it?
{
do_action('initialized');
});
function initialized(){
// ...
}
**Second question**
Will a vicious circle occur like the following?
function initialized(){
do_action('init');
} | Yes, you can nest actions.
Yes, your example will cause an infinite loop. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, functions, actions"
} |
Notification when visitor is on specific WordPress Article
I am desperately attempting to find a way to get an alert when a specific article on my WordPress is visited (and no, I will not be flooded by emails, the code will be used temporarely) Being new to php, I used this code, but the site gets a critical error if I put it into the functions.php?
function email_alert() {
wp_mail( '[email protected]', 'Alert', 'This Site was Visited!' );
}
if(is_article(1234)){
}
add_action( 'wp', 'email_alert' );
please help/advice, a big thank you! | here we go, this is the code that works, triggering an email-alert when a specific article is viewed
function email_alert() {
global $post;
if( $post->ID == 1234) {
wp_mail( '[email protected]', 'Alert', 'This Site was Visited!' );
}
}
add_action( 'wp', 'email_alert' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts"
} |
SSL and www to non-www redirection works only on homepage - Wordpress
I've enabled SSL on my Wordpress website and set redirection from www to non-WWW via the following code placed in .htaccess:
# REDIRECT WWW TO NON-WWW
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule (.*) [L,R=301]
# REDIRECT HTTP TO HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ [L,R=301]
However, it works good only on homepage (example.com). What I am doing wrong? | You've put the directives in the wrong place, the canoncial redirects need to go _before_ the `# BEGIN WordPress` section (the front-controller), otherwise, they are not going to be processed for anything other than physical files and directories. (The "homepage" maps to a physical directory, so _is_ redirected).
For some reason you have also repeated the WordPress front-controller section, with a slight difference. You should only have one.
>
> # BEGIN block author scans
> RewriteEngine On
> RewriteBase /
> RewriteCond %{QUERY_STRING} (author=\d+) [NC]
> RewriteRule .* - [F]
> # END block author scans
>
This section is also in the wrong place and needs to go _before_ the `# BEGIN WordPress` section. You should remove the `RewriteEngine` and `RewriteBase` directives from this block. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "redirect, htaccess, ssl"
} |
Why is my array of nav menus returning empty?
I am trying to retrieve of list of available menus but the array is returning empty.
function get_menus() {
$menu_list = [];
$wcs_menus = wp_get_nav_menus();
foreach($wcs_menus as $m) {
$menus_list[$m->slug] = $m->name;
}
return $menu_list;
}
$menus = get_menus();
var_dump($menus); | Are you missing a "s" in your variable `return $menu_list;`?
Your array is called `$menus_list;` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus"
} |
wp_schedule_event custom event time
Ok, let's say I want to give the user the ability to schedule a wp cron event every X minutes. Now, let's say I want X to be anywhere from 10 to 525600 (minutes in a year).
What I'm seeing is an utterly stupid way to handle cron events through the $schedules array. If I understand correctly, I have to add a custom schedule to the array for every single different event time the end user wants. For example:
add_filter( 'cron_schedules', function ( $schedules ) {
$schedules['twelve_minutes'] = array(
'interval' => 12,
'display' => __( 'Twelve Minutes' )
);
return $schedules;
} );
Please tell me there's some way to schedule an event with a custom time without having to add 525,590 unique intervals to the $schedules array. | I use the following code to run a task. this doesn't require adding a cron schedule.
function setup_my_action() {
if (!wp_next_scheduled('my_action')) {
wp_schedule_single_event(time()+3600, 'my_action');
}
}
function my_action() {
// do something
}
add_action('init','setup_my_action');
add_action('my_action', 'my_action'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development"
} |
How to check if which hook triggered the call to a function?
I have a situation where I have a function hooked to more than one custom hooks. How to check in the callback function which custom hook triggered the call?
Or the question in code will be
add_action('my_test_hook_1','my_test_callback_function');
add_action('my_test_hook_2','my_test_callback_function');
add_action('my_test_hook_3','my_test_callback_function');
add_action('my_test_hook_4','my_test_callback_function');
function my_test_callback_function(){
$called_action_hook = ; //Some magic code that will return current called action the hook
echo "This function is called by action: " . $called_action_hook ;
} | I found the magic code you need.
Use `current_filter()`. This function will return name of the current filter or action.
add_action('my_test_hook_1','my_test_callback_function');
add_action('my_test_hook_2','my_test_callback_function');
add_action('my_test_hook_3','my_test_callback_function');
add_action('my_test_hook_4','my_test_callback_function');
function my_test_callback_function(){
$called_action_hook = current_filter(); // ***The magic code that will return the last called action
echo "This function is called by action: " . $called_action_hook ;
}
For reference: < | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 4,
"tags": "hooks, actions, callbacks"
} |
I need help with storefront theme shop page
I know I might be asking for a huge request and I would appreciate it if anyone can help me with my storefront theme on woocommerce.
I am planning to have a shop page similar to <
my current page is < (it's a mess)
so what I actually want is to be able to access the HTML file and add a few divs and grids for the product title and price.
 and then with the search tool from VS Code look for any specific class, or ID of the specific page that you want to edit | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic, themes"
} |
Best way to trigger rewrite rules
I typically call the rewrite rules with this action
add_action('init', 'add_my_rewrite_rules')
But what I do not like about it is that the rewrite rules are written every time an `init` action is triggered, which means pretty much every time a page is refreshed.
Is this the correct action to call the rewrite rules? Is there a better way of handling that? (i.e, no need to add the rules every time we trigger `init`)
Thanks. | `init` is the recommended hook and no, the rewrite rules will not be overwritten each time the hook fires or that the page is loaded, _unless_ if you call `flush_rewrite_rules()` or `WP_Rewrite::flush_rules()` in your callback.
add_action( 'init', 'add_my_rewrite_rules' );
function add_my_rewrite_rules() {
add_rewrite_rule( ... );
flush_rewrite_rules(); // don't do this
}
So please don't do that, or do it only upon plugin/theme activation and deactivation — and if you don't already know, you can easily flush the rules by simply going to the Permalink settings admin page, without having to hit the Save Changes button. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "url rewriting, rewrite rules"
} |
Enable automatic minor core updates when root of site is a git repository
I have a client site that's under version control using Git. The single repository is at the Wordpress root level, but it is set to ignore everything except for theme and plugin files. I did some research into best practices and found some content on submodules, which I might try next time, but at the moment, I'm wondering if there's a way to achieve both of the following:
1. Keep the Git repository structured as is at the WordPress root but effectively only use it to version control theme and plugins in a single repository.
2. Enable automatic WordPress core updates and get around this error: `This site appears to be under version control. Automatic updates are disabled.`
;
From < | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 5,
"tags": "automatic updates, git"
} |
Access files at new location using old file paths
I have a bunch of posts that contain images with urls that follow this pattern:
`
I've imported the posts into a new install of wordpress on the same domain with file structure where the files now reside at
`
Because "example_directory" is now a category slug, I cannot simply update the new directory structure to mirror the old one.
How can I make the files inside `new_directory` appear when my browser tries to visit urls at `directory/files`? | I believe I've found the solution. I add the following
RewriteRule ^example_directory/files/(.*) new_directory/$1
to my WordPress .htaccess rules like so:
RewriteEngine On
RewriteBase /
RewriteRule ^example_directory/files/(.*) new_directory/$1
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
I couldn't get it working before and I think the key was moving the new `RewriteRule` directive to the line directly following `RewriteBase /` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "url rewriting, htaccess, slug, migration, directory"
} |
Multiple meta_key in one global $wpdb;
I have this code which works great:
global $wpdb;
$ticker_tag = $wpdb->get_col( "SELECT meta_value, COUNT(*) AS c
FROM $wpdb->postmeta
WHERE meta_key = 'ticker'
GROUP BY meta_value
ORDER BY c DESC" );
Is there any way to add two meta_key values?
I have tried:
WHERE meta_key = 'ticker', 'ticker2'
also tried this:
WHERE meta_key = 'ticker' AND 'ticker2'
but none of them works. | Use `WHERE meta_key = 'ticker' OR meta_key = 'ticker2'` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, functions, mysql"
} |
404 Not Found on CSS file even though it's in the correct directory
This is in the template file:
function add_pt_style() {
wp_enqueue_style ('pt-style', ROOT_PATH.'/pt.css', array(), '1.0.0');
}
add_action( 'wp_enqueue_scripts', 'add_pt_style' );
get_header();
Here are my files:
 {
$plugin_url = plugin_dir_url( __FILE__ );
wp_enqueue_style ('pt-style', $plugin_url . 'css/pt.css', '1.0.0');
}
add_action ('wp_enqueue_scripts', 'pt_load_plugin_css'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp enqueue style"
} |
Author post count in category
I want to count authors post count in a specific category. How do i do that? I have red this thread here but still can't fiure it out.
Count number of posts by author in a category
Edit: This is what i got and tried but doesnt work at all.
$user_id = get_the_author_meta('ID')
$args = array(
'author_name' => $user_id,
'category_name' => 'categoryname',
};
$wp_query = new WP_Query($args);
while ( $wp_query->have_posts() ) : $wp_query->the_post();
echo $my_count = $wp_query->post_count;
wp_reset_postdata();
endwhile; | Here is the correct code. It shows authors post count from a specific category by category slug name.
$user_id = get_the_author_meta('ID');
$args = array(
'author' => $user_id,
'category_name' => 'category_slug_name',
);
$my_query = new WP_Query( $args );
$my_count = $my_query->post_count;
echo $my_count; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, categories, author, count"
} |
How can we redirect user from login page to home page if user is logged in WordPress?
I have just installed WordPress locally in my computer and run the website successfully. I want to achieve following: when logged-in user tries to access wp-login.php or register page, it should be automatically redirected to home page.
I have spent several hours on web, but could no come up with solution neither was I able to find appropriate WordPress plugin.
My question is: why does WordPress function this way? how can we change this behavior as natively as simply as possible?
Thank you | You can check the current page being loaded through the $pagenow global variable. Both login and registration is handled through wp-login.php. Adding this to the functions.php of your theme should work:
<?php
add_action('init', function () {
if ($GLOBALS['pagenow'] === 'wp-login.php' && is_user_logged_in() && (!isset($_GET['action']) || $_GET['action'] !== 'logout')) {
wp_redirect(home_url());
exit;
}
});
**EDIT:** Added a check to allow logging out and clarified where to put this code. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "login"
} |
How to query a nested field in wordpress api using _fields param
I'm trying to access certain fields which are deeply nested using _fields param which is offered by wordpress. What's wrong with my query?
structure of response.
{
"_embedded" : {
wp:featuredmedia : [
{
"id": 21917,
"date": "2021-02-27T11:56:48",
"slug": "SLUG",
"type": "attachment",
"link": "
"title": {
rendered": "SLUG NAME"
},
}
]
}
}
Desired response :
{
"_embedded" : {
wp:featuredmedia : [
{
"link": "
}
]
}
}
Query I'm Trying to use:
| I believe what you want to use is **_fields=** not **_filter=**
I don't believe you can make fields only show _embedded thought. Best I was able to do was to make it show _links which then also shows _embedded.
Hope this helps. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, rest api, api"
} |
Display values of current POST request on page
I would like to get some value that was included in the http request header and display it on my webpage, i.e:
* I have a webpage, say: ' _mywebsite.com_ '
* I have a POST request to ' _mywebsite.com_ ' with a variable (lets call it `var_A`) in its header
* Then I would like to display the value of `var_A` on ' _mywebsite.com_ ', i.e. add it to the HTML
* * *
I've found things like: `get_the_content()` that will return the POST content of the current page. I can add that to my website using the _Code Snippets_ plugin, however, I can't seem to understand how to then display the content values (like `var_A`) on the webpage itself.
I'm a bit lost on how to connect the PHP stuff to the JavaScript that runs in the frontend? | You can use `filter_var` or, more directly, `filter_input` to retrieve data from the REQUEST data.
$var_a = filter_input( INPUT_POST, 'var_a', FILTER_SANITIZE_STRING );
The above code will get `var_a` out of the `$_POST` data, and sanitize according to PHP's `FILTER_SANITIZE_STRING`. You can read the PHP Manual on Types of filters for other data types. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, headers, http"
} |
How to control ajax calls without effecting memory of server?
I am trying to understand how ajax call and memory of server are linked? Is there any parameter in WordPress control this.
Say if am importing something big using ajax how can perform that without effecting the server with a memory limit of 250MB?
Pls help | An AJAX request to your server is no different to any other PHP request the server might handle, e.g. the frontend.
Browser requests have a time and memory limit configured at the server level, _WordPress itself is not responsible for setting or enforcing those limits._
> Say if am importing something big using ajax how can perform that without effecting the server with a memory limit of 250MB?
You have the following options:
1. Use less memory
2. Don't process the entire import in a single request
3. Break your import file into smaller chunks that get processed separately
4. Do the processing elsewhere, e.g. a CLI task. PHP running from a CLI command has no upper limit on time or memory except the amount of physical memory installed on the server.
Otherwise, you can't do stuff for free, there is always a cost. Browser requests are not suited to long running expensive/heavy tasks. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, ajax, server"
} |
What theme does this website use?
see <
Does anybody know the theme this site uses? Or, this site is not using wordpress? In this case, can you tell me what CMS/framework the site is built with?
Thanks | Looks like WP - BuiltWith shows Wordpress and Elementor as of Feb 2020, and Elementor classes are visible via inspector
There's no way to see which theme it is (afaik), but it's using Elementor, so it probably wouldn't matter which theme it uses if you're just looking to emulate its appearance.
Also worth noting that even when you use the same theme as another site, there are a million different ways in which a theme can be customized, so going for same/same is generally an exercise in futility. And the internet would be awfully boring if every site looked the same :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "themes"
} |
Overwrite tpl-footer.php in child
I am trying to overwrite a template file (tpl-footer.php) in my child-theme. According to the wordpress docs this should be possible just by adding the file with the same name and the same path into the child-theme. When I do so, nothing happens.
The theme I use is **snsnitan**
Does anyone know what I am missing? Do I need to overwrite more files?
The footer.php in parent theme has just:
<?php wp_footer(); ?>
</body></html> | **If the file is included via`get_template_part` or a part of the template hierarchy, then yes**, create a file with the same name in a child theme and WordPress will preferentially load that file.
**If the file is included via`include`/`require`, then no**, those are PHP language features, not WordPress functions, there is no way to intercept or override them so that your file is loaded instead. Either fork the theme or contact the theme support route. The author may have provided alternative methods of overriding the template, or be able to add support for it.
Remember, child themes let you preferentially load child theme templates via the template hierarchy and `get_template_part`. They can't auto-replace arbitrary PHP files, CSS, JS etc files by putting them in a child theme and expecting them to be used instead | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "parent theme"
} |
htaccess redirect not working
I'd like to 301 redirect all `.com/language/X` URLs to `.com/members/?members_search=X`.
Test case:
` should 301 redirect to
`
The rule I have set up:
RedirectMatch 301 "^/language/(.*)" "/members/?members_search=$1"
It works correctly when I use a `.htaccess` tester. The rule is at the very top of the `.htaccess` file. Any ideas? | Even though you've placed this rule at the top of the `.htaccess` file, `RedirectMatch` is a mod_alias directive so still runs _after_ other mod_rewrite (ie. `RewriteRule`) directives, so you may have a conflict.
Try changing this to a mod_rewrite directive. For example:
RewriteRule ^language/(.*) /members/?members_search=$1 [R=301,L]
NB: No slash prefix on the `RewriteRule` _pattern_ when used inside `.htaccess` files.
You will likely need to clear your browser cache before testing. Preferably test with 302 (temporary) redirects to avoid potential caching issues. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "redirect, htaccess"
} |
What is the reason for the new_to_publish hook not working?
this hook should normally be triggered on new post but it doesn't work
add_action("new_to_publish", "doSomething", 10,1);
function doSomething($post){
global $post;
$_SESSION['yeni'] = 'test';
}
echo $_SESSION['yeni']; | When you create a new post, the initial post status is not `new`, but rather `auto-draft`. Try this:
add_action("draft_to_publish", "doSomething", 10,1);
function doSomething($post){
global $post;
$_SESSION['yeni'] = 'test';
}
echo $_SESSION['yeni'];
Also note that you may want to make sure your session is properly initialized. To verify the callback works at least, enable `WP_DEBUG` and `WP_DEBUG_LOG` and do something like
add_action("draft_to_publish", "doSomething", 10,1);
function doSomething($post){
error_log( 'Inside the new post transition');
}
Then publish a post and look at `wp-content/debug.log` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "publish"
} |
About template hierarchy
The hierarchy picture doesn't tell me exactly which one is dominant.
/search/query/?category_name=general&post_type=custom
/category/general/?s=query
/tag/any/?s=query
/custom_post/?s=query&custom_tax=term
/?s=query&custom_tax=term&post_type=custom
When I tested the links I gave above, I could not draw any conclusions. When we open these links, I do not understand which archive file it prefers.
Sometimes it goes to `archive.php` while opening `search.php` in some cases.
Outside of this hierarchy, is there any indication of what it prefers when it comes to equivalence? | The answer is simple:
* `/search/query/?category_name=general&post_type=custom` is not a part of WordPress and has been added by a plugin/theme, you need to ask their support or inspect the code to find out
For everything else, if `is_search()` is true, then it's a search archive. If `is_search()` is not true it is not a search archive.
Since all of those URLs have `?s=` they are all searching for things, so they are all search archives.
We know this because it shows `search.php`, and because the body class is:
class="archive search search-results category category-maintenance category-39 logged-in admin-bar customize-support"
You shouldn't need to know the priority of template to know which template is currently loaded. WordPress shares this information openly if you built the theme correctly, debugging tools will tell you, and you can always put **this is the search template** at the top of `search.php` and see if the text appears. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "template hierarchy"
} |
what is the address of default home page?
By default we can see list of last notes, categories etc... int first page. After I installed WooCommerce I changed my home page to shoping page from settings->reading->front page. So far so good. No I want to add a link to my top navbar which points to the old home page url. But I don't know what's the url.
Bottom line: **I want to add a link to my blog.**
I don't want it to be the home page But I still need it !
Thanks In Advance, | _Settings > Reading_, set a page as your blog page and the URL will be that page's URL.
Please note that depending on your theme it may not use the same template as your previous front page. You will need to talk to the theme author if that's a problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "blog"
} |
How to display my comment count in the wordpress admin bar?
Ok, so when I'm logged in, the above admin bar show's zero. Even though I did wrote 5 comments:

to this code
if ($go_magazine_options['post_meta_author'] === 'enable' && in_the_loop()) {
echo '<span class="client">' . get_the_field('name') .
'<span class="entry-meta-author author vcard"><i class="fa fa-user"></i><a class="fn" href="' .
esc_url(get_author_posts_url(get_the_author_meta('ID'))) . '">' .
esc_html(get_the_author()) . '</a></span>' . "\n";
}
but something is not working? | Little Aprilia learns to code ;-) was a silly idea to mix two things, justed added the ACF-Field, using its own if-rule
if( get_field('apri') ): ?>
<span class= "promo"><?php the_field('apri'); ?></span>
<?php endif; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "advanced custom fields"
} |
PHP variable = get_the_post_thumbnail_url outputting without slashes
In a custom shortcode function, I'm grabbing the featured image URL:
$text_slider_testimonial_img = get_the_post_thumbnail_url($single->ID);
If I echo `$text_slider_testimonial_img` immediately I see the correct image URL: `//localhost:3000/wp-content/uploads/2021/03/splitbanner1.jpg`
When I pass this variable to a function, and that function uses:
$text_slider_content .= "<div class='text_slider_testimonial' style='background-size: cover; background-image: url('". $text_slider_testimonial_img ."')>";
return $text_slider_content;
the style component of the above is output as:
style="background-size: cover; background-image: url(" localhost:3000="" wp-content="" uploads="" 2021="" 03="" splitbanner1.jpg')="">
Why are the slashes being stripped out, and the `=""` being added?
Help appreciated.
Here is the wider code context (pastebin.com). | Replacing the line with below line may solve the issue.
$text_slider_content .= '<div class="text_slider_testimonial" style="background-size: cover; background-image: url('. $text_slider_testimonial_img .');">'; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, post thumbnails"
} |
RSS audio enclosures have length of zero (podcast duration is missing)
I have had success at creating an RSS feed with enclosures containing episodes of my podcast by simply creating a post and inserting an mp3 file from my media library into it via the robust `Add Media` functionality of the post editor. However, I have found that the RSS feed created from these posts includes an enclosure for each mp3 file with its length attribute set to zero:
<enclosure url=" length="0" type="audio/mpeg" />
How can I set the length attribute of the enclosure so that it is accurate?
I am not interested in changing the format of my posts, so any plugin-based solution should not require a significantly different workflow when posting. | The enclosure tag will implement via the function `rss_enclosure`. This function has the filter hook `rss_enclosure`. So you can change the result via this hook.
Here is a longer post about the how-to for audio files, this should help you. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "media, rss, audio, podcasting"
} |
Set WordPress Transient Expiration via Variable Value
I want to set WordPress Transient via Variable Value.
This is an example code with what I'm trying to achieve.
<?php
if ( false === get_transient( 'special_query_results' ) ) {
$ExpiryInterval = "24 * HOUR_IN_SECONDS"; // <--- Storing in Variable
$RandPostQuery = new WP_Query(array('post_type'=>array('tip'),'posts_per_page' => 1,'orderby'=>'rand'));
set_transient( 'special_query_results', $RandPostQuery , $ExpiryInterval ); // <-- Retriving from Variable
}
?>
I don't know why it's not working. If I try setting directly without variable it's working perfectly. Not sure why it's not working this way. | $ExpiryInterval = "24 * HOUR_IN_SECONDS";
`$ExpiryInterval` is being assigned a string, but you need a number.
Consider this example:
$foo = 5 * 10;
$bar = "5 * 10";
The value of `$foo` is `50`. The value of `$bar` is `"5 * 10"`. `set_transient` expects a number, not a string, `"24 * HOUR_IN_SECONDS"` is text/string, `24 * HOUR_IN_SECONDS` is a number. `HOUR_IN_SECONDS` is a constant equal to the number of seconds in an hour. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, transient"
} |
Please help a newbie with blog page issue?
<
<
The first link is to my post’s permalink. The second is at it appears when you go to the website’s blog page from the navigation panel. I have no idea how to make the second link look like the first. It’s really bothering me. I’ve dug around the settings and googled lots, but nothing. Can someone please help?
I’m using Bluehost’s BH Website Builder theme. | WordPress uses something called Post Types to generate different types of content.
The first URL belongs to a post ( default type ). You can access it under the "Posts" menu.
The seconds URL belongs to a post type called "page", or simply a Page. You can access it under the "Pages" menu.
To achieve what you need, you can make a new post and copy the page's content to it.
A better solution would be to setup pretty permalinks under the "Settings" menu. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, permalinks, pages"
} |
Changing the category for existing Gutenberg blocks
I'm trying to re-categorise some existing blocks (both core and third party). I've been told this should be doable using the registerBlockType filter but I haven't had much luck.
Could someone share a working example?
TIA | Try this, it changes the core Spacer block from the Design to the Media category in the insertor:
function myprefixFilterSpacerCategory(settings, name) {
if (name === "core/spacer") {
// Object.assign can also be used instead of lodash.assign
return lodash.assign({}, settings, {
category: "media",
});
}
return settings;
}
wp.hooks.addFilter(
"blocks.registerBlockType",
"myprefix/filter-spacer-category",
myprefixFilterSpacerCategory
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, block editor"
} |
How to add CSS via custom plugin?
I am making my first plugin. I create a folder in `\wp-content\plugins`, create a test.css and a test.php file.
Here is my test.css:
body {
background-color: red !important;
}
Here is my test.php (Taken from Theme Developer Handbook):
<?php
/*
Plugin Name: Site Plugin for Quảcầu.com
Description: Site specific code changes for Quảcầu.com
*/
function add_theme_scripts() {
wp_enqueue_style( 'style', get_stylesheet_uri() );
wp_enqueue_style( 'slider', get_template_directory_uri() . 'test.css', array(), '1.1', 'all');
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );
But the color doesn't change. Do you know why? Of course I have activated it. | Here's your problem:
wp_enqueue_style( 'style', get_stylesheet_uri() );
wp_enqueue_style( 'slider', get_template_directory_uri() . 'test.css', array(), '1.1', 'all');
Neither of those files are in your theme. `get_stylesheet_uri` refers to the `style.css` that has the themes name etc, and `get_template_directory_uri` is the URL of the parent theme. Neither of those are your plugin folder.
_You can confirm this by looking at the browser dev tools and seeing an error in the console that it tried to load a`test.css` from your themes folder and failed._
Instead use `plugins_url`.
e.g.
plugins_url( 'images/wordpress.png', __FILE__ )
Where the first parameter is the path to the file in your plugin folder, and the second parameter is the main plugin file location on the server.
So this:
get_template_directory_uri() . 'test.css'
becomes:
plugins_url( 'test.css', __FILE__ ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, css, wp enqueue style"
} |
From 3.5 to 5.6.2 - Recommendation on how to get there with the least amount of pain?
I've recently been asked to help someone who's neglected their WordPress for a long time. They're currently on 3.5. I need to get them current. I'm considering the following options:
1. Manually upgrade step-by-step. Outside of the pain of more than 20 steps, I'll also likely need to upgrade plugins when the old version no longer works with the next WP version.
2. Export the site contents using the WP export, then re-import the content. I've got a few plugins that won't export (and I'm not sure I want to deal with import/export of them from the database directly).
Any advice before I spend more time than I'd think it's going to take? | Considering that i) as @Tony Djukic put, "depends on how complicated the site is and how much of it is worth keeping around" ii) pain is something without an objective way of measuring iii) there will be some pain (and you acknowledge it). I say: just rip the Bandaid and go with option 2.
Evaluate if the website really needs the features and functionality the plugins provide. If so, add them progressively later. If the side doesn't need the features it has today, you just got done and have a clean(ish) slate, and it may even be less painful than you thought. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "upgrade"
} |
If post by specific role different css to everyone
So i have searched alot but cant find a solution.
Every solution which i find is changing css only to that specific role not for everyone else.
Basicly i want to do this:
If user role contributor then do this to his post and also so everyone can see it
.type-post { border: 10px solid #fff }
else
.type-post { border: 20px solid #000 }
So if a post i made by a specific user who has user role contributor his post borders color will be white and 10 px and everyone should see that not only people with that user role.
If post is made by everyone one else it should have default css or a css of my pick and everyone should see that including people with user role contributor.
Hope someone can help me out! | You can update the post classes depending on user role to include an additional selector which add your custom styling i.e
function add_contributor_class_to_single_post( $classes ) {
if ( is_single() ) {
$post_id = get_queried_object_id();
$author_ID = get_post_field( 'post_author', $post_id );
$author_data = get_userdata( $author_ID );
if (in_array( 'contributor', $author_data->roles)) {
// add post class
array_push( $classes, 'user-contributor' );
}
}
return $classes;
}
add_filter( 'post_class', 'add_contributor_class_to_single_post' );
Then update your css to:
.type-post.user-contributor { border: 10px solid #fff }
.type-post { border: 20px solid #000 } | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "css, user roles"
} |
Subsets and Splits