INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
malware in wordpress installer on dreamhost. <link rel='dns-prefetch' href='//coinhive.com' />
I was trying to create a website. It is live. And you can see that there is a malware which google detected.
In the source you will see three lines
`<link rel='dns-prefetch' href='//coinhive.com' />`
THere is one more place where coinhive is visible.
This is basically a code which mines monero on client's desktop/ laptop
Q) how do we find out how this malware got into the website at the first place? Parts: 1) Is it because of the shared hosting of dreamhost being hacked? 2) Some plugin which did this? 3) How do we remove this. 4) How do we make sure it does not come back :(
Have been trying to find out but no clue.
I have been building this for 3 months and have done many things including downloading some themes from "torrent"
So difficult to track. But if you guys have any previous experience, then it will be easy to figure out. | I found the problem..
Answering for others who might have gotten this...
There is this code embedded in one of the plugins
function enqueue_my_scripts() {
wp_enqueue_script( 'wp-internal', ' false, false, true );
wp_enqueue_script( 'wp-backend', plugins_url() . '/LayerSlider/assets/js/jquory.js', false, false, true );
}
add_action( 'admin_enqueue_scripts', 'enqueue_my_scripts' );
add_action( 'wp_enqueue_scripts', 'enqueue_my_scripts' );
And this javascript file Jquory.js.
Just remove the code above and the js file. The problem will be gone.
Cheers. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "hacked"
} |
Disable dragging of metaboxes in custom post types?
I am able to disable dragging of metaboxes sitewide with this function:
function disable_drag_metabox() {
wp_deregister_script('postbox');
}
add_action( 'admin_init', 'disable_drag_metabox' );
But I want it only on a custom post type. I tried the usual:
function disable_drag_metabox() {
global $current_screen;
if( 'event' == $current_screen->post_type ) wp_deregister_script('postbox');
}
add_action( 'admin_init', 'disable_drag_metabox' );
and also this one:
function disable_drag_metabox() {
$screen = get_current_screen();
if( in_array( $screen->id, array( 'event' ) ) ) {
wp_deregister_script('postbox');
}
}
add_action( 'admin_init', 'disable_drag_metabox' );
Sadly it doesn't work. What am I doing wrong? the custom post type is called event. | The current screen isn't setup on the `admin_init` hook. That's why `global $current_screen` and `get_current_screen()` don't work.
Every admin page has a `load-something` hook that fires after the current screen is set up. Since you say this is for an events custom post type, you should use the `load-post.php` hook. So you're code would look like:
function disable_drag_metabox() {
if( 'events' === get_current_screen()->post_type ) {
wp_deregister_script( 'postbox' );
}
}
add_action( 'load-post.php', 'disable_drag_metabox' );
You can use the Query Monitor plugin to figure out what hooks fire on each page and in what order. It also does a lot of other cook stuff. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "custom post types, customization"
} |
Product atributes in title of order (not in description)
I have couple of variable products. When someone order product, some product displey in new variation format (where order atributes are in title). Image: <
– And other disply whit old variation format (where product atributes are in description) Image: <
How can i display all order in old variation format ?
Thanks | This requires a little bit of code to be placed in functions.php. If you want you can use a plugin like WP-Designer to do that.
The WooCommerce filter 'woocommerce_product_variation_title' uses 4 arguments which are self-explanatory in the following piece of code which you can use in you functions.php. I tried it on my install and it works just fine.
add_filter( 'woocommerce_product_variation_title', 'wooc_product_variation_fix', 10, 4);
function wooc_product_variation_fix( $maybe_suffix, $product, $title_base, $title_suffix ) {
return $title_base;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "woocommerce offtopic, order, variables"
} |
How do I display the password field on the WordPress user registration screen?
On the registration screen I need to show the password field how do I do this with code without using plugins? | There is no password field (unless you use a specific plugin). You register for an account with a login name and email.
You then get an email with a link to set your password.
If you want to have users enter a password when they register, you should look into using a plugin or so, like Theme My Login. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "password"
} |
Check category before displaying featured image
My single.php shows the featured image:
if ( has_post_thumbnail( ) ){
the_post_thumbnail( 'full',array('class'=>'img-responsive') );
}
I don't want the featured image displayed if the post is in certain categories.
I have no idea how to write the code, none of the suggestions I found helped me. | `has_category()` will do the trick. You can pass it an ID or slug, or an array of IDs or slugs, and it will return `true` if the post has any of the given categories:
// ID
if ( has_category( 1 ) ) {
the_post_thumbnail( 'full', array( 'class' => 'img-responsive' ) );
}
// Slug
if ( has_category( 'one' ) ) {
the_post_thumbnail( 'full', array( 'class' => 'img-responsive' ) );
}
// IDs
if ( has_category( [1, 2, 3] ) ) {
the_post_thumbnail( 'full', array( 'class' => 'img-responsive' ) );
}
// Slugs
if ( has_category( ['one', 'two', 'three'] ) ) {
the_post_thumbnail( 'full', array( 'class' => 'img-responsive' ) );
}
And you can check if the post is not in certain categories by adding `!` to the condition, to indicate 'is not':
if ( ! has_category( [1, 2, 3] ) ) {
the_post_thumbnail( 'full', array( 'class' => 'img-responsive' ) );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post thumbnails"
} |
How to hide a specific user role option in a user role list?
I have to hide Administrator user role in the "User roles" area for these pages:
* /wp-admin/users.php
* /wp-admin/user-new.php
* /wp-admin/user-edit.php
;
function hide_adminstrator_editable_roles( $roles ){
if ( isset( $roles['administrator'] ) && !current_user_can('level_10') ){
unset( $roles['administrator'] );
}
return $roles;
} | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 6,
"tags": "wp admin, user roles"
} |
WordPress core code contains things marked as deprecated by... Wordpress?
I have some problems matching this message in my WordPress network update page:
> You have the latest version of WordPress. Future security updates will be applied automatically. If you need to re-install **version 4.9.4** , you can do so here:
With the one I just noticed after temporarily enabling debug mode:
> Notice: wpdb::escape is deprecated since **version 3.6.0**! Use wpdb::prepare() or esc_sql() instead. in /home/user/public_html/blog.network/wp-includes/functions.php on line 3846
>
> Notice: get_current_site_name is deprecated since **version 3.9.0**! Use get_current_site() instead. in /home/user/public_html/blog.network/wp-includes/functions.php on line 3846
What am I missing? How can core WordPress code still use code that its very own developers marked as deprecated? How can I update _functions.php_ file in _wp-includes_ to not use deprecated code and methods? | Line 3846 in `wp-includes/functions.php` is in a function named `_deprecated_function()`, which warns about the use of deprecated functions. I did a quick search of my copy of 4.9.4 core and didn't find any instances of `wpdb->escape()` or `get_current_site_name()`, the two functions you're _actually_ being warned about.
Most likely, the deprecated functions are in a plugin or a theme. If you disable all plugins and switch to a default theme (such as Twenty Seventeen), the **Notice** s should go away. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wpdb, deprecation"
} |
How to use Vuejs inside a custom control?
I'm building a custom control and would like to use Vuejs however I'm having trouble with Vuejs not being able to recognize the base element. I keep getting an error saying the element doesn't exist.
I'm guessing this is because the settings are loaded via ajax. I've tried loading the script with the `customize_controls_enqueue_scripts` hook but I can't get it working.
Any idea how to sort this out?
Thank you. | I suggest following the example found in Customize React Street Address Control, but using Vue instead of React. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme customizer"
} |
How to sanitize my cookie name
guys! I'm setting a cookie after my Gravity Form is submitted. The name is based on the current page, so each page that has this form will have its own cookie. Some pages with urls ending such as /324234-2/ will not set the cookie and return a error message ( **Warning: Cookie names cannot contain any of the following '=,; \t\r\n\013\014** ), while others with more regular names will. I'm trying to sanitize this cookie names so that I don't get any errors at all.
This is my function:
add_action( 'gform_after_submission_6', 'contentCookie', 10, 2);
function contentCookie($entry, $form) {
$from_page = rgar( $entry, '6' );
setcookie( 'unrestrict_'.$from_page, 1, strtotime( '+30 days' ), COOKIEPATH, COOKIE_DOMAIN, false, false);
};
How do I sanitize my cookie name? Thank you! | Assuming `$from_page` is a string value and not an array or object, `sanitize_key()` should do the trick, it allows only `a-z0-9_-` and I believe is used for permalink.
$cookiename = sanitize_key( 'unrestrict_'.$from_page );
setcookie( cookiename, 1 ...
there's a whole bunch of wordpress sanitizing functions, reference available in the docs. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, cookies, sanitization"
} |
Change the - WordPress from titlebar?
I use this code to edit the titlebar in the admin pages:
add_filter('admin_title', 'my_admin_title', 10, 2);
function my_admin_title($admin_title, $title)
{
return 'Example.com'.' • '.$title.' ‹ '.get_bloginfo('name');
}
Which works great, but I still can't figure out how to do the same with the title bar which appears on the Log in / Registration in the frontend. | Thank you mysticalghoul.
This was the answer:
function custom_login_title( $login_title ) {
return str_replace(array( ' ‹', ' — WordPress'), array( ' •', ' what ever you want'),$login_title );
}
add_filter( 'login_title', 'custom_login_title' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization"
} |
WordPress on VirtualBox - no pretty permalinks
Right, this has me stumped.
I cannot get the pretty permalinks to work. They go to 404.
The permalinks are updating, I can see the URL change to each setting as I save them by going to a post, but only the default "p=ID" works.
* Wordpress is installed under /var/www/html/
* .htaccess is being created and updated whenever I update the permalinks
* Owners and Permissions are set to www-data:www-pub and 755/644 (dir/file)
* AllowOverride All is set in the [my-site].conf file
* mod_rewrite is enabled
* apache2 has been restarted (several times).
Any ideas which I've not tried? | ... and as per usual, I figure it out as soon as I post the question -.-
Using this answer, I changed **apache2.conf** under _/etc/apache2/_.
There is a section towards the bottom talking about the security model. The section **Directory /var/www/** needs to be changed from _AllowOverride None_ to _AllowOverride All_.
I restarted apache and it works. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "permalinks, redirect, apache"
} |
Custom templates for a specific category
I am having issues creating a custom page template for a category in WP. I am currently using the standard content type "post".
So the issue is I have a parent category, and many sub categories and I would like any posts within these categories to use a specific layout. This custom template should apply to all sub categories within the parent. Is this possible, or would I need to create separate templates for each sub category?
I have looked at custom post types as another option, but It doesn't seem they have the hierarchy options required.
Any advise would be appreciated | Have a look at this article in the the WordPress Theme Developer Handbook.
You should create a template in your theme named `category-unicorns.php` where **`unicorns`** is the **slug for the parent category** you want this template to be used for. You can also create a template file `category-5.php` where **`5`** is the **id of the parent category**. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "custom post types, categories, templates"
} |
Why does the theme of secondary site load the primary one in Wordpress Multisite?
**I have this situation:**
1. I activated Multisite mode to develop the main website in a secondary site with subdomain "beta";
> EX: www.mysite.com, beta.mysite.com
2. I duplicated the default theme with "beta" suffix, but it is not set as a child theme;
3. every site has applied with the own respective theme.
> EX: _mysite-theme_ for www.mysite.com, _mysite-beta_ for beta.mysite.com
**The problem is:** when I visit the beta site, php files are loaded from _mysite-beta_ as expected, but the css files are loaded from _mysite-theme_.
Why does happen this with Wordpress? How can solve this situation? | To test with the primary content I used `switch_to_blog(1);` in a main php page and it causes that the `get_header();` function loads the header page of blog **1** (in this case).
So, I added `restore_current_blog();` after searching contents with WP_Query and before calling `get_header();` and the theme works as I expect.
I omitted the function because I thought it is not necessary, but I was wrong. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, multisite"
} |
Is there an equivalent to WP_Error object I can return in the case of a successful REST request?
In the case of an error at a REST endpoint I've set up, I am accustomed to returning a `WP_Error` object, which is convenient because I can include a code, a message, and an HTTP status into a single returned object.
But what about in the case of success? Is there an equivalent class, for the sake of control and uniformity?
I'm looking at the constructors of `WP_HTTP_Response` and `WP_HTTP_Requests` but they don't seem to accept the same parameters as `WP_Error`. | I think you are looking for `WP_REST_Response`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, rest api, http, wp error"
} |
The value of attribute [ data-type ] must be in double quotes - custom html widget error
I am trying to use a JavaScript typewriter effect and WordPress is throwing me the following error (The value of attribute [ data-type ] must be in double quotes.) when adding the html into a custom html widget.
I have the code working on CodePen. However w hen I change the data-type to double quotes and the data inside to single quotes the code stops working.
Any suggestions/am I missing something?
Thanks in advanced. | change it to CSV
data-type="Information Gathering, Farming & Husbandry, Delivery Service, Emergency Response, Remote Inspections, Mapping & Surveying, Maritime Success, Military & Defense Support, Scientific Research, Real Time Surveillance "
then do
var toRotate = elements[i].getAttribute('data-type').split(", ");
the `.split(", ")` turns the CSV string into an array. then do
new TxtType(elements[i], toRotate, period);
the `toRotate` is passed into `TxtType` as-is, it's not parsed by JSON anymore, just kept the array it is.
_prepare for a mod to flag this as unrelated to wp_ | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "javascript, html"
} |
Stop admin-ajax?
Is it possible to simply disable/stop `admin-ajax.php` from running?
Have searched WordPress Doc. Have searched Google. Have searched this forum. Found no answer.
Have also tried this, but it doesn't work:
function stop_ajax()
{
define( 'DOING_AJAX', false );
}
add_action( 'admin_init', 'stop_ajax' ); | The first thing `admin-ajax.php` does is define `DOING_AJAX`. Then, it loads `wp-load.php`. It does some other stuff, and the first thing it comes across that you have control over is `wp-config.php`.
So if you want to stop all ajax, you can add to following to your `wp-config.php` file.
if( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
wp_die( '0', 400 );
}
If you don't have access to the `wp-config` file, or just want to do it via a plugin, you can do that too. No need to add it to a hook since if it's a request that doing ajax, it's already defined.
/**
* Plugin Name: Stop Ajax
*/
if( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
wp_die( '0', 400 );
}
There will be side effects if you're using plugins or themes that require ajax, so be careful. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 7,
"tags": "ajax, admin"
} |
Change default recovery link expiration time
I need to change the default expiry time of the WordPress password recovery link. I'm not sure how to go about this, I need to set it to ~30+ days (Gross I know).
So far my searching has come up pretty empty. I have however found this little snipped `$expiration_duration = apply_filters( 'password_reset_expiration', DAY_IN_SECONDS );` Obviously this won't do it on it's own. I have tried combinations of apply / add filter in my themes functions.php but to no avail. (Testing by setting the expiry time to 30s and then trying to login.)
Thanks! | I would think this would change it to a month:
add_filter( 'password_reset_expiration', function( $expiration ) {
return MONTH_IN_SECONDS;
});
using the built-in `MONTH_IN_SECONDS` constant.
For a quick testing:
add_filter( 'password_reset_expiration', function( $expiration ) {
return 60; // A minute
}); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "password"
} |
How to modify "[Product] has been added to your cart" in WooCommerce?
I would like to change the "Product has been added to your cart." text for variable products to include the variation.
For example if I added a size 7 Shoe to my cart it should say: "Shoe in Size 7 was added to your cart"
What do I have to edit to change this? | add_filter( 'wc_add_to_cart_message', 'my_add_to_cart_function', 10, 2 );
function my_add_to_cart_function( $message, $product_id ) {
$message = sprintf(esc_html__('« %s » has been added by to your cart.','woocommerce'), get_the_title( $product_id ) );
return $message;
}
The above code will help you to change the message. Since by knowing the hook `wc_add_to_cart_message` you can improve the code | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "woocommerce offtopic, filters"
} |
How to fix wordpress site url attaching to social media links in the widget?
I'm using the Willow theme and when I "customize" the social media widget in the footer for some reason it attaches the site's url to the buttons.
For example, I have inputted the Facebook link for the Facebook button but when I go to click it, it shows up as:
`myWordPressSite.com/www.facebook.com/` instead of just `www.facebook.com/`
I'm not sure what is causing it, I'm not well versed in WP, but I want to learn how to fix something like that. Do I need to access the jQuery UI Widget? I have full admin access incase anyone is wondering.
I'm not sure what other kind of details you may need but please let me know and I will provide what I can
Thanks! | You've left ` or ` off the links. For example:
www.facebook.com/
will be treated as a relative link to the current URL, while:
is the actual URL to Facebook. You need to enter the whole thing so the browser knows that it's a link to another domain/website. This applies wherever you enter links. It's not a WordPress or theme issue, it's just not writing URLs correctly. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "widgets"
} |
Is there a way to override require_once of the main theme on the child theme?
I would like to override a `require_once` present at the beginning of the functions.php of my main theme through my child theme.
specifically I have:
require_once get_template_directory().'/libs/some-function.php
I know that replacing `get_template_directory()` with `get_stylesheet_directory()` I can load a modified copy of the some-function.php file into my child theme. but I wouldn't change the parent theme, I would make the change only in the child theme.
I add that the `require_once` is not hooked
Suggestions?
Thanks | No, the parent themes `functions.php` is always loaded, and `require_once` is not a WordPress API but a part of the PHP language itself
The only way to change it would be to modify the file | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "customization, themes, child theme"
} |
Debug.log file is never created?
It's the first I have seen this. In a project I'm working on, I tried to switch on the debug mode for wordpress to see logs. Even if I activate the debug_log in `wp-config.php`, `debug.log` file is never created in `/htdocs/wp-content/`
**wp-config.php**
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors',0);
define('SCRIPT_DEBUG', true);
**wp-content dir rights**
 {
ini_set( 'log_errors', 1 );
var_dump( WP_CONTENT_DIR . '/debug.log' );
// display correctly this => "/htdocs/wp-content/debug.log";
ini_set( 'error_log', WP_CONTENT_DIR . '/debug.log' );
} | I found the problem. In the Apache server, inside the php.ini, the variable...
track_errors = Off
To get this information, you can do in a phpfile `phpinfo();`. So, to write the debug log file, you need to set `track_errors` as `'On'`. | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 7,
"tags": "debug, wp debug"
} |
Get Objects While Deleting term
I created a custom taxonomy **organization** for users and I could get specific organization user list by using **get_objects_in_term($term_id, $taxnomy_name)** functions. But, I can't use **get_objects_in_term($term_id, $taxnomy_name)** while deleting term with these below action
do_action( 'delete_term_taxonomy', $tt_id );
do_action( 'deleted_term_taxonomy', $tt_id );
do_action( 'delete_term', $term, $tt_id, $taxonomy, $deleted_term );
do_action( "delete_$taxonomy", $term, $tt_id, $deleted_term );
My question "Is there any ways to get user list from specific organization before deleting that organization?" | Use the `pre_delete_term` hook, which fires before the actual deleting occurs, so the relationships will still be present.
function wpse_296972_pre_delete_term( $term_id, $taxonomy_name ) {
if ( $taxonomy_name === 'organization' ) {
$objects = get_objects_in_term( $term_id, $taxonomy );
// Do something with $objects.
}
}
add_action( 'pre_delete_term', 'wpse_296972_pre_delete_term' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugin development, terms"
} |
Custom post type sorting: alphabetical order
I want to display my custom post type "portfolio" in alphabetical order and I got it working fine with this code:
add_filter("posts_orderby", "my_orderby_filter", 10, 2);
function my_orderby_filter($orderby, &$query){
global $wpdb;
//figure out whether you want to change the order
if (get_query_var("post_type") == "portfolio") {
return "$wpdb->posts.post_title ASC";
}
return $orderby;
}
Unfortunately it affects also normal posts order list. I don't know why. How may I fix this? Thank you | Try using `$query->get()` instead of `get_query_var()`.
function my_orderby_filter($orderby, &$query){
global $wpdb;
//figure out whether you want to change the order
if ($query->get("post_type") == "portfolio") {
return "$wpdb->posts.post_title ASC";
}
return $orderby;
}
Alternatively, you can use this one, which filters the query via the `pre_get_posts` hook.
add_action( 'pre_get_posts', 'my_orderby_filter2' );
function my_orderby_filter2( $query ) {
if ( 'portfolio' === $query->get( 'post_type' ) ) {
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, order, sort"
} |
How to remove scripts/style added to customize_controls_enqueue_scripts hook by current active theme
I am looking for a way to remove/unhook all assets (css and javascript) files added to customize_controls_enqueue_scripts hook when the query string `mo-reset=true` is added to the customize url. | You can use the `global $wp_scripts` and `global $wp_styles;` to get all registerd scripts and styles.
Eg.
;
foreach( $wp_scripts->registered as $script ) :
$all_scripts[$script->handle] = $script->src;
endforeach;
// echo '<pre>';
// print_r( $all_scripts );
// echo '</pre>';
All **Styles**
// All Styles
global $wp_styles;
$all_styles = array();
foreach( $wp_styles->registered as $style ) :
$all_styles[$style->handle] = $style->src;
endforeach;
// echo '<pre>';
// print_r( $all_styles );
// echo '</pre>'; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "hooks, wp enqueue script, theme customizer, wp enqueue style"
} |
Moved WP Multisite, cannot access sites
Just moved my WP Multisite from example.com to example.com/u/ I can access the main site and the admin pages for that and the network admin. But i cannot access the example.com/u/site1 or their example.com/u/site1/wp-admin I have changed all the URLs to include the subdirectory, but it still is not working.
What am i missing? | Solution was:
RewriteBase /u
Inside .htaccess | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "multisite, directory"
} |
How can check if heartbeat is disabled?
I want a code to check if the heartbeat is disabled from a WordPress site or not. | The heartbeat API is essentially a script that is included in your site's head. It performs calls back to the server. So, to disable the heartbeat the script must not be enqueued. And you can check whether a script is enqueued with `wp_script_is`. Like this:
if (wp_script_is ('heartbeat')) ... | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "heartbeat api"
} |
Use WP admin AJAX url to hide API key
Currently I am using `AJAX` to request a simple `JSON` response from an external API. The problem is, that the API key is exposed. I'm aware the best method is to process this through `admin-ajax` and set call the url through PHP. What is the most secure method to do this, and how can this be requested through PHP?
$.ajax({
type: "GET",
url: "
data: dataString,
dataType: "json",
//if received a response from the server
success: function(response) {
console.log(response);
},
}); | I would break this problem in to 2 parts.
First, you could sent an Ajax request to your server, sending only the `dataString` variable.
Then, you can use either `cURL` or `wp_remote_get()` on the server to access the real API.
This could be the only solution, if you want to avoid playing hide and seek with hashes and writing tons of code just to make it hard for the users to find the API key. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "ajax, wp admin, api, curl"
} |
REST API URL parameters not working with apache server
The title pretty much says it all, if I try eg. `/wp-json/wp/v2/posts?id=1`, I get all the posts as response. URL parameters are not working as they should. According to the REST API Handbook, the server is not configured properly to detect URL parameters. There's a common solution given for nginx servers, but I use apache, so I have no idea how to solve this. | You’re using the wrong endpoint. Look at the documentation. `id` is not one of the parameters for the posts endpoint.
The correct way to retrieve a post with the ID of 1 is:
/wp-json/wp/v2/posts/1 | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "rest api, apache"
} |
How to add a new button on post
I would like to add a button next to the _edit button_ on each article, with a link to a specific page.
This button is for translation purpose. It should redirect the user to the translation page of the post.
Thanks in advance for your help. | in the free theme Customizr, you can add content after the edit link with this code in the file `functions.php` of the child theme
add_action("__after_regular_heading_title", function () {
$post = $GLOBALS["post"];
?>
<span>
an addition after the link to edit
"<?php echo htmlspecialchars($post->post_title);?>"
</span>
<?php
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "front end, buttons"
} |
How do I get slug of all active plugins programmatically?
I want to check plugin version using following API
For that how can I get Slug of All Active Plugins ? | Use option `active_plugins` to get all plugin init files. e.g.
$current = get_option( 'active_plugins', array() );
// print_r( $current );
Here, `htmlpress` is the plugin slug.
 | As you can see in the hierarchy flowchart on the page that you linked to, Site Front Page will choose `front-page.php` before falling back to behaving like a normal page:

I could get **comment_date** with a loop.
And it shows like **2018-03-19 12:30:06**.
Here, I just want to get **Last seen** format.
(For instance, **3 min ago , 1 hour ago , 1 day ago , 2 week ago** )
How can I achieve it?
["comment_date"]=>
string(19) "2018-03-19 12:30:06"
["comment_date_gmt"]=>
string(19) "2018-03-19 12:30:06" | WordPress already have such function in its core. It’s called ‘human_time_diff’ and it’s used in WP admin section.
Usage is pretty simple:
echo human_time_diff( $from, $to );
where $from is Unix timestamp from which the difference begins and $to is Unix timestamp to end the time difference (or time() by default).
So you’ll have to use strtotime function to convert date to timestamp.
Here you can find more info about it and some examples: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "comments, date time, formatting"
} |
File sharing platform for user contributions?
I am looking for a way to allow my visitors to share content between each other in an organized fashion. Essentially the ability to upload files or browse/download files that others have contributed.
These are just XML configuration files that contain a plethora of settings for a 3D printers, so at the core they are really nothing more than just text.
Before I go reinventing the wheel though, is there anything like this already available for Wordpress? If not, what would be my best option? I am thinking perhaps a custom post type, but giving anyone the ability to add them seems difficult. | I suggest using BuddyPress groups with the BuddyPress Docs plugin (attachments enabled).
You need to allow XML uploads with:
add_filter('mime_types', 'custom_upload_xml');
function custom_upload_xml($mimes) {
$mimes = array_merge($mimes, array('xml' => 'application/xml'));
return $mimes;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, uploads, media library, file manager"
} |
Pulling author name via $_GET parameter
So I'm running a few ACF forms. One creates the post, and then I have an edit post form that edits the post via a form that populates based on the post id.
So my edit post url: site.com/edit-post/?post=478
Then I have some code in my file:
<?php
$post_id = $_GET["post"];
This effectively lets me get the current post ID based on the ID passed in the URL. It works well for my forms. The issue I'm having is I want to display the author name for the post in the URL, however I can't seem to find the right syntax to do it. I've tried `the_author();` and it doesn't give me the right author.
Additionally, I tried `the_author_meta( 'display_name', $post_id['post_author'] );` and it gave me a different author name but still not the right author for the post.
Any ideas as to what I could try to get this working?
Thanks, let me know if you need more info. | You get the author ID of the post ID via get_post_field
$post_author_id = get_post_field( 'post_author', $post_id );
With this post ID you get all author meta data, also the name like
the_author_meta( 'display_name', $post_author_id ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "advanced custom fields, author"
} |
Finding post content that begins with a specific character
If I want to find all posts where the very first character(s) of the post text / content (ie not the title) are
"<"
or
"<a"
How would I do so?
I tried these solutions:
<
<
but they did not work | Something like this will probably work:
$results = array();
$allPosts = get_posts('post_type=post&numberposts=-1');
foreach ($allPosts as $aPost) {
if ( substr($aPost->post_content, 0, 1) == '<' || substr($aPost->post_content, 0, 2) == '<a' )
$results[] = $aPost->ID;
}
echo "<pre>".print_r($results,true)."</pre>";
**UPDATE:** but you should revisit the MySQL approach in the links you provided. This php method is somewhat wasteful as it gets everything, instead of only whats needed. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "wp query, functions"
} |
wordpress do not let user registered with info@ email and other reserved emails to get registered by users
Does wordpress do not let user registered with info@ email and other reserved emails to get registered by users?
how to fix this...?
when ever user are trying to register with [email protected] they are getting error as Email already exists, although it never actually exist! Please help me! | I fixed it myself.
The issue was with the Hosting, they altered the Apache Configuration, which resulted in complete E-mail failure.
Thanks for Support Everyone! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "email, user registration"
} |
How do WordPress Nonces Work?
I am trying to understand how WordPress nonces work in terms of security. `nonce` stands for a number used once, but according to WordPress, it can be valid for up to 24 hours, which makes no sense. It could be used 9999 times during this period (by same client).
I thought that a WordPress nonce is really a number used once and that a nonce is valid only for one-time usage, but that's not the case. I guess for a better security, a one-time usage number would be better, e.g. you have a commenting system and someone clicks on "reply" two times. Instead of inserting the comment two times, it is being inserted one time, because of the one-time valid nonce (same one) given in the two requests.
Am I getting something wrong? What is the purpose of those WordPress nonces? | If you read Wordpress Nonces in Codex, they have explained it pretty fairly. some of the key points are:
1. always assume Nonces can be compromised.
2. Nonces are a hash made up of numbers and letters.
3. Wordpress Verifies any https request with both `nonces` and `user cookies`.
I believe point #3 is, in short, is how it works with WordPress. They have mentioned that use `current_user_can()` function instead of wordpress nonces.
As for the purpose, I believe, it serves basic purpose of multilayer security. Read this Are Nonces Useless | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 6,
"tags": "security, nonce"
} |
Custom Post Type using single.php is looking for a template that doesn't exist
I have a list of custom post types, which includes one called "Tall_Homes" and a home page of six boxes generated from six different custom post type excerpts. They all link successfully to content-single.php, via single.php where
`$post_type = get_post_type( $post->ID );`
is used to write each page. They all work except for Tall_Homes, which doesn't reach the single.php page. Instead it generates this error:
`Warning: include(.../post-template-tallhomes.php): failed to open stream: No such file or directory in ...\wp-includes\template-loader.php on line 74`
However, there is no "tallhomes.php" template and this spelling of "tallhomes" is not found in the custom post type setup. I don't know where it's coming from.
Which one of the register_post_type items or args contains the information used to generate the template name? Any idea how to fix this?
Thanks Charles | Without seeing more code, on the surface it looks like a typo somewhere because the `{$posttype}` would be `tall_homes`.
You could try putting an override function in your theme's `functions.php` file though that should get around this:
function tall_homes_override( $template ) {
global $wp_query;
$post_type = get_query_var( 'post_type' );
if ( $wp_query->is_single && $post_type == 'tall_homes' ) {
return locate_template( 'single.php' );
}
return $template
}
add_filter( 'template_include', 'tall_homes_override' );
What this should do is that when WordPress goes to look for what template to use, it will test and see if this is a single post and what the `post_type` is. If it is single and the post_type is `tall_homes` then it will set it to use `single.php` instead. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types"
} |
Query the REST API for a Tag by slug
Is it possible to query the API directly using a tag slug rather than a tag ID? Or do you have to query the main tags endpoint to find out its ID?
For reference, you can fetch a tag this way:
> GET /wp/v2/tags/
<
Does core support a method that would allow me to use a slug instead of an ID? Or is there a workaround/filter addition that might add this? | I was looking at this before... Here is what I found (about 7 months old from today 3/21/2018.)
The “correct” way to do this with the REST API is to get the IDs of each of those tags, then make the request using the ?tags= parameter: assuming “clicks” has ID 1, and “passes” has ID 2, that would look like this
[
Using slugs for querying taxonomy terms is an issue, but slug-based queries were deliberately left out of core because they are more prone to change than taxonomy term IDs. To demonstrate the issue, if you renamed a slug and made a request with an outdated slug, your request will fail; but if you use the ID, changing the slug will not break your query.
You can get the ID of a slug by querying for e.g. `/wp/v2/tags?slug=clicks` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "rest api, endpoints"
} |
What's the best way to add the LESS preprocessor to a WordPress theme?
I have looked for a good plugin for using LESS in a WordPress theme and the most relevant options I've found are:
< (last updated 6 years ago) < (last updated 4 years ago) < (last updated 3 years ago)
LESS still seems to be a good CSS preprocessor and many people use it so why am I having trouble finding an updated solution for that? | After the comment of David Sword I realized that doesn't exist a best way to use LESS on a WordPress theme, but several ways to do that. And a good way is to use the resources of a good text editor. I'm used to work with Sublime Text 3 but after trying several times to make it work with no success I decided to use another text editor, Crunch 2, and with it I didn't have any problem to compile the .less file to .css, as this is a normal feature of the free version. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "css"
} |
Where to store OAuth 2.0 client id and secret?
I'm building some functionality within one of my WordPress sites that integrates with a third-party API, and that API uses OAuth 2.0.
I use both the client ID and secret every time I need a new access token, which is going to be at least once a day as the access token expires after 24 hours. (Generating a new access token also generates a new refresh token, and the previous refresh token is invalidated.) I'm storing the tokens in the options table in the database, along with the expires_in time.
Where should I be storing my client ID and secret? Is there a typical place to store things like this within WordPress? Right now I just have them defined in the wp-config.php. While I'm thinking this should work well, are there any potential drawbacks to this method, particularly regarding security of the client secret? | This depends on what is it that you are developing. If it is a plugin, you have to store such settings in options as the last thing site owner should be asked to do is to modify their config file.
If it is your own site, just make it a constant that is declared in your code if you do not want it to be configurable by the admin. There is no advantage in keeping it in some non obvious place which is harder to find when inspecting the code.
As for security, in theory having it in the code is more secure, as you do not have to worry about someone hacking into the DB, but in practice, since if someone can get into your DB you are already toast (he will add its own admin user...), it makes almost zero difference. (the only difference I can think of is getting a dump of the DB, but this kind of hack is still hard and probably super rare) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "security, api, wp config, oauth"
} |
What's the difference between same wp functions get_posts(); functions in different form?
get_posts('post_type=post&numberposts=-1')
**and the**
get_posts( array(
'post_type' => 'post',
'posts_per_page' => -1
) );
**Are they the same?** | Yes they are, the first form is internally converted into the second. IMO you should not use the first form as it is a relic to the days wordpress DB structure was much simpler. Today I am not sure if you can even achieve all the things you can do with the second form by using the first. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, php, functions, theme development, metabox"
} |
Reinstall WordPress from zero
So, i'm a member of a voluntary team in my university and we're having a wordpress website. I'm the only one who knows how to handle it so i'm responsible for everything about it. The problem is that we're having some problems with it (like not allowing to upload anything, except if i manually upload it from FileZilla) and i'd like to delete this particular version and clean install a new one. The problem is I haven't done this before so i'd like someone to verify that the steps i'm going to make are correct:
1. Delete wordpress database from Phpmyadmin
2. Delete everything regarding wordpress inside public_html folder from FileZilla
3. Create a new database,
4. Install a new WordPress version in public_html folder
Are those the exact steps? | Yes, you're right. Steps need to do:
1. Delete the `db` related to your WordPress installation( or you can just emty your `db` without deleting it. This option will save several minutes of your time to not creating another `database` )
2. Delete all files related to your installation
3. Upload another version of website, unzip it( if it has archived ) and call your website url from browser
4. You'll see fresh WordPress installation page:
">Copy text</button>
<p>The document.execCommand() method is not supported in IE9 and earlier.</p>
<script>
function myFunction() {
var copyText = document.getElementById("myInput");
copyText.select();
document.execCommand("Copy");
alert("Copied the text: " + copyText.value);
}
</script>
Source found here: w3schools | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, javascript, html, buttons, text"
} |
Get the most recently modified post date of most recently modified post
I have Googled this, but there are always answers to get the modified date of a single post, which I know how to do.
What I'd like to do is get and display the most recent modified date of the _most recently modified post_.
In other words, if I have 100 posts on a site and someone modifies any one of them, I want to display that date elsewhere on the site.
As in "Most recent site update: March 25, 2018" | Try this:
$q = new WP_Query;
$posts = $q->query( array(
'posts_per_page' => 1,
'orderby' => 'post_modified', // Sorts by the date modified.
'order' => 'DESC', // Sorts in descending order.
'no_found_rows' => true,
) );
// Note that $posts could have more than one post, if your site have sticky
// posts. However, the first post, unless filtered by plugins, would always
// be the most recently modified/updated one.
if ( ! empty( $posts ) ) {
$post = $posts[0];
setup_postdata( $post );
?>
<p>Most recent site update: <?php the_modified_date( 'F d, Y' ); ?>.</p>
<?php
wp_reset_postdata();
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, query posts, date time"
} |
product_cat image url from database
I am trying to get the image url of the product categories.
I got all product categories using:
SELECT * FROM wp_terms WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE taxonomy='product_cat')
I found that the images are stored as posts with post_type = 'attachment', but I can't find the connection between those and the product categories.
SELECT * FROM wp_posts WHERE post_type = 'attachment'
Thanks in advance! | The connection was in wp_termmeta. The term_id has a meta_key = 'thumbnail_id' and the meta_value is the post_id containing the url of the image. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, woocommerce offtopic"
} |
Can I Create a Second Admin Level User Role?
I want to create a second User Role, which has the same priveleges like a Admin User Role. This way I can use the Adminimize plugin to disable some features there.
I'm trying to have a User Account which can view certain Admin stuff, but not everything.
The limitation I got right now is that with Adminimize, if I disable certain features for the Admin user Role, they also get disabled for me (the real admin).
Or does anyone have a better way of doing this?
Thanks in advance! | You can use this plugin: <
You can set up a new role and copy all allowed tasks to the new role. In adminimize you can then disable what you need to. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, user roles, user meta, capabilities, user access"
} |
How can I remove the editor from the 'main posts page'?
I'm trying (and failing - despite the numerous previous posts by others) to more easily/reliably remove the content editor from this page.
I can remove it using the page-ID:
add_action( 'admin_head', 'hide_editor' );
function hide_editor() {
if( isset( $_GET['post'] ) && $_GET['post'] == '7' ) // '7' is the ID of the page ID.
remove_post_type_support( 'page', 'editor' );
}
But I'd prefer to remove it according to template used - in this instance, the default 'home.php'.
I've tried various conditionals, variants of 'get_page_template' and 'is_page_template' - none of which work... I suspect because the page uses a default rather than selected template. | WordPress already does this by default, so long as that page doesn't have any existing content. Plus it adds a notice explaining why the editor isn't there.
These are the lines already in WordPress Core:
if ( $post_ID == get_option( 'page_for_posts' ) && empty( $post->post_content ) ) {
add_action( 'edit_form_after_title', '_wp_posts_page_notice' );
remove_post_type_support( $post_type, 'editor' );
}
Lines 74-76 here: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post editor"
} |
Woocommerce template single-product.php in theme folder not working
`single-product.php` not working for single products. I do not have `woocommerce.php` file in my theme but still `single.php` executing for single products. This is a custom theme and when i change my theme name to `twentyten` then `single-product.php` started to execute but when i change its name to something else (custom theme name) than this template does not work at all and instead it execute single.php Any suggestion will be much appreciated. | I add this line in my theme's functions.php file and now everything working fine.
add_theme_support( 'woocommerce' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "woocommerce offtopic, templates"
} |
Getting a ressource ID, from a WC_Order_Item_Product/Order
I have been trying to figure out how i get the ressource on a WC-order, from the product line data, but i seem not to be able to figure this out in WC 3.0+ - pre that it was pretty easy.
I have looked at both the booking meta data, the order meta data, and everything else i can think of, but still unable to find what im looking for.
I have 1 Product with the ID 194 and that product have 2 ressources - and im looking to find the resource in the order line.
Code:
$order = new WC_Order((int)$order_id);
$orderLine = array_values($order->get_items())[0];
Plugins:
* Updated WooCommerce
* Updated WooCommerce-Booking | So i found a "solution" even though it's not as good as i hoped - or atleast not as good as the way it was done pre 3.0.
$iOrderID = $_POST['iOrderID'];
$aBookingQuery = new WP_Query(
array(
'post_parent' => (int)$iOrderID,
'post_type' => 'wc_booking',
'posts_per_page' => 1
)
);
= $aBookingQuery->posts[0]->ID;
$iBookingRessoureceID = get_post_meta($iBookingID)['_booking_resource_id'][0];
this gives you the ressource ID of said booked product. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, functions, woocommerce offtopic"
} |
How to find default functions of wordpress
How can I find all the default functions that are required for theme development.
Like for logo, widgets etc. | The Theme Handbook would be the place to start. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development"
} |
List $wp_admin_bar menu items (debug)
I would like to dump the content of the `$wp_admin_bar` object in order to remove some menu items with the `remove_menu()` method.
What is the suggested way to do it without printing anything on the website?
I have enabled `WP_DEBUG` and `WP_DEBUG_LOG` in `wp-config.php`. I was thinking about printing it in `debug.log`
Thanks for the suggestions! | You can use `error_log()` and `print_r()`:
add_action( 'wp_footer', 'wpse_debug_toolbar' );
function wpse_debug_toolbar() {
global $wp_admin_bar;
error_log( print_r( $wp_admin_bar, true ) );
}
Note that when using `print_r()` we've set the second parameter `$return` to `true` so that the results are returned and not echo'd. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp debug"
} |
Auto assign author to new posts with wp_insert_post_data
I need to make the default author for all **new posts** be already selected but leave existing posts unmodified.
So since the default post status is "draft" i thought to only do this if the post is a draft like so:
add_filter( 'wp_insert_post_data' , 'update_author', '99', 2 );
function update_author($data , $postarr) {
if ($postarr['post_status'] == 'draft') {
$data['post_author'] = 45;
}
return $data;
}
But then it never runs, so i tried the other way around. Do it when it isn't "published" but then it runs for all new and existing posts...
add_filter( 'wp_insert_post_data' , 'update_author', '99', 2 );
function update_author($data , $postarr) {
if ($postarr['post_status'] != 'published') {
$data['post_author'] = 45;
}
return $data;
}
What am i missing here? | to know if it's a new post, you juste need to read the value of `$postarr["ID"]` :
$postType = "post";
add_filter("wp_insert_post_data" . $postType, function ($data, $postarr) {
if (0 === $postarr["ID"]) { // it's a new post
$data["post_author"] = 45;
}
return $data;
}, 10, 2); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "author"
} |
Remove year and month in URL using .htaccess
For example, to redirect old URLs of the form:
`/2016/10/mukunda-murari-kannada-songs-download.html`
To
`/mukunda-murari-kannada-songs-download.html`
I have already changed the permalink structure in WordPress, but wish to redirect the old URLs to the new, in the most efficient way, in order to help preserve SEO.
This is my code:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)/?$ $1.html [L,R=301]
RewriteRule . /index.php [L]
</IfModule>
# END WordPress | Assuming you have already changed the permalinks structure as @RickHellewell suggests, then you can do something like the following near the top of your `.htaccess` file (before the existing WP front-controller) to redirect the old URLs (with the stated format) in order to preserve SEO.
RewriteRule ^\d{4}/\d\d/([a-z-]+\.html)$ /$1 [R=301,L] | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "htaccess, seo, mod rewrite"
} |
Remove certain post-formats from showing in blog?
I'm coding this wordpress theme and I enabled post-formats, currently designing them. What I want to do is use quote post-format to display reviews and I don't want it to show in blog posts. Is that possible?
**EDIT:** This may be a dumb question but can you create your own post-format? | It might be possible, but you can not control what the user has in the DB before activating your theme, so you might have to handle "quotes" which are not reviews in any case.
In theory you can try to detect based on the content, or if you use some specific meta values, based on them, whether it is a review or not and handle the html generation accordingly.
I would not be too worried about that as post format are rarely used, so the chance of them being used wrongly, is probably slim.
As for the not "dumb" at all part, You might be able to hack it, but the whole point of post formats is that it is standardized between themes. If you create something outside of the standard, it might work in your theme, but fail when the user switches to another, or fail integration with plugins, so not advisable at all.
It sounds like what you should consider is using a custom post type for it, which is what "testimonials" kind of plugins do. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, blog, post formats"
} |
404 error on default post type and default taxonomy fronted page
I have installed WordPress through Softaculus installer. After that I logged in and created a post. when I wanted to view the post it says 404 page not found.  can see a lot of information that only an admin can on their Dashboard. Is this normal?? If yes, how do I change it??
They can see the website statistics and plugin information.
The screenshot:
<
!Screenshot | Subscribers will see the WP Events and News widget, but they shouldn't be seeing the other stuff. Somewhere the theme and/or plugins are adding widgets in a way that's allowing all user levels to see them. You can either hit up the support teams for the themes and plugins that are adding them, or you can create your own plugin with code that removes these metaboxes. You'll need to look up the name for each meta box; here's one example that removes the "Right Now" box:
<?php
add_action('wp_dashboard_setup', 'wpse_298944_clear_dash_widgets');
function wpse_298944_clear_dash_widgets() {
if(!current_user_can(publish_posts)) {
remove_meta_box('dashboard_right_now', 'dashboard', 'normal');
}
}
?>
Another option is to call the global variable `$wp_meta_boxes` and unset them one by one. See How to Remove ALL Widgets from Dashboard? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "users, dashboard, permissions"
} |
custom post type section selector
I have a custom post type which is named products. Each product will have overview/details/pricing.
How can i make a navigation inside my post-type for each field? Example:
* Product 1: (Custom Post Type Product)
* Overview/Details/Pricing (Custom Fields i guess)
On overview click i want to display an overview for the product, (maybe use a child page and load into the overview field? )
I'm really confused, can anyone help? | Ok, as requested.
Create an ACF field. Add a repeater field. Inside the repeater, add a text field with name title. Inside the repeater, add an URL field with name link.
$menu_items = get_field( 'repeater_field' )
if ( $menu_items ) {
echo '<ul>';
foreach( $menu_items as $item ) {
echo '<li><a href="{{ item.link }}">{{ item.title }}</a></li>';
}
echo '</ul>';
}
You can then link to any sub-pages you have created. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types"
} |
what is the use of esc_attr() function?
I want to know use of **esc_attr()**? how it is used? Any example would be highly help!
esc_attr( $variable ) | esc_attr() is written specifically for escaping a string that is to be used as an html attribute, which means also escaping single and double-quote characters etc.
In general, it's better to use the data validation API that WP provides rather than the generic PHP functions. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "functions"
} |
Change Admin Bar "Visit Site" URL
I am using this code to open the admin "Visit Site" URL in a new window. How could I modify the code to also point the URL to a custom page? e.g. www.domain.com/blog
add_action( 'admin_bar_menu', 'customize_my_wp_admin_bar', 80 );
function customize_my_wp_admin_bar( $wp_admin_bar ) {
//Get a reference to the view-site node to modify.
$node = $wp_admin_bar->get_node('view-site');
//Change target
$node->meta['target'] = '_blank';
//Update Node.
$wp_admin_bar->add_node($node);
} | The admin bar is using the home_url() function which you can modify the result by using the "home_url" filter, this will change a lot of links on your admin area so looks like it's not the best solution, anyway remember to use the is_admin() conditional tag or you will affect everything on the front end too.
<
The second option is to set the href directly:
$node->href = ' | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "functions, admin"
} |
Run visual composer code in php page
I am working on a site built in visual composer/wp bakery. I do not want to work in the admin but in a php file.
How can I get code like
[vc_column_text]
<h3><a href="home">home</a></h3>
[/vc_column_text]
to parse from a a php file, rather than WP admin? | Based on Toms comment this will work:
<?php echo do_shortcode( '
[vc_column_text]
<h3><a href="home">home</a></h3>
[/vc_column_text]
' );?> | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 5,
"tags": "shortcode"
} |
How do I make my sites logo smaller?
My sites logo is far to big I have tried changing the overall image size in photoshop however it doesn't help.
http:bentleyandhudson.com | This question isn't really WordPress specific it's more an image editing or CSS question.
Firstly, your logo image size is incredibly large and there's no need for it whatsoever - you should resize it so that it's the size that you would like it actually displayed.
It looks like you're using a GoDaddy WordPress theme which is partly the problem too as it's explicitly setting the size of your image (`<img>`) element to 3067px X 986px and I've no idea at all why it would do this...
But, in order to help you, here's some CSS code that you'll need to enter in your themes CSS options or in your child themes style.css file to alter the size of the logo image:
.site-title-wrapper {
width: 480px; /* Change this to whatever width you want */
float: none; /* This stops the image being 'floated' to the left */
margin: 0 auto; /* This centers the image */
}
Hope this helps! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "logo"
} |
Adding a class to the body of an inactive site using multisite
I am using multisite and have made inactive one of the sites. I would like a way to add a class to the body tag of inactive sites so that I can in turn, use that class to add a note for admin to see from the front-end that the site is indeed inactive. Can the functions file be used to do this perhaps? | Yes, you can use the `body_class` filter. If all the sites use the same theme, you can get away with putting this in `functions.php` (in a child theme so your code doesn't get overwritten when the theme is updated), but if any sites have a different theme, you'll need to put it into a custom plugin (perhaps a MU plugin).
<?php
add_filter('body_class', 'wpse_299000_body_class');
function wpse_299000_body_class() {
// check if current subsite is inactive, deleted, archived, or spammed
$is_inactive = ms_site_check();
// value will come back either true or false
if($is_inactive == true) {
// add your desired class to <body> - this example adds .inactive
$classes[] = 'inactive';
}
// always return classes so none are taken away
return $classes;
}
?>
You can also remove classes if needed. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, multisite, css"
} |
how to set a WP Plugin's url
I am taking my first steps with developing on WP and so far I have been successfully able to play around with a custom widget that prints all necessary html to load a calendar with fullcalendar.js. So far so good. The next thing I would like is to have a url feeding the calendar with a set of data extracted from a specific post type set. Do I need to created a new widget for that functionality and how do I let know WP on what url to call my widget? ex. /my/custom/url/feed/json
thanks a lot! | This is a perfect use case for WordPress' REST API.
It probably makes sense, to create a custom endpoint, where you can in detail define what results you need. Something along the lines of
<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'kostas_calendar/v1', '/feed/', array(
'methods' => 'GET',
'callback' => 'kostas_calendar_endpoint_feed',
) );
} );
function kostas_calendar_endpoint_feed( WP_REST_Request $request ) {
// your code
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, plugin development, widgets"
} |
Function to incorporate an option in each Page
Hello (sorry for my bad english).
I have searched but not found what I want. I would like to know if there is a possibility to incorporate an option for each page. Something like in the Customize. Each page has a different wallpaper and I want to modify the opacity of each wallpaper with an option in the Page.
I don't know if I'm clear, but with the customizer I change the option for all the pages. What I want is to have an option for each page and a different variable and modify ti in the page and not in the theme customizer. The same way I change the Page attribute or the author.
Thanks you very much for your help and have a good day ! | It sounds like you need custom meta boxes. You could either create your own plugin to add them or use a plugin like Advanced Custom Fields. You would add two meta boxes to each post type where you want to be able to select these options, one to select the image, and another to set an opacity. For an overview of creating your own meta boxes - Add custom meta box on Post page
From there, you would need to output custom CSS using the selected image and opacity as the background for one of the elements on the page - perhaps `<body>` or `<main>` but it would depend on your theme. You could either create a child theme and output the `<style>` tags directly in `header.php` or you could add to your own plugin and have it output the `<style>` tags at the `wp_head()` hook.
From here I'd suggest working on adding the custom meta boxes first, and come back if you get stuck on a specific step. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, options"
} |
how to rewrite args in a custom post type from your functions.php?
I feel like this has been asked a million times, but I couldn't find anything close to the code I currently have.
function overwrite_gallery_slug( $args, $post_type ) {
if ( $post_type === 'gallery') {
$args['rewrite']['slug'] = 'team-murray';
}
return $args;
}
add_filter( 'register_post_type_args', 'overwrite_gallery_slug', 10, 2 );
I need to add `with_front` and make it `false` but in my current code I'm not sure how to do that. | The `$rewrite` parameter of `register_post_type()` accepts either a boolean or an array. We can overwrite the existing value of `$rewrite` with the array of our desired settings:
function overwrite_gallery_slug( $args, $post_type ) {
if ( $post_type === 'gallery') {
$args['rewrite'] = array (
'slug' => 'team-murray',
'with_front' => false,
);
}
return $args;
}
add_filter( 'register_post_type_args', 'overwrite_gallery_slug', 10, 2 );
Remember to flush permalinks after implementing this code. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "custom post types"
} |
WooCommerce: One term for Many Product Attributes
I am using WooCommerce Product Attributes to show mobile phones specifications.
 different link, e.g. `example.com`. I.e. when someone types `example.com` it would serve `site1.example.wordpress.com` but in browser it would display `example.com`.
I'm aware of this and this solutions. However, I do not want to install the plugin, and the solution that suggests changing TLD in wordpress seems iffy (it's a good solution, that I keep seeing everywhere on the net). However, can a CNAME be used?
And if I add `example.com` as a CNAME, can I add it just as a `ServerAlias` (apache 2.4) in my existing vhost for multisite? Or should I make separate virtual host that would reverse proxy to `site1.example.wordpress.com`? | WordPress Multisite can handle this without a plugin.
What you need to do:
_I'm assuming that your WP Multisite installation is at`example.wordpress.com` and your desired URL for the new site is `example.com`, per your question._
1. Create the site in the Network Admin section on `example.wordpress.com`.
2. Select **Edit Site** on the newly-created site.
3. Change the **Site Address (URL)** to whatever you need it to be (in this case, `example.com`.
As long as the DNS resolves correctly, and your webserver knows that `example.com` is to be served by `example.wordpress.com` (eg, your `example_wordpress_com.conf` file in Apache has a line like `ServerAlias example.com`), you should now be able to go to `example.com` in your browser and have your new site appear.
See this answer for a couple of screenshots. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, domain mapping"
} |
How to set show admin bar front to true for all users?
I just wanted to know whether it is possible to set for all users `show-admin_bar_front` meta data to true. I've tried this to put those lines in functions but with no results :
// Create the WP_User_Query object
$wp_user_query = new WP_User_Query(array('role' => 'Subscriber'));
// Get the results
$users = $wp_user_query->get_results();
// Check for results
if (!empty($users)) {
// loop trough each author
foreach ($users as $user) {
// add points meta all the user's data
update_user_meta(5, 'show_admin_bar_front', 'true');
}
} | You can use `update_user_option()` function (see codex)
Your loop looks fine to me, so probably this would work:
// Create the WP_User_Query object
$wp_user_query = new WP_User_Query(array('role' => 'Subscriber'));
// Get the results
$users = $wp_user_query->get_results();
// Check for results
if (!empty($users)) {
// loop trough each author
foreach ($users as $user)
{
// update option
update_user_option( $user->ID, 'show_admin_bar_front', 'true');
}
}
Things to pay attention to:
1. You're looping through all queried users, so in `update_user_option` the first parameter needs to be the id retrieved from current user object (not the hardcoded ID)
2. The third parameter in `update_user_option` should be of a string type apparently, so `"true"`, not `true` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "users, user meta, admin bar"
} |
Remove default WYSIWYG editor without removing custom fields editors
If I create a page by default it has a page title and full WYSIWYG editor. I have created some custom fields using the custom fields plugin which gives you the option to hide certain things. If I select the checkbox to hide the WYSIWYG editor then it removes the default one but also removes all the custom fields I created too which is no good. Is there a way to just remove the default one?
I saw some examples of code to do this but my problem with those is that they rely on hard coding the page name. If the user were to change the page name then that code would break. | WordPress has the `remove_post_type_support` function that can be used with this purpouse, you can learn more from <
Just an example borrowed from codex
/**
* Remove excerpt support from posts.
*/
function wprocs_custom_init() {
remove_post_type_support( 'post', 'excerpt' );
}
add_action( 'init', 'wpdocs_custom_init' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom field"
} |
Show only IF not Google bot
I have some code (ad banners etc.) that I would like to not show to Google. Is it possible to create a conditional statement that will disable a function or template part, if the site is requested by Google? | This isn't really a WordPress specific question. However, I recently wrote a function for this (and blocking other user agents). Perhaps you could use it, or some of it?:
function is_a_bot(){
$is_bot = false;
$user_agents = array( 'GTmetrix', 'Googlebot', 'Bingbot', 'BingPreview', 'msnbot', 'slurp', 'Ask Jeeves/Teoma', 'Baidu', 'DuckDuckBot', 'AOLBuild' );
$user_agent = $_SERVER['HTTP_USER_AGENT'];
foreach ( $user_agents as $agent ){
if ( strpos( $user_agent, $agent) ){
$is_bot = true;
}
}
return $is_bot;
}
Simply add/remove the bots that you want/don't want from the array `$user_agents` and use in the following way:
if ( ! is_a_bot() ){
// Do something if it's not a bot (eg. display ad code, template part or run your function here...)
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "php, functions, google"
} |
WordPress REST API validation
I'd like to validate the data sent to my end point.
< This post referenced the undocumented validation options. I have got 90% of what I need but now need to validate a strings length which I can't seem to figure out.
Basically I need to say the max length is X. I tried 'maxLength' but that isn't working. Has anyone done this or better yet is there any documentation on this, the post I found was quite old.
'args' => array(
'external_id' => array(
'required' => true,
'type' => 'string',
'description' => 'external id',
'maxLength' => 10
)
)
Thanks, Andy | There is no such `maxLength` option in the WP REST API.
You can pass a `validate_callback` though. Example:
<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
'args' => array(
'id' => array(
'validate_callback' => function($param, $request, $key) {
return is_numeric( $param );
}
),
),
) );
} );
Source: < | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 5,
"tags": "rest api, validation"
} |
I can't find where a hook is being defined in a plugin - Easy Digital Downloads
I've been reading the code of the plugin " _Easy Digital Downloads_ " in order to learn more about plugin development techniques. I'm getting crazy because of a hook I can't manage to find where is being defined.
add_action( 'edd_edit_user_profile', 'edd_process_profile_editor_updates' );
Located in: includes/shortcodes.php Line: 918
I know `edd_process_profile_editor_updates` is the function used to process the profile updates (duh, obvious), and `edd_edit_user_profile` is the hook location that triggers the function, but I haven't been able to find where is being defined `do_action('edd_edit_user_profile')`
Yes, I did a full search for `edd_edit_user_profile` in the whole plugin but this is the only line that mention this hook.
Thanks in advance! | in
includes/actions.php
there's
function edd_post_actions() {
$key = ! empty( $_POST['edd_action'] ) ? sanitize_key( $_POST['edd_action'] ) : false;
if ( ! empty( $key ) ) {
do_action( "edd_{$key}", $_POST );
}
}
add_action( 'init', 'edd_post_actions' );
in
templates/shortcode-profile-editor.php
there's
..input type="hidden" name="edd_action" value="edit_user_profile" ..
* * *
which, if the two are used together, would make
do_action( 'edd_edit_user_profile', $_POST );
As I said in my comment on your post - its very common in WP for actions to be dynamic, so you need to be less specific on your search, exempting the prefix, variable actions, or just remove the key and search a large `do_action` query instead. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "plugin development, hooks"
} |
Having trouble adding CSS class through menu to link
I have a menu item that is a custom link. I want to add some CSS to this particular item only, so I'm going in and adding a CSS class through the menu. Without adding the class, the HTML looks like this:
<a href="#">My Menu Text</a>
When I add the class through the Menu editor, the resulting HTML looks like this:
<a href="#">
<i class="no-hover"></i>
"My Menu Text"
</a>
So I can't use the class to reference the `<a>` element. This is contrary to all of the doc that I've read, which all suggests that you can simply put the class into the menu item through the editor and then simply reference it in CSS.
Is this perhaps a strange feature introduced by a plugin I'm using, or is there something I'm missing? | The problem is an incorrect implementation of a menu item custom class by _Virtue_ theme. Two changes are required in `themes/virtue/lib/nav.php` file. Replace line 30:
//$classes[] = $custom_class;
with:
$classes[] = $custom_class;
Replace line 45:
$icon = ! empty( $custom_class) ? '<i class="'. $custom_class . '"></i>' : '';
with:
$icon = '';
**Note:** to avoid your changes being overwritten by theme's update, create a child theme, and make your changes in it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus"
} |
custom class and size for the_post_thumbail
I want to resize a particular image on the fly with the_post_thumbnail() which I have done like so:
<?php the_post_thumbnail( array (475, 317 ) ); ?>
This works in resizing the image to the specified size but I also want to add a class to this. If I try add a class then the size dimensions are still correct but it doesn't apply the class?
<?php the_post_thumbnail( array (475, 317, 'class' => 'border--round' ) ); ?> | Try To Use it Like This :
<?php the_post_thumbnail( array (475, 317), [ 'class' => 'border--round' ] ); ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "post thumbnails"
} |
How can I add a google play badge to my header and footer?
How I can add images or edit html for the header and footers within wordpress.
I am looking in the header and footer sections under both "Theme Panel" and "Appearance" but can't figure out how to add html anywhere for adding the Google Play badge. | First of all, you can modify your header and footer from either using FTP client else from WP admin dashboard. if you are not familiar with FTP the please follow following steps.
1.Go to WP admin dashboard.
2.Under the Appearance menu, there is an option for edit theme. name it Edit.
3.In right side section list of files under the theme, ll be list.
4.Click on header.php and footer.php for edit header and footer accordingly.
please refer this for Google badge and paste the code in header or footer as per your needs.
I hope its useful and solve your issue. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "html, headers, custom header, logo, google"
} |
One Wordpress Installation for 2 Domains
I've completed my wordpress page with a few subpages and one domain xyz.de. So I've a couple of pages, let's assume:
> xyz.de
>
> xyz.de/page1
>
> xyz.de/specific_topic
Right now, my second domain **specific_topic.de** redirects to **xyz.de/specific_topic**. I'm wondering whether it would be possible to keep the domain **specific_topic.de** in the addressbar of the browser, so when entering **specific_topic.de** , I want to see exactly the page which is right now shown when visiting **xyz.de/specific_topic**. There wouldn't be any subpages for **specific_topic.de** ; it would JUST ONLY SHOW that single page. All the other menu items would again link to the original domain **xyz.de**.
So I want to get rid of the hard redirect, but instead keep the domain. This domain wouldn't have any further subpages, it's really just this domain for this one page named "specific_topic".
Is this possible?
Thanks | This free plugin seems to be exactly for what you want, and is up to date: <
You will need to point the DNS A record of the second domain to the same IP as the main one. There are more instructions in the FAQ section of the page I linked.
This is NOT for a multisite. It is for a single WordPress installation with multiple domains. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "customization, multisite, domain, domain mapping"
} |
Can't unregister parent theme's CPT from my child theme
Here's how I create my CPT in my parent theme's `functions.php`:
function my_custom_post_job() {
...
register_post_type('job', $args);
}
add_action('init', 'my_custom_post_job');
I'm trying to unregister this in my child theme's `functions.php` like so:
add_action('init', 'remove_cpt');
function remove_cpt() {
remove_action('init', 'my_custom_post_job');
}
What am I doing wrong? | you cannot remove a hook when you are in the same hook with the same priority.
a solution is to hook the action with a lower priority
add_action('init', 'remove_cpt', 5); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom post types, hooks, actions"
} |
Use wp_set_post_terms() instead of wp_insert_post()
Since I use cron jobs for automation I ran into some problems with the taxonomy. Before I used the cron job, the following code used to work:
$custom_tax = array(
"project-type" => array(
"2"
)
);
$mypost = array(
'post_title' => $basicdata["Model"],
'post_type' => "portfolio",
'post_status' => "publish",
'tax_input' => $custom_tax,
'comment_status' => "closed"
);
$pid = wp_insert_post($mypost);
I know when I use cron jobs, can't use `tax_input` in `wp_insert_post()` anymore, but it should work with `wp_set_post_terms()`. I didn't really understand how to achieve the same thing with `wp_set_post_terms()` by reading the WordPress codex. Would be nice if anyone could help me... | After some hours of further searching i found the solution:
`wp_set_post_terms($pid, array("2"), "project-type");` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin development, taxonomy, wp insert post, wp cron"
} |
need to insert php code in path Get Template Part
<?php
get_template_part('template/sliders/<?php echo $template1; ?>', 'home');
?>
this `<?php echo $template1; ?>` not work in path string any another way to make it work im use wordpress | Looks like a syntax error, this should work for you:
get_template_part('template/sliders/' . $template1, 'home'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "php"
} |
Custom Template 404 for specific custom post type
Some solution to create a custom template for (page 404) for specific custom post type. | This is going to track only `post_type` query var, but you also can add checks for `query_vars` of all your post_types or only ones you would like to get a custom 404 page for.
add_filter( '404_template_hierarchy', function( $templates ) {
global $wp_query;
if ( '' !== $wp_query->get('post_type') ) {
array_unshift( $templates,
sprintf( '%s-404.php', $wp_query->get('post_type') ) );
}
return $templates;
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, pages, templates, page template"
} |
AJAX call using admin-ajax URL is returning 400 bad request
I am attempting to create an AJAX call to pass custom taxonomy into my `WP_Query` but I am getting `400 (Bad Request)`. I believe my `data` array is built correctly so I am not sure what's causing it. Does anything look off here? Is there a way for me to get a more detailed error of why it is returning error 400?
$.ajax({
type:'POST',
url:ajaxUrl,
data: {
taxonomy: 'products',
slug: 'shirts'
},
beforeSend:function(xhr){
},
success:function(data){
$('#response').html(data); // insert data
}
});
I console logged `ajaxUrl` and I am getting the correct path to `admin-ajax.php` so I know that's not the issue. I think it has to have something to do with `data`. | you forgot the "action" key in your data array. With that key you define which function is called from your plugin or function.php File. For more information see the Wordpress documentation - AJAX in Plugins | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 1,
"tags": "ajax"
} |
How to redirect if is post edit or publish page?
I want to redirect if page is edit.php or post-new.php and i write this function. But it doesn't work. It must work only 'post' post type.
add_filter('admin_menu', 'redirect');
function redirect() {
require_once(ABSPATH . 'wp-admin/includes/screen.php');
$screen = get_current_screen();
if( $screen->post_type == 'post' && is_edit_page() ) {
wp_redirect('
}
} | For what you want to achieve, using the `id` instead of `post-type` should do the job. Try this:
add_action('admin_menu', 'custom_redirect_function');
function custom_redirect_function() {
$screen = get_current_screen();
if ( $screen->id == "edit-post" ) {
wp_redirect( site_url() );
exit();
}
}
References:
* get_current_screen
* wp_redirect | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, redirect"
} |
Use content custom filter for all shortcodes
I have tried many hooks trying to manipulate the processed content coming from of all the shortcodes, customize it, and output the final result on the pages
I have no idea what shortcodes are, so I would like to execute a filter or something that works on every shortcode
How this can be done? | > so I would like to execute a filter or something that works on every shortcode
Looks like you're after do_shortcode_tag. It "Filters the output created by a shortcode callback.".
Aurovrata Venet gives a demo usage similar to:
add_filter( 'do_shortcode_tag',function ($output, $tag, $attr){
//make sure it is the right shortcode
if('aShortcode' != $tag){
return $output;
}
//you can even check for specific attributes
if(!isset($attr['id'])){
return $output;
}
$output .= '.. do somthing ..';
return $output;
},10,3); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "filters, shortcode"
} |
Custom excerpt length filter doesn't work
So I'm trying to change the standard post excerpt length.
Every single blog post on the web tells me to do it with a filter like this:
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
function custom_excerpt_length( $length ) {
return 15; // Length of the excerpt in number of words
}
Problem is there is no change to the excerpt length. All the text is being output and not just 15 words. I have no idea why this doesn't work when it's supposed to be the solution.
I'm using `<?php the_excerpt(); ?>` in the post loop on home.php, category.php and tag.php to output the excerpt. | For anyone wondering, as custom excerpts don't get trimmed by the `excerpt_length` filter hook, try adding this filter:
function trim_custom_excerpt($excerpt) {
if (has_excerpt()) {
$excerpt = wp_trim_words(get_the_excerpt(), apply_filters("excerpt_length", 55));
}
return $excerpt;
}
add_filter("the_excerpt", "trim_custom_excerpt", 999); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "posts, filters, excerpt, blog"
} |
How to amend time format of comments, using child-theme?
How to amend (override) the time format of the comments (of the posts and pages), not touching the wordpress initial installation? I use a child theme and if it is possible in any way to do it from the child theme to prevent my changes been overwritten by the next WP update. I would prefer to use add_filter()
I am trying to use:
// define the get_comment_time callback
function filter_get_comment_time( $date, $d, $gmt, $translate, $comment ) {
$d = "g:i:s";
return $d;
};
// add the filter
add_filter( 'get_comment_time', 'filter_get_comment_time', 10, 5);
But it returns only the string "g:i:s".
WP 4.9.4 | You have to return the formatted date string, the following will work:
// define the get_comment_time callback
function filter_get_comment_time( $date, $d, $gmt, $translate, $comment ) {
$d = "g:i:s";
$date = mysql2date($d, $date, $translate);
return $date;
};
// add the filter
add_filter( 'get_comment_time', 'filter_get_comment_time', 10, 5); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "comments, date time, formatting"
} |
.PO file is found but I don't see translations: how to debug the problem?
I have installed the Stack theme, and I want to make Danish translations. I have downloaded the `Stack.pot` file, made the modifications I need, and uploaded them to:
/wp-content/themes/stack/languages/stack-da_DK.po
I installed a `PO/MO Editor` plugin, and here I can see my translation:
?
And is there something obvious I am missing? | It's the .MO file compiled saving the .PO file which is used by WordPress. Without .MO no traduction will be available. You can use another plugin to translate your theme : Loco for example ; or a Windows software : Poedit, which will create a .MO file when you'll save your .PO file with your translation. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, theme options, localization, debug, testing"
} |
Get Post Types in admin
I have this code in a page of my custom theme:
$args = array(
'public' => true,
'_builtin' => false
);
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$post_types = get_post_types( $args, $output, $operator );
This code if loaded in a wp-admin page.
The problem is that I want to load all types of post, I tried changing the built in but it does not work. I want to get the default post of wordpress and the custom post type as woocomerce products. Does someone help me? Thank you! | Custom post types can only be registered on the `init` hook. So if you're trying to get the post types before the `init` hook, you will only ever get the built-in ones.
To get custom post types, you need to use a hook after `init`, or later on `init` than the custom post types were registered.
function wpse_func() {
$args = array(
'public' => true,
'_builtin' => false,
];
$post_types = get_post_types( $args );
}
add_action( 'init', 'wpse_func', PHP_INT_MAX );
//* Or
add_action( 'wp_loaded', 'wpse_func' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types"
} |
Missing argument 2 for a custom function widgets_init
I am using a theme_mod string from customizer to generate custom sidebar, but it is called from another function. This is my code:
function call_sidebar_function() {
if ( get_theme_mod( 'enable_sidebar' ) ) {
$name = "mySidebarName";
$numberOfSidebars = get_theme_mod('number_of_sidebars');
generate_sidebars($name, $numberOfSidebars);
}
}
function generate_sidebars($name, $numberOfSidebars) {
$i = 1;
foreach ($numberOfSidebars as $sidebar) {
register_sidebar(
array(
'name' => $name.$i,
'id' => $name.$i,
)
);
$i++;
}
}
add_action( 'widgets_init', 'generate_sidebars' ); | `widgets_init` isn't a function, it's an action hook. The callback you specify for that hook is `generate_sidebars` which requires two parameters, but the `widgets_init` hook doesn't pass any parameters to its callbacks.
I think what you're trying to do is this:
add_action( 'widgets_init', 'call_sidebar_function' );
Which will call the `call_sidebar_function()` function which will then call the `generate_sidebars()` function with the correct parameters. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "functions, widgets, sidebar"
} |
Possible to swap in a placeholder image globally for the_post_thumbnail_url if one doesn't exist?
I am working on a new theme for a site, but the majority of the posts don't have a featured image set. Throughout the new theme I am pulling in featured images using `the_post_thumbnail_url`. I am wondering if there is a function I can add to `functions.php` to override this url, globally, with a url to a placeholder image if there is no featured image assigned to the post. | If you know the URL of the placeholder image, you sure can do it.
`get_the_post_thumbnail_url()` function calls the `wp_get_attachment_image_url()` function which in turns calls the `wp_get_attachment_image_src()` function to get the source of the post thumbnail. `wp_get_attachment_url()` returns the result from `wp_get_attachment_image_src` filter. So we can use that filter to modify the result if there is no image and the size is 'post-thumbnail'.
namespace StackExchange\WordPress;
function image_src( $image, $attachment_id, $size, $icon ) {
$default = [
'
];
return ( false === $image && 'post-thumbnail' === $size ) ? $default : $image;
}
\add_filter( 'wp_get_attachment_image_src', __NAMESPACE__ . '\image_src', 10, 4 ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "post thumbnails"
} |
Are theme .php files stored in the database?
I'm asking about the relation of WP .php files (themes etc.) with the database. Is (part of) the content of these files stored in any way on the database?
**Context:** I'm trying to migrate from http to https. All the relevant guides, talk exclusively about a "Search and Replace" of the < with the < in the database. Nowhere did I find anyone mention that you should also do a search and replace in the theme or other .php files of WP; though often there are links/references to the domain in these files. | No, a theme's `.php` files are not stored in the database. Themes _should not_ be hardcoding URLs in their files. However, it's totally possible for this to happen, particularly with a custom theme or plugins whose developer did not follow best practices.
I'd suggest using a search utility such as grep (grepwin is nice for Windows) to look within your files just to be sure if your domain appears or not.
Also, when doing a search and replace on the DB, remember to use a utility that is able to handle serialized arrays, since a simple string replacement will damage data. WP CLI's search-replace is one option. WP DB Migrate is really nice too.
Be sure to make a backup of everything before you make changes. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "themes, database, https"
} |
Get old values for post before saving new ones
I'm using the `save_post` hook to do some additional logic after a post has been saved.
However I need to find a way of getting the old values of the post, specifically in my case the slug/handle aka `post_name`.
Tried using the `wp_insert_post_data` filter to catch the post and add the old slug as an additional field pre save but that doesn't seem to work.
TL;DR want to achieve something like this:
public function post_sync( $post_id, $post, $update ) {
$post_new_handle = $post->post_name;
$post_old_handle = $post->post_old_name;
if($post_new_handle !== $post_old_handle) {
//additional logic
}
//additional logic
}
Any way of achieving this? Thanks. | The `post_updated` action gives you both old and new values as arguments before the new values are saved:
do_action( 'post_updated', $post_ID, $post_after, $post_before ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 6,
"tags": "posts, filters, hooks"
} |
$content = $post->post_content; with formating
I'm trying to get formating but with no luck. My code looks like this
global $post;
$content = $post->post_content;
And to output here
<div class="tribe-events-single-event-description tribe-events-content">'.$content.'</div>
Please if anyone have suggestions let me know. | If i get your question correct, you want the post_content formatted like the content put out by the_content, right?
Change your upper code like this:
global $post;
$content = apply_filters('the_content',$post->post_content);
This does everything to your content that would be performed when outputting it by the_content();
If you only want the p and b tags, you can use `wpautop($post->post_content)` instead. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "the content, formatting, post content"
} |
rest_post_query on multiple post types?
how do you get the rest_post_query filter to work across multiple post types? I'd like to modify the orderby for all post types but at the moment i have to specify "post" in the filter name, which means it doesn't work on the custom post types i've created?
add_filter("rest_post_query", function ($args) {
$args["orderby"] = "menu_order";
$args["order"] = "ASC";
return $args;
}, 10, 2); | Define the callback as a named function and hook it separately for each post type.
function wpse_299908_order_rest_query( $args ) {
$args['orderby'] = 'menu_order';
$args['order'] = 'ASC';
return $args;
}
add_filter( 'rest_post_query', 'wpse_299908_order_rest_query' );
add_filter( 'rest_page_query', 'wpse_299908_order_rest_query' );
There's no filter that automatically applies to all endpoints, likely for the same reason that you can't query multiple post types at once to begin with. As discussed during development of the API:
> Because each custom post type is modeled differently, it's not possible to fetch them from the same endpoint in v2. Conceptually, it's like fetching users and posts from the same end point — it doesn't make much sense. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "rest api"
} |
Remove Cookies From Wordpress Core
I'm developing a custom theme and i understand Wordpress does come with some built-in cookies? With the new GDPR regulations coming I would like to remove these - I believe they are only there log-in / username purposes. The site is for my own company and it's just a brochure site with no data being gathered at all. I don't mind having to type my details in whenever I login.
How do i remove Wordpress cookies from Wordpress itself?
Many thanks, | You won't be able to log in to WordPress _at all_ without cookies. It's not just about remembering if you're logged in the next day, it's about remembering if you're logged in _every time you go to a different page in the admin_.
 are for logging in and for commenting. You only need the login ones to be able to use the admin, and the comment ones are only relevant if you have comments enabled.
So if your regular users aren't doing either of those things then you and your site are not using cookies to identify users and have nothing you need to gain consent for.
The situation is obviously different if you're using analytics, ads, plugins, or anything else that uses cookies, but then that doesn't have anything to do with WordPress itself. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "theme development, cookies"
} |
account page development
I am trying to make a account page that user can edit their password and profile in the front-end without plugin. I can't find any good tutorial in google. Are there some good tutorial about this? and can you give me some advice? thank you. | There are many articles already available which shows how to build profile and change password screens without using any plugin.
This can help you with the purpose: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "account"
} |
How to change WooCommece variation data programmtically
While editing a variable product, you can go to the "variations" tab and edit the data for each variation (such as the SKU). I want to edit this data programmatically. The WC_Product_Variation class does not allow to set the value for those fields, just to get them. Is there another way to set those fields programmatically? | have you try withup date_post_meta
<?php update_post_meta( $post_id, $meta_key, $meta_value, $prev_value ); ?>
for example
update_post_meta($variation_post_id, '_price', $variation['price']);
update_post_meta($variation_post_id, '_regular_price',$variation['price']); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, php, woocommerce offtopic"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.