INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Front-end only $_POST and $_POST requests handling in WordPress plugin
I just created a WordPress plugin with a custom template that handles a $_GET request before the HTML code. Wordpress team is asking me to put this code inside a function.
I understand that for admin panel forms the way is to use
admin-post.php
or
add_action( 'admin_post_****', '****' );
But how do you handle a front-end form post (not that of admin panel). In what kind of a function should I put my template's $_GET or $_POST handling code. Because wordpress.org is not accepting my plugin without these request handles to be inside a function. | you can use something like this:
add_action( 'admin_post_add_foobar', 'prefix_admin_add_foobar' );
//this next action version allows users not logged in to submit requests
//if you want to have both logged in and not logged in users submitting, you have to add both actions!
add_action( 'admin_post_nopriv_add_foobar', 'prefix_admin_add_foobar' );
function prefix_admin_add_foobar() {
status_header(200);
die("Server received '{$_REQUEST['data']}' from your browser.");
//request handlers should die() when they complete their task
}
for more information you can check this page ) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, request filter"
} |
parse content from wikipedia article replacing search term with the title of article
I have a piece of php code, which shows wikipedia article introduction. It works fine, but I need to replace search term with the title of article.
<?php
function getDescription($keyword){
$url='
$xml=simplexml_load_file($url);
return $xml->Result->Description;
}
echo getDescription('*some term*');
?>
My problem is to replace `getDescription ('*some term*');` search word with title of article.
I`m trying with:
echo getDescription('<?php single_post_title(); ?>');
but it returns nothing.
My code located on other plugin (advanced ads). Any suggestions?
Thanks | You can't and shouldn't echo something into a function's arguments. The `single_post_title()` function will echo the title by default. You should either set the second parameter to false, or use another function:
echo getDescription( single_post_title( '', false ) );
WordPress also offers the `get_the_title()` function that returns the single post's title which you can use here.
So, your code should be:
echo getDescription( get_the_title() ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development"
} |
wordpress with 1.5 million posts
I wanted to transform my dictionaries into a WordPress website that has different dictionaries for different views. As you can imagine by now, the posts will mostly have just 2 words and a short sentence of the definition.
so The post body will mostly be this big:
home / casa
a place when people love
I'm not sure how much space that post would occupy considering it will be linked to 1 category (no tags nothing else) and have an explanatory title like `casa translation`
The text files in total consist in about 100MB of space I'm guessing as WordPress posts they would occupy double that. So I have 1Gb of ram. Will this be enough according to you WP experts out there?
Any possible fine tuning/customization I could make?
Like fcgicache or some mysql cache because I'm thinking WP super cache would not be a good option for so many files.
Thank you! | 1 GB on virtual private server (VPS) should be enough, if you don't have a high traffic.
WP Cache could cause problems when number of posts is more than 30,000 due to limitations on file descriptors.
Main rules of tuning nginx, php and MySQL are the same as for high traffic site. You can read relevant article in my blog. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "optimization"
} |
Slow Search Queries - How to exclude pages, media, excerpt, authors, private posts?
So I have this from _Query Monitor_ :
AND (((zp_posts.post_title LIKE '%mercedes%')
OR (zp_posts.post_excerpt LIKE '%mercedes%')
OR (zp_posts.post_content LIKE '%mercedes%')))
AND zp_posts.post_type IN ('post', 'page', 'attachment')
AND (zp_posts.post_status = 'publish'
OR zp_posts.post_author = 1
AND zp_posts.post_status = 'private')
ORDER BY zp_posts.post_title LIKE '%mercedes%' DESC, zp_posts.post_date DESC
I would like the searches queries to target only post_title and post_content, exclude all others parts. Any idea in achieving that? | You should be able to use `pre_get_posts` to change the query. I'd suggest creating a custom plugin, so that if you ever change your theme your modifications will still apply.
To get you started, here's how you can set the post types being searched:
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', array( 'post' ) );
}
}
}
add_action('pre_get_posts','search_filter');
You would continue to add `$query->set` statements inside the conditionals to further customize what fields to search.
One other option would be to write a completely custom query and call that from your search rather than using WP's built-in query. You might want to benchmark that solution to see whether it is any faster than the `pre_get_posts` way. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "query, search"
} |
Can I use register_settings and unregister_setting once the settings page has loaded?
I want to add few settings fields dynamically on settings page depending on user action. I am planning to register these new fields dynamically once user asks for it and show the corresponding HTML using jQuery. Is it possible to register settings once you are already on settings page? Also, is there a better way to do this? | Better to avoid such a thing. The settings API has two "faces", one the UI, and the other is handling the form submission. The form submission is handled on a different URL than the UI (`/wp-admin/options.php`) and therefor your "user action" depended code will not run and the handling of storing the setting in the DB might fail.
You need to register properly all fields, and then you can use CSS or JS to show/hide the relevant UI. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, options, settings api"
} |
Override plugin option by with a custom theme
I'm creating a custom theme and using one of video embedding plugins from the market. There are plenty of options and among them "don't load css style", is there a way how to make it always checked when my theme is active? Author hasn't provided any define value to fix it.
it's stored in option: `fve_disable_css`
I have tried to `update_option();` on init and as well tried a filter `pre_option_fve_disable_css` but no success, any ideas?
Thanks a lot | Plugin can read options on init event or just in code (during loading). All plugins are loaded before theme load. So, using init action can be too late.
Filter `pre_option_fve_disable_css` doesn't change value of the option. Instead, you have to use `option_fve_disable_css` filter. But again, it can be also too late.
You should check the handle name in wp_enqueue_script function in plugin code, which enqueues relevant css and deregister this handle in your functions.php during wp_enqueue_script event. This is the right time for such an action. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development, options"
} |
Redefine REST API variables
I'm having quite a few problems with my WP settings. The main issue is that I need to have WP installed at //domain1.xxx/ and viewed at //domain2.xxx. It's not enough to change wp_home and wp_site_url to achieve this. Since I want to remove all trace of domain1 when viewing the site at domain2 I use relative paths (courtesy of a plugin called "Remove HTTP"). The problem that remains is that some plugins still use absolute paths. One of them is Contact Form 7 which use the WP REST API. My question is: Can I redefine the REST variables so that I remove domain1 and replace it with preferable "/" or if that fails use domain2. | This solved my problem:
if ( $_SERVER['HTTP_X_FORWARDED_HOST'] ) {
$_SERVER['SERVER_NAME'] = $_SERVER['HTTP_X_FORWARDED_HOST'];
}
$_SERVER['HTTP_HOST'] = $_SERVER['SERVER_NAME'];
define('WP_HOME',' $_SERVER['SERVER_NAME']);
define('WP_SITEURL',' $_SERVER['SERVER_NAME']);
I also needed to change my home and siteurl value in the database to "/".
This only applies if you use a load balancer that sets forward headers. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "rest api, proxy"
} |
How to Prevent User From Submitting Property Or View His Posted Properties Before Login in wordpress?
Hello I Want Real Estate Website to develop like 99acres.com in wordpress.Now I Want User To Compulsory Login Before Posting /submitting property to site or to view his posted properties he must be logged in.Is There Any wordpress Plugin That Provides such functionality? | WordPress has function to check whether user is logged in or not
is_user_logged_in(){
/**Your code goes here**/
}
wrap your code inside this to allow only logged in users the access | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Page inside custom post type (url rewrite?)
I am trying to create a page that I can use inside of a custom post type.
I have a CPT named forums, so the url is: example.com/forums
I would like to have a page called new-topic with the url: example.com/forums/new-topic
I have been looking at parent/child relationships and url rewrites but I am completely lost. | Thanks to **WebElaine** for pointing out the obvious solution!
Just created a post in the custom post type and gave it a unique template, thus achieving the desired url. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, url rewriting, site url"
} |
Theme-based character encoding issue
I am getting a Swiss Standard German, which looks like the letter "B", that replaces "ss" in my copy.
When I test with plugins enabled/disabled using the 2017 theme the issue goes away. When I enable Bones theme, with plugins enabled/disabled, I get the strange character encoding.
Copy is not pasted from Word and is generated via the WP text editor.
I've verified proper collation in my database.
An example can be found in the first paragraph, looking for the word "express" or "regardless": < | The issue resides within the CSS. I found the style block below baked in to the base stylesheet. Font-feature-settings, "gives you control over advanced typographic features in OpenType fonts." "liga" refers to ligatures and dlig refers to discretionary ligatures. Both of which are included in OpenType font sets.
<
<
p {
-webkit-font-feature-settings: "liga", "dlig";
-moz-font-feature-settings: "liga=1, dlig=1";
-ms-font-feature-settings: "liga", "dlig";
-o-font-feature-settings: "liga", "dlig";
font-feature-settings: "liga", "dlig";
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, encoding"
} |
wpdb::prepare() isn't working
Here's my code:
global $wpdb;
$table_name = $wpdb->prefix . 'product_codes';
// Check if codes exist
$query = $wpdb->prepare( "SELECT * FROM %s", $table_name );
$existing_data = $wpdb->get_results( $query );
// Returns empty array despite data existing
print '<pre>';
print_r( $existing_data );
print '</pre>';
If I enter the table name literally, it works. If I print out the table name variable, it shows the correct string. But for some reason when I use the code above, I get an empty array - zero results. | The issue is that in My/SQL table names are not strings. So `'wp_product_codes'` is being interpreted as a string instead of as an actual table. This is why you usually don't see tables passed into `wpdb::prepare()` \- you should know the table names as they won't change where `wpdb::prepare()` is meant for data that you may not know / can't be trusted and needs to be sanitized. So let's modify the query:
$existing_data = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}product_codes" );
printf( '<pre>%1$s</pre>', print_r( $existing_data, 1 ) );
die(); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "query, wpdb"
} |
URL problem in my site
Recently I publish my site. I moved my site form localhost to server. I change all config file but url site is redirecting for ohter url. The site only show the nav-bar and in the content part show 404 error. The redirecet is < to < | Use the duplicator plugin. It basically make a snapshot and an Installer.php file. When moving the archive snapshot zip and php file to your new server, you navigate to < It's like a setup process that asks you for your new database (you can point it to an empty database) and what the new URL should be. It will update your URL all across the site to the new URL.
Once I found this plugin I have never used anything else.
Plugin link: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "server, site url, configuration"
} |
How to get all users by user_login as a json_encode array?
How to get all users by user_login as a json_encode array? Like this:
["john","mena","mark"] | Try this one:
function prefix_get_users(){
$args=array(
'blog_id' => $GLOBALS['blog_id']
);
$all_users=get_users($args);
$arr=array();
foreach ($all_users as $val) {
$arr[]=$val->data->user_nicename;
}
die(json_encode( $arr ));
}
Reference: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions"
} |
Registering a script dilemma→ wp_register_script
wp_register_script( $handle, $src, $deps, $ver, $in_footer );
If `$ver` is not required then should we leave that space blank? or completely remove the commas?
Example →
wp_register_script( 'scroll', get_template_directory_uri() . '/js/infinite-scroll.pkgd.min.js', array( 'jquery' ), '1.1', true );
There is no dependency on JQuery. this needs to be removed entirely:
, array( 'jquery' ),
or leave it blank like this →
wp_register_script( 'scroll', get_template_directory_uri() . '/js/infinite-scroll.pkgd.min.js', , '1.1', true ); | Simply pass in `null` or the empty equivalent.
For example, if you don't depend on anything, say so. It's expecting an array of the dependencies, so pass an empty array `array()`
Or pass in `null` | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "wp register script"
} |
Give access only for a period of time
I'm new to WordPress and I need to sell a digital, non-downloadable product. I found WooCommerce plugin, I think it's useful. The problem is that I want to give access for **a period of time**.
This is a concrete example: Lets say the site is selling videos. There are three types of subscriptions: 1 month, 6 months and 1 year.
Depending on the choice of the user, the site choose the access period **from the purchase date**.
If it's possible free solutions are better.
Thank you. | A membership plugin would be better for that, you can select content for each membership types as well. Try out < it might solve your issue | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "plugins"
} |
Extract links inside embed tags in WordPress
I am using the default WordPress embed to embed a couple of videos in the content.
I want to extract the video link from `[embed] can anyone help with the regex? | No need to use regex. WordPress has a handy function to strip shortcodes from a string.
Use `strip_shortcodes( $content )`.
So in your case,
$content = "[embed]
$your_clean _url = strip_shortcodes( $content );
echo $your_clean_url; // should output
**EDIT**
Here's a function (tested) that will remove your _"unwanted"_ shortcode, and any other one.
function remove_unwanted_shortcode($shortcode, $content) {
$start = "[" . $shortcode . "]";
$stop = "[/" . $shortcode . "]";
$cleanFirst = str_ireplace($start, '', $content);
$cleanSecond = str_ireplace($stop, '', $cleanFirst);
return $cleanSecond;
}
And you would use it like so:
$content = "[embed]
$short = "embed";
echo remove_unwanted_shortcode($shortcode, $content); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "the content, youtube"
} |
Can't get_users info by using json_encode
Here's the code that i used:
function get_users(){
$all_users = get_users();
$arr=array();
foreach ($all_users as $val) {
$arr[]=$val->data->user_nicename;
}
$resp = array (
'data' => json_encode($arr)
);
wp_send_json($resp);
}
this code is working like this:
["john","mark","mena"]
I want the code to work like this:
[{value: "user_nicename", label: "display_name",icon: "user_avatar"}] | Try this code
function get_users(){
$all_users = get_users();
$arr=array();
foreach ($all_users as $val) {
$arr[]=array( 'value'=> $val->data->user_nicename, 'label'=> $val->data->display_name, 'icon' => get_avatar_url($val->ID));
}
wp_send_json($arr);
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, users, html, json"
} |
Dequeue scripts and styles only for specific custom post type
I am trying to dequeue some scripts and styles only for specific custom post type. But when I add this snippet of code the actions are applied for the entire website as the styles and the scripts are dequeued for all other post types and pages where I need them. Thanks in advance!
add_action( 'wp_enqueue_scripts', 'dequeue_my_scripts', 999 );
function dequeue_my_scripts()
{
if ( 'guide' == get_post_type() )
wp_dequeue_script( 'dw_focus' );
wp_dequeue_script( 'comment-reply' );
wp_dequeue_style( 'style' );
wp_dequeue_style( 'responsive' );
} | You are missing the `{...}` around the calls to `wp_dequeue_script`. That means only the first one is associated with the `if` statement, and the rest are being executed for every case.
Update your code to the following:
add_action( 'wp_enqueue_scripts', 'dequeue_my_scripts', 999 );
function dequeue_my_scripts()
{
if ( 'guide' == get_post_type() )
{
wp_dequeue_script( 'dw_focus' );
wp_dequeue_script( 'comment-reply' );
wp_dequeue_style( 'style' );
wp_dequeue_style( 'responsive' );
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, functions"
} |
Link won't show using the_permalink();
Inside my loop, I'm trying to have a link show and it won't I'm not sure why
Here is the code:
<?php the_title('<h2 class="wow"><a href="<?php the_permalink(); ?>"', '</a></h2>'); ?>
I understand this is maybe because of the `''` quotations instead of `""`, but how would I achieve this general thing with just PHP and not by wrapping `the_title();` in an a tag. | because `the_title()` expects a string for the `$before` and `$after` args, you need to use the string version of the permalink, in a string concatenation;
`<?php the_title('<h2 class="wow"><a href="'.get_permalink().'">', '</a></h2>'); ?>`
you also had a missing `>`.
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, loop, permalinks"
} |
get users search not working with array
Here's my code:
function prefix_get_users(){
$args=array(
'blog_id' => $GLOBALS['blog_id'],
'search' => 'mark'
);
$all_users=get_users($args);
$arr=array();
foreach ($all_users as $val) {
$arr[]=$val->data->user_login;
}
$resp = array (
'success' => true,
'data' => json_encode($arr)
);
wp_send_json($resp);
}
The code is working by getting all the user successfully but when to try to use search it's not working and give me empty array by ajax (data[]) | `get_users` looks for an exact match for the value in `search` in the email _address_ , _URL_ , _ID_ , _username_ or _display_name_ fields... it doesn't look in the _first name_ field.
As you can't search the first name directly, you could instead look for people with a username or display name that _starts with_ it by using the wildcard `*` in the search string, e.g.:
$args=array(
'blog_id' => $GLOBALS['blog_id'],
'search' => 'mark*' /* Note the * wildcard to match anything starting with "mark" */
);
$all_users=get_users($args);
[...] | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, array"
} |
WP Custom Fields Metabox Disappears - ACF plugin issue
The WP custom fields metabox on all posts (including CPTs) disappear, and the checkbox in a post's Screen Options is also gone. This only happens when Advanced Custom Fields is activated. None of my ACF field groups hide the custom fields metabox, nor does deactivating all of my field groups solve the problem. How do I get the custom fields metabox to display on my posts? | ACF 5.6+ intentionally removes the custom fields metabox to improve performance when loading posts. To display the metabox, add this to `functions.php` in your theme:
add_filter( 'acf/settings/remove_wp_meta_box', '__return_false' );
In addition to the above code, make sure that the custom fields metabox is enabled in Screen Options at the top of a post, and that an individual ACF field group is not disabling the custom fields functionality in its settings.
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom field, metabox, advanced custom fields, screen options"
} |
Query Posts multiple conditions
I have a theme that uses the following code
$user_bids = query_posts( array(
'post_status' => array('publish', 'accept', 'unaccept'),
'post_type' => BID,
'author' => $current_user->ID,
)
);
I altered the posts so that they contain post meta "duplicated" that is either equal to 1 or 0
So I'm trying to figure out how to make a query that brings up all posts unless:
Post meta "duplicated" is equal to 1.
but I also need an additional condition:
If that post has status of "accept" include that post anyway even if post meta "duplicated" is equal to 1 | Try to use WP_Query as stated in this answer When should you use WP_Query vs query_posts() vs get_posts()?.
$user_bids = array(
'post_type' => 'post',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'duplicated',
'value' => '0',
'type' => 'numeric',
'compare' => '='
),
array(
'key' => 'accept',
'value' => '1',
'type' => 'numeric',
'compare' => '='
)
)
);
$query = new WP_Query( $user_bids ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, wp query"
} |
Does delete_post_thumbnail() actually delete the image?
When running delete_post_thumbnail(), does it **delete** the image? | No it certainly doesn't. It is simply a case of poor choice of naming. The function should have been named **unset** _post_thumbnail(), particularly when we already have set_post_thumbnail().
Today's WordPress annoyance. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post thumbnails"
} |
If custom taxonomy exist on post?
I have custom taxonomy called ‘filter’ and if the post has the ‘filter’ ‘reel’ I want to use this loop else use another.
$work_tax = wp_get_post_terms( $post->ID, 'filter' );
if (array_key_exists('reel', $work_tax)) {
get_template_part( 'loop', 'work_feed_reel' );
} else {
get_template_part( 'loop', 'work_feed' );
}
How should I write that if statement? | You can use `has_term()` to check if a post is in a specific term.
if ( has_term( 'reel', 'filter', $post->ID ) ) {
get_template_part( 'loop', 'work_feed_reel' );
} else {
get_template_part( 'loop', 'work_feed' );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy, taxonomy, array"
} |
Will php documentation conflict with wordpress documentation?
Hi I have a php script that makes liberal use of
> `/* */`
>
> `//`
my question is will that conflict with wordpress since the wordpress engine often reads variables inside those things?
The reason I ask is that to make a custom template, you just modify some text inside the documentation in the first part of the script
/** * Template Name: Full Width Page * * @package WordPress * @subpackage Twenty_Fourteen * @since Twenty Fourteen 1.0 */
I worry my documentation inside my script could cause wordpress to do unexpected actions or worse create a security vulnerability | I believe the practice of including additional data within PHP code comments is typically called _annotations_.
WordPress core makes no use of annotations technique for any code runtime tasks and doesn't have an API for such purpose.
In number of context it _will_ read file headers to extract meta data, such as main plugin files and some theme templates. As long as you follow documentation and include necessary elements for those I doubt you are going to have any trouble with them. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "documentation"
} |
Filter yoast canonical add_action priority
I'm trying to look around over Google of how to hook the `add_action` and change the priority of Yoast Canonical,
from: 20
`add_action( 'wpseo_head', array( $this, 'canonical' ), 20 );`
to: 55
`add_action( 'wpseo_head', array( $this, 'canonical' ), 55 );`
This affect the position from the frontend head tag section. Is there a way to manipulate this function to hook it inside my `functions.php` file?
Note: I tried to copy and paste this to my function, but hook is not reaching the action.
**Updated Response Fig. 1**
global $wpseo;
$wpseo = new WPSEO_Frontend();
remove_action( 'wpseo_head', array( $wpseo, 'canonical' ), 20 );
add_action( 'wpseo_head', array( $wpseo, 'canonical' ), 55 );
I tried using this as I can see the `WPSEO_Frontend` was the declared class where the `add_action( 'wpseo_head', array( $wpseo, 'canonical' ), 20 );` is located... But ended-up to broken site. | You would need to look in the Yoast plugin to find what the global class is that is referred to as `$this`, so that you can access it outside the class context. If it was for example, `$wpseo`, in your functions.php you could do something like:
$wpseo = WPSEO_Frontend::get_instance();
remove_action( 'wpseo_head', array( $wpseo, 'canonical' ), 20 );
add_action( 'wpseo_head', array( $wpseo, 'canonical' ), 55 );
To find the class name to use, look for the name of the class that contains the `add_action` with `$this` in it as you have already, and then get the instance of that class, like `$wpseo = WPSEO_Frontend::get_instance();`
**UPDATE** changed code to reflect actual found and tested class instance. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, hooks, plugin wp seo yoast"
} |
Plugin is not getting updated
I have recently updated my wordpress plugin. It shows that the plugin is updated successfully. But when i visit dashboard, again it shows to update the same plugin. I have tried to deactivate and activated again. But still the problem persists. Is there any other way to update it? | How do you update? Automatically via the admin menu? Did you restart your browser and clear the cache just to make sure? Check in the plugin editor if the version in the file is the correct one. To do that, go into the admin dashboard, in the plugin menu, go to "Editor" then select your plugin on the top right dropdown. The first file should be the main file, and in the top of the file there should be something like
<?php
/*
Plugin Name: my plugin name
Version: 1.2.2
Check if that's the latest version. If not, you do not have the right files on your server.
If that is what fails can for example manually remove it and copy the latest version in via FTP or file mananger, whatever is appropriate for your environment. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Organize functions.php
What's the best way to organize functions.php for performance?
I have a couple of add_action calls, few more add_theme_support and couple of add_filter and 4 additional functions. For breadcrumbs, stylesheets, registering menu and widgets.
Is there an order we will need to follow? For example first all the add_filter functions, then the add theme_support etc.
Not sure if it's relevant to add the code since it's a general question. If needed, I would gladly update this post. | Doing this simply won't make a significant performance difference, instead organize your customizations with clear headings so you can find and edit things faster later... in other words, organize for development in this case, not for the frontend. There are plenty of other optimizations that can be done with some research but this just isn't one of them. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "functions, theme development"
} |
How to localize something coming from theme customizer
<p><?php echo get_theme_mod('simplisto_p'); ?></p>
something is saved in the database through a theme customizer and then pulled through `get_theme_mod`.
# My Question →
How to localize this? `_e` something of this sort to be used. I can use this on normal strings but confused how to do this here. | If it's a text field, why would you? The user can put in whatever they want in their own language. If it's some sort of select then you just localize the options.
Regardless, you're not supposed to put variables or code inside `__()` functions because that's not how translations work. WPML has its own way of translating theme options that doesn't involve `__()` functions for this reason. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme customizer, localization"
} |
Security for data obtained from the database
I am getting information from the database to show it to the user, example:
$data = (get_option('config')) ? get_option('config') : false;
I need to display this data when loading the webpage, example:
<label><?php echo $data['title']; ?></label>
<input type="text" value=" <?php echo $data['value']; ?> " >
Is it necessary protect this data before showing it to the user, if the information is obtained from the database?
_Thank you very much_ | Well, it depends on the context. Usually we don't need to protect data for only showing it in frontend. **_But the best practice is, always escape or validate data, no matter where they comes from._** Like for your case you can do that like below-
<label><?php echo esc_html( $data['title'] ); ?></label>
<input type="text" value=" <?php echo esc_attr( $data['value'] ); ?> " >
Hope this above helps. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "php, wp query, functions, options"
} |
What is the section ID (name) for "Menus" in the Customizer?
I browsed many articles to know the section Name of the "Menu" in the theme customizer. Here are the few resources that proclaim and identifies that the default section name is "nav" →
1. <
2. <
Currently, there are 5 fields that are resting in the →
title_tagline - Site Title & Tagline
but as soon as I change their section name to :
'section' => 'nav',
The fields do not appear inside the menu section. whats the issue? | _Customizer > Menus_ is a _panel_ named `nav_menus`.
_Customizer > Menus > Menu Locations_ is a section inside the `nav_menus` panel called `menu_locations`.
Each menu is added a little differently, but I believe they are sections inside the `nav_menus` panel whose ID is `nav_menu[menu_id]'` where `menu_id` is the `term_id` of the menu.
_Customizer > Menus > Add a Menu_ is a section inside the `nav_menus` panel called `add_menu`, with a priority of `999`.
Browsing core code is the best way to find this stuff out. All this stuff is in `/wp-includes/class-wp-customize-nav-menus.php`
Both those articles pre-date Customizer menus by 3 & 2 years, respectively. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme customizer, settings api"
} |
Query returning same results even though the ID changes
$topics = query_posts( array(
'post_type' => 'topics',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
'key' => 'forum_category',
'value' => $forum_id,
'compare' => '='
)
)
);
Doesn't seem to make a difference to this query what you set $forum_id to, it just loads all topics for all forum_category inputs... Any ideas what could cause this?
Just to be clear, this is a function being called in the loop, so where the function is being called $forum_id is set by get_the_id() | Changing the query to:
$topics = query_posts(
array(
'post_type' => 'topics',
'meta_query' => array(
array(
'key' => 'forum_category',
'value' => $forum_id
)
)
)
);
fixed it, I guess the meta query had to be in a double array? I can't see any difference apart from that... | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "query, meta query"
} |
Change the HTML of the comment form that is generating somewhere from the core Wordpress
 are generated by the WordPress →
<cite class="fn"></cite>
<span class="say"></span>
but unless I put in some div arrangement I can't implement the HTML design to my WordPress comment system →
<div class="some-class">
<cite class="fn"></cite>
<span class="say"></span>
</div>
I am sure that there must be certain way to achieve this(Modify the core comment form HTML). | You can write your own custom HTML structure for comment listing. Inside your `comments.php` file, there will be a call to `wp_list_comments()` function. Find it, and pass your own function as its callback:
wp_list_comments( array( 'callback' => 'my_function' ) );
Now, create a callback function and start implementing your own HTML structure. This function accepts 3 arguments. Here is a basic example:
my_function( $comment, $args, $depth ){
$GLOBALS['comment'] = $comment;
// You have access to comment's ID and other
// comment query methods here, such as comment_ID();
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, comments, comments template"
} |
change the comment time output to: X time ago instead of actual date and time
<?php printf(__('%1$s at %2$s'), get_comment_date(), get_comment_time()) ?>
Above is the default code that exists for comments.php in the WP Core.
This will produce an Output like this:
, get_comment_time()
to get the above-mentioned effect? | What you need is: <
So this should do exactly what you need:
<?php printf( _x( '%s ago', '%s = human-readable time difference', 'your-text-domain' ), human_time_diff( get_comment_time( 'U' ), current_time( 'timestamp' ) ) ); ?> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "functions, date time, comments, comment meta"
} |
Does wordpress wp_enqueue_style support noscript?
I want to add stylesheet wrapped in noscript tag for a custom theme. Does wp_enqueue_style has any support for it? Or should I just include it like we do normally in html? | No, it doesn't. If you need to use **NOSCRIPT** , you need to add it to the theme header.php directly or use **`wp_head`** action to add it from code. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "wp enqueue style"
} |
Why would a theme writer put their CSS in one long string?
Today, I was reviewing the CSS for Divi Theme, and I realized that all their styles are in one long string (150 pages worth) in style.css. I have never seen this in a WordPress theme. I'm guessing that there is some compelling reason to do so, but I can't imagine what it is.
I also noticed that there is a style.dev.css files with the line breaks, but why no line breaks? | The main file is minified, so it will be smaller and faster to load. But, the author provided you with the development file version. style.css and style.dev.css are basically the same files, but the dev version is readable, and the main one minified.
All WordPress default CSS/JS files are provided with normal and minified version too (but .min is used for minified file and file without the .min is normal version). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css"
} |
How to set active class to the menu of any page coming from a single.php template
I have a static bootstrap menu in header.php with elements as follow:
<li> <a href="about-fundation.php">About Fundation</a>
</li>
I want that every page derived from single.php gets the active class for the li element. Example of the code in single.php
<?php
$post = $wp_query->post;
if ( in_category('events') ) {
include(TEMPLATEPATH . '/single_events.php'); }
Example of the resulting pages: website/2017/09/18/Name-of-the-event/
I'm already using (for certain menus):
<?php if (is_page('about-fundation')) echo 'active'; ?>
which does not work for these singlepage derived pages. | Update: Here is the answer:
<?php if(is_single()) echo 'active'; ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus"
} |
Get the category name outside of the loop in category.php
I am in a `category.php`, and I have to write the category name outside of the Loop. The category name needs to be pulled dynamically through PHP.
<p>You are browsing <?php get_the_category ?> articles.</p>
I tried the above one, but it didn't work. Whats the fix? | You're looking for `single_cat_title()`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "functions, categories, codex"
} |
How to Reverse Taxonomy Order
I have a custom taxonomy template, the items are being displayed in the default order, from newest to oldest post.
How would I change the custom taxonomy template to list the posts in the opposite order? Is there a function for this? | You can do this with the `pre_get_posts` action. `pre_get_posts` fires after the query variable object is created, but before the actual query is run. So you won't suffer performance penalties by running multiple unnecessary queries.
In your `functions.php`:
add_action('pre_get_posts','xx_taxnomy_query');
function xx_taxnomy_query($query) {
if ($query->is_main_query() && ! is_admin() && $query->is_tax('your_taxonomy')) {
$query->set('order', 'asc');
return;
}
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "custom taxonomy"
} |
Woocommerce cart page - Add "Free" to the shipping label when shipping is 0
I use a custom shipping plugin for my WooCommerce called Table Rate. When the cart's total is more than X $, the shipping cost is set to 0.
In the cart page, when there is a shipping cost, it currently displays, for example "Postal delivery: $6,00" in the shipping method section. When the shipping is free, it displays "Postal delivery".
I would like that when the shipping is 0, it adds the text "(Free)" after "Postal delivery" in the cart and checkout page, but I can't find out where this is managed in WooCommerce. I have checked the different template files, but get stuck there. I guess it could be done with a hook in the functions.php file but I'm quite inexperienced with this.
Thank you very much.
 {
if ( $method->cost == 0 ) {
$label .= "(Free)";
}
return $label;
}
add_filter( 'woocommerce_cart_shipping_method_full_label', 'custom_label', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "woocommerce offtopic"
} |
Trying to filter tag cloud args, but it removes the wrapper
I'm trying to reset the font size for tag cloud by using the `widget_tag_cloud_args` filter as follows:
add_filter( 'widget_tag_cloud_args', 'filter_tag_cloud_widget' );
function filter_tag_cloud_widget() {
$args = array(
'smallest' => 16,
'largest' => 16,
'unit' => 'px'
);
return $args;
}
This should set the font size for all the tags to 16px. The code does its job, but now there is an issue. The `<div class="tagcloud"> ... </div>`wrapper for tag cloud is gone. The anchors are directly output in the sidebar like this:
<a href="/tag-path/" class="tag-cloud-link tag-link-32 tag-link-position-2" style="font-size: 16px;" aria-label="tag">tag</a>
What am I doing wrong? | You're overwriting the defaults passed to the filter, one of which is `echo`, which is `false` by default for the widget. This is because the function that generates the tag cloud has `echo` equal to `true` by default, so your tag cloud is getting immediately output instead of `return`ed back to the widget handler. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets, tags"
} |
Display CPT description on archive.php pages for all CPT
i'd like to show the CPT description on the archive.php page but it'd like to do it dynamically for all CPT's. I mean without specifying the current type myself. Something like the_archive_description but for CPT. | Since 4.9.
if ( get_the_post_type_description()) {
echo get_the_post_type_description();
}
redeclaring the function will crash WordPress. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom post types, archives"
} |
Add image to gallery with slug
It's possible to create gallery not by id of images, but with url?
I don't want this
[gallery ids="729,732,731,720"]
I want something like this
[gallery slug=" " "
Is there some plugin? or anything?
Thanks for help | <
By default the gallery shortcode will only accept IDs or if left blank will default to current page.
You need to create a plugin and register your own shortcode or download one that already exists.
| stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "gallery"
} |
Is it ok if I use this <title> tag?
I'm using
<title><?php echo get_bloginfo('title'); ?></title>
but it shows the same title in all pages. Is it any way to show the title post, the separator and the blog name in the tag? | WordPress generates TITLE tag on its own, and you should not add title tag like that into the theme. Here is the article on WordPress Codex on how to add title tag support to the theme: Title Tag.
By default, WordPress includes website name in the title tag too, and if you implement it like this, SEO plugins will be able to modify the title tag. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "theme development, theme options, seo, wp blog header.php"
} |
Insert a hash into the url of custom posts to make them function as anchors
I have custom posts functioning as sections of a front page, and I would like to jump to them with anchors.
I have this:
example.com/about
I want this:
example.com/#about
So far, I have removed the slug from the custom posts, with `'with_front' => false`.
I would appreciate any hint how this could be done. | I have come up with a solution.
First I have assigned a slug to the custom post type:
$rewrite = array(
'slug' => 'something',
'with_front' => false,
'pages' => false,
'feeds' => false,
);
The I use a filter and a regex.
function 1234_filter_custom_post_url( $url, $post ) {
if ( 'my_custom_post_type' == get_post_type( $post ) ) {
$url = preg_replace('/something\/(.+)\//', '#$1', $url);
}
return $url;
}
add_filter( 'post_type_link', '1234_filter_custom_post_url', 10, 2 );
<
> post_type_link is a filter applied to the permalink URL for a post or custom post type prior to being returned by the function get_post_permalink. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, navigation"
} |
Importing ACF code in other page templates
We reuse allot of our ACF groups on different pages on our site. Is there a anyway to only "program" the backbone of it once and importing it on my other page templates? Right now I need to copy paste the code and if I want to change anything I need to go through all the pages that are using this ACF group and change the code.
Is it clear what I mean? Is this possible?
Thanks! | You could make one php file (not a page template) for the code of that group. Then you can include that file on the pages so you only have to edit one file to indirectly edit all the files that included that file.
You can do this with the get_template_part function
For example: You create a php file with the name of the group or something to remember it by like normalpage-code.php. you can place it directly in your (child) theme or create another directory and place it there. then in your page templates you can do:
<?php get_template_part( 'normalpage','code' ); ?>
or if you have it in another directory in your theme:
<?php get_template_part( '/anotherdirectory/normalpage','code' ); ?>
You could also use the php include function combined with locate_template to pass variables from the page template to the code for the group.
<?php include( locate_template( '/anotherdirectory/normalpage-code.php' ); ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "advanced custom fields"
} |
Increase per_page limit in REST API
WP 4.8.2
We need to increase the per_page limit on responses to a REST API request. afaik – the limit is 100
There used to be a way to filter that parameter, but it seems this filter hook is no longer working: `rest_post_collection_params`
Is there any way to increase that limit without hacking the code?
We understand the repercussions of increasing the limit, but we need to exceed the per_page in a _single_ call for use in code that will not be distributed. | The collection params accessed via that filter appear to describe the available query params but are not actually used in the query.
I think what you actually want is the `rest_{$this->post_type}_query` filter which allows you to modify the args before they are passed to `WP_Query::query()`.
Also keep in mind that on the API request the `per_page` arg might be set, but internally that is translated to `posts_per_page` for the actual query args.
Edit: I think I misread the original question...
The `rest_{$this->post_type}_collection_params` does indeed describe the available params.
You should be able to set the `per_page` max at `$params['per_page']['maximum']`. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 6,
"tags": "rest api"
} |
Gravity Forms custom Field entry
I've setup a pretty long form using gravity forms, I have gravity custom fields installed and was hoping I could then create some custom fields using "Advanced custom fields" plugin.
Then once the fields were created, associate fields in the form, to submit to one of those fields.
So ive setup My form field like this :
 into an Advanced Custom Fields field. I've had a read around and found some info and code snippets but nothing is working thus far
A bit more research and it looks like Gravity forms stores multi checked data, but ACF doesn't see more than the first field entry, Ive done an answer below, changing the field id to the field name does the trick as the example shows.
Removed Images, No need for them ( I've put the answer below ) | Ok Figured it out with a bit of tinkering with the above. Might not be ideal but it works. If someone has a better way of doing it please feel free to chip in explaining why its better :)
$gravity_form_id = '10'; // Gravity Forms ID
add_action("gform_after_submission_$gravity_form_id", "gravity_post_submission", 10, 2);
function gravity_post_submission ($entry, $form){
$post_id = $entry["post_id"];
$values = get_post_custom_values("services_available", $post_id);
update_field("field_59d5ef43664cc", $values, $post_id);
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin gravity forms"
} |
404 Error on trying to enqueue a JS file
I have been trying to use wp_enqueue_script() to load a JS script into one of my pages but it keeps throwing a "Failed to load resource" 404 error in the console (running Chrome). My code is as follows:
myplugin.php:
function myplugin_load_script() {
wp_enqueue_script( 'myplugin-testjs', (plugin_dir_path( __FILE__ ) . "scripts/myplugin-test.js"), array('jquery'), null, true );
add_action('wp_enqueue_scripts', 'myplugin_load_script');
}
myplugin-test.js:
alert("Hello!");
I have checked the HTML tag and the development tools and both of them display the correct URL (eg. wp-content/plugins/myplugin/scripts/myplugin-test.js).
I have also checked that the file does exist there and the name is correct, PHP throws no errors either. Thanks for any help! | Your syntax is wrong. The action must be defined outside of the callback.
Also, you are using `plugin_dir_path()` function, which gets the path to plugin directoy in the filesystem of the server, not the url. You should use `plugin_dir_url()` instead.
add_action( 'wp_enqueue_scripts', 'myplugin_load_script' );
function myplugin_load_script() {
wp_enqueue_script( 'myplugin-testjs', plugin_dir_url( __FILE__ ) . "scripts/myplugin-test.js", array('jquery'), null, true );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp enqueue script"
} |
Wordpress Yoast SEO plugin Post Save/Update Issue
**The Problem**
Whenever the Yoast Premium SEO plugin is active, posts are unable to save/update properly in the Admin Menu. After hitting the Update button, I found that all the custom theme shortcodes within the post were being rendered (without the CSS) instead of me being returned to the post editor. With debugger enabled, I was receiving errors like:
`Cannot modify header information – headers already sent by (some/file.php)` | **The Solution**
After WAY more research than I cared for and ultimately not getting a straight answer, I started to realize that the custom shortcode I was using to create HTML might be to blame. I was creating content by closing the `<?php` tag and reopening it after the html was finished. Turns out, I should have been using an output buffer like `ob_start()`/`ob_get_clean()` and returning the code instead.
Before:
`if (argument > 0) { ?> <p>Some text</p> <?php } `
After:
`if (argument > 0) { ob_start(); ?> <p>Some text</p> <?php return ob_get_clean(); } `
This returns the buffered HTML and allows any filters or echos to take place on the shortcode properly. Once this change was made, Yoast (and a couple others like Relevanssi) started working as they were intended to.
Now it's possible that you might get the same debug errors for other reasons, but in this instance, it boiled down to my custom theme not producing shortcodes correctly. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "posts, shortcode, plugin wp seo yoast"
} |
How to add keyword field in custom form programmatically?
For a lot of good reasons, I've inserted in my wordpress website a custom form, coded manually inside a custom plugin.
There is a simple way to add to raw code of the form a field for adding keywords (like the one this site use for 'tags', 'boxing' every word after a space)? | This link can help you in transforming text into tag-style boxes :-<
Then you can store them individually as per your use case | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "tags, forms, html"
} |
How do I sanitize the str_replace function in javascript variables
I have the following code in the javascript which outputs the date(s). With backslash for that, I'm replacing those strings with the `str_replace` to remove backslash, but I can't sanitize that using any escaping function like `esc_js`.
**Stored Days Array**
array (size=2)
0 => string '4/7/2018' (length=8)
1 => string '11/18/2017'(length=10)
**The code**
var disabledDays = <?php echo str_replace( '\\/', '/', wp_json_encode( $iva_disable_days ) ); ?>;
**Tried Code which is not working**
var disabledDays = <?php echo esc_js( str_replace( '\\/', '/', wp_json_encode( $iva_disable_days ) ) ); ?>;
Result Output
var disabledDays = ["4/7/2018","11/18/2017"];
How do I sanitize the above section in **The Code** | `esc_js()` is intended for escaping data for use within an HTML attribute.
If you want to escape data for use within an inline script, `wp_json_encode()` should be sufficient.
For example:
var disabledDays = <?php echo wp_json_encode( $iva_disable_days ); ?>;
This outputs:
var disabledDays = ["4\/7\/2018","11\/18\/2017"];
If you check the variable in your dev tools console, you will see that it is being parsed correctly:
, the second param to `wp_json_encode()` is a bitmask of options:
var disabledDays = <?php echo wp_json_encode( $iva_disable_days, JSON_UNESCAPED_SLASHES ); ?>;
This outputs:
var disabledDays = ["4/7/2018","11/18/2017"];
For a list of available options, check the PHP `json_encode()` docs. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "validation, sanitization, datepicker"
} |
masonry only works if jquery is called twice
So I noticed that I'm loading jQuery twice in my WordPress install and when I removed the CDN I added in my footer and just use the jQuery WordPress comes with my masonry stopped working and gave the error:
> Uncaught TypeError: $(...).masonry is not a function.
so then I tried using `wp_enqueue_script('masonry');` and `wp_enqueue_script('jquery-masonry');` to load WordPress's version of masonry, it still didn't work and also the script file wasn't loaded either. I'm not sure whats going on any help would be great thanks! | figured it out, turns out i was missing wp_footer() in my footer, once i added that i was able to solve my problem. thanks for the help | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery, masonry"
} |
get_terms parent for current product only
I wish someone can give me a clue.
I am actually displaying all product category (product_cat taxonomy) on single page products, displaying also childs regarding the product itself.
For instance: Product-A has Cat1-parent > Cat1-child1, Cat1-child2 => The code display them properly but also will display any other Parent Category that belongs to an another existing product.... result I get an extra parent category displaying with no childs.
So Id like to display only parent categories that belongs to the product itself.
I think I am missing some knowledge in the beginning of the code with the get_terms function
$parents = get_terms( 'product_cat' , array( 'parent' => 0 ) );
foreach( $parents as $parent ):
echo '<div class="parent '.$parent->slug.'">' . $parent->name . '</div>'; | `get_terms` relates to getting all the terms of a taxonomy. `get_the_terms` grabs all the terms related to the post.
The problem is that it sounds like you only want to return those terms which are parent categories, not the children, and `get_the_terms` does not pass an arguments array.
$terms = get_the_terms( get_the_ID(), 'product_cat' );
foreach ( $terms as $term ){
if ( $term->parent == 0 ) {
echo '<div class="parent '.$term->slug.'">' . $term->name . '</div>';
}
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "posts, taxonomy, single, terms"
} |
Table editing in Wordpress
I'm using a table in Wordpress to get my spacing right, but I'd like to remove the border completely or make it white so it isn't visible anymore. If anyone knows how to do that I'd appreciate it. I've tried a bunch of ways to do it and just can't. The web address is www.hrms.co.za (but it is still under construction) | You can do this by adding a custom CSS.
Go to "Appearance > Customize > Additionnal CSS" and add this :
td,tr {
border: none!important;
}
it will get rid of all table border | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "table"
} |
Why are Shortcodes Disabled in Widgets by Default?
I've looked all around but can't seem to locate a definitive answer for my question: why are WordPress shortcodes disabled by default in text widgets?
It's super easy to enable them, with the line `add_filter('widget_text', 'do_shortcode')`, so I'm just curious as to why WordPress doesn't have that option enabled by default.
Is it for potential security reasons? Page rendering speed? | That has been the case for a long time, text widget existed before shortcodes were added to WordPress, and since then, no one bothered to implement it. But, version 4.9 scheduled for November/December will finally have this enabled for the text widget. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "shortcode, widgets, customization"
} |
Removing code added to htaccess with insert_with_markers
I use insert_with_markers in a couple of my plugins to add some small bits of code to the htaccess file. What I'm unclear about is how to remove the code and markers.
For example, if I call the function like this:-
insert_with_markers($htaccess, "marker","RewriteBase /foobar");
The result in htaccess is:-
# BEGIN marker
RewriteBase /foobar
# END marker
I can use insert_with_markers, with an empty string, like so:-
insert_with_markers($htaccess, "marker","");
Which removes all the code, but the markers remain, like this:-
# BEGIN marker
# END marker
Does anybody know of a clean way to remove the markers as well?... that doesn't involve filtering the htaccess file with regex? I would like to be able to uninstall my plugins and remove all the traces if possible. | If you know the exact code that is inserted, then read the `htaccess` file with a function that contains `fread` command, and do a search for your inserted text, replacing the found text with an empty string. Then `fwrite` the text to the `htaccess` file.
If you are just looking for a way to remove the `# BEGIN MARKER / # END MARKER` text, then use the same process. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "htaccess"
} |
Using polylang, how can I see which post is the "original" and which are the "translated children"?
I am using Polylang. It is not obvious to me how the relationship between posts are established. I can switch between different language versions of the same post, and I can tell that they're (obviously) different posts in the database. But I can see how Polylang establishes and maintains that relationship. I assumed that there was some meta-value, but that's not the case. Does anyone have any insight?
Initially, I'd like to know this, because I need to create a publish flow where translations aren't accidentally published before the "original". | polylang stores translation in a taxinomy but it's better to access them with the polylang object like that :
// test if the plugin polylang is present
if (isset($GLOBALS["polylang"])) {
$translations = $GLOBALS["polylang"]->model->post->get_translations($post->ID);
// $translations contains an array with all translations of the post
}
all translations are interconnected then there is no parent translation. if you want to find the first created post you can search the lowest ID or sort by publication time. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "translation, plugin polylang"
} |
Site header logo and parallax image on homepage do not display on iPhone
I use Chrome and an Android phone, and only just looked at my site on a friends iPhone. On my homepage there is no logo in the header, and the parallax image on the homepage doesn't load.
Site: <
Other images load on the site fine. There looks to be the correct @2x images there. Website also uses WebP images, but from what i understand the image format will default to jpg/png if the device can't display WebP.
Any suggestions would be gratefully received, as I no longer have an iPhone to check :( | Do not use WebP, it works in Chrome only. If you check your website in Firefox or Edge on Windows, these images are not loaded also. When I check the source of your website in Firefox or Chrome, the image source is with JPG extension, but Firefox returns that image is missing, and if I try to open it in other programs, it says that format is not recognized. Only Chrome, Vivaldi and Opera can see these images because they all use Chromium in the browser with WebP support.
That is why iOS Safari (and most likely normal Safari on macOS) don't see these images.
Also, I am not aware of any method to automatically replace WebP with PNG/JPG for WordPress or any other CMS. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "images, iphone"
} |
Problems using WooCommerce & Qstomizer
In my site:
> Warning: Missing argument 3 for Qstomizer::qsmz_change_product_image_thumbnail_html() in /home/grafixcordoba/public_html/corp/wp-content/plugins/qstomizer-custom-product-designer/qstomizer.php
Could anyone help me? | > This plugin hasn’t been updated in over 2 years. It may no longer be maintained or supported and may have compatibility issues when used with more recent versions of WordPress. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "woocommerce offtopic"
} |
get full category structure by post id
I have three level category structure as bellow.
- parent 1
- parent sub 1
- child 1
- child 2
- parent sub 2
- child 3
- child 4
Unfortunately, some of posts doesn't fill correctly which means it ticks only the sub parent level or child level.
I have a specific requirement to get whole category structure by post id. So I used following code to retrieve the ids,
wp_get_post_categories( $post_id )
This is only giving me the category ids which was ticked, but I need the full category structure.
Eg :
if a posts ticked only `child 2`, from above code I get only `child 2` cat id. instead of that I need `child 2`,`parent sub 1` & `parent 1` cat ids.
How can I do that ? | Have you tried using get_ancestors?
Ideally, you would do this in a hook after the post has been updated and add the parent categories to the post so that you can use them in Queries. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories"
} |
Several times request to load plugins when sending one request
When we sending 1 request to load any page (Home, Single or etc), WordPress running more than several times.
For example you can adding the below code in the main plugin file or `functions.php` in current theme and you can see the log file!
file_put_contents('log', print_r($_REQUEST, 1), FILE_APPEND);
I need a solution to fix/skip this issue. | That might well be, but that's alright. There might be redirects happening, and those will result in multiple requests. The WordPress-Cron System relies on AJAX-requests, those will also show up in the log. If you load any resources (images, scripts, stylesheets) that do not exist, WordPress will be loaded and handle the 404, resulting in more requests (and log entries).
Unless you're seeing a large number of requests per page view, it's probably fine. If you do, use your browser's developer tools to see what requests it is sending and why. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "http, logging"
} |
Best method to upgrade multisite plugin's numerous database table
In the codex it is explained how to hook to `plugin_loaded` and check the version of the currently installed plugin against what's registered in the options, then realise if you need to upgrade the plugin table.
Question is - what's the method to do it with a multisite plugin that has custom database tables for each network blog? If I hook into `plugin_loaded` then a random user who happens to be the first that executes the code will need to take all the load of this potentially huge and long process.
Isn't there any manual way to do it? somehow via cron? other suggestions? | You could just add a check for `is_admin()` and `current_user_can("update_plugins")` to make sure you're running only for admin users that are currently in wp-admin. Any user browsing the front end won't notice anything, logged in or not.
You will probably also want to make sure that this runs only once to avoid race conditions that would produce database errors e.g. running the same `ALTER TABLE add ...` twice. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, multisite, upgrade"
} |
Correct way to insert taxonomies on page insert
$page = array(
'post_title' => 'New Job',
'post_name' => 'new-job',
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'jobs',
'tax_input' => array (
'status' => 'system'
)
);
wp_insert_post( $page );
This doesn't work. I am trying to create post and relate it to my custom term in my custom taxonomy.
Taxonomy: status
Term: system
What am I doing wrong? | Turns out you can't use the term slug (for obvious reason of possible duplicate slugs _face palm_ ) you need to use the terms ID.
$term_id = term_exists( 'system', 'status' );
$page = array(
'post_title' => 'New Job',
'post_name' => 'new-job',
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'jobs',
'tax_input' => array (
'status' => array ( (int)$term_id["term_id"] )
)
);
wp_insert_post( $page ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom taxonomy"
} |
add_action.. will work if function is empty?
My Example:
function example() {
if ($checked) echo 'true';
}
add_action('wp_head', 'example');
now, if not `$checked`, will wordpress do an empty `add_action` or will avoid it? if do, how I can just add action if `$checked` is true? | The function will run, but nothing will happen. There is a small overhead, but you shouldn't worry about it, the possible savings are minimal.
Depending on when you have $checked available, you could also do
function example() {
echo 'true';
}
if ($checked) add_action('wp_head', 'example'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "actions"
} |
Wordpress delete mysql rows with string
So I'm updating the code of an old wordpress plugin(never released), and I want the database to be "clean" before importing new data otherwise data will just add up and i want it clean before every import, so that duplicates dont happen.
This is the code that i'm using but doesn't seem to work.
global $wpdb;
$wpdb->delete( $wpdb->postmeta WHERE meta_key LIKE '_cb_%' ) );
$wpdb->delete( $wpdb->posts WHERE post_type LIKE 'webcam' ) );
What's wrong with this picture?
Thanks in advance. | Look at the documentation, $wpdb->delete() takes at least two parameters, the table name and the Where-conditions as an array(). LIKE isn't supported for delete imho, so you'll need to use ->query
global $wpdb;
$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key LIKE '_cb_%'" );
$wpdb->query( "DELETE FROM $wpdb->posts WHERE post_type LIKE 'webcam'" );
I assume the double closing parentheses and missing quotes were just from copy pasting? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, post meta, mysql, post type, customization"
} |
Where would I place `wp_footer();`?
I am currently working on the `footer.php` file. I am just wondering where I should place the `wp_footer();` in relation to the `<footer>` elements. Which of the following would be correct?
**Method A:**
<footer>
<h1>Title Text</h1>
<p>Some text</p>
<?php wp_footer(); ?>
</footer>
</body>
</html>
**Method B**
<footer>
<h1>Title Text</h1>
<p>Some text</p>
</footer>
<?php wp_footer(); ?>
</body>
</html>
I checked WordPress' Codex but could not find a solution. I did not notice any aesthetic difference to the web page. So maybe it is a personal preference? | wp_footer() loads enqueued JS files, etc.
Place it just before the closing tag like in method B. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, footer"
} |
Concatenate string to the_field()
I need to show something like "40 MINUTES PREP/COOK" and the preparation_time returns "X MINUTES" but I can't concatenate a string to the_field.
<?php if(the_field( 'preparation_time' )) :
the_field('preparation_time');
echo " PREP/COOK";
endif; ?>
What am I doing wrong? | You'll have to show more of the relevant code, but, to begin with, if you want to check for the availability of a 'preparation_time' ACF value, use
if ( get_field( 'preparation_time' ) ) : // get_field(), not the_field()
As the ACF docs put it, `the_field( 'field' )` is the same as `echo get_field( 'field' )` \- so wouldn't return true or false, but instead simply print (if you get to it).
I'd probably write it
if ( get_field( 'preparation_time' ) ) {
echo get_field( 'preparation_time' ) .
' 40 MINUTES PREP/COOK' ;
}
But no guarantees, since I don't know the context. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
Can you define readability settings in wp-config.php?
The title basically answers the question, but I am trying to set basically any random setting at will in wp-config.php so that it's not overwritten by default when I do staging -> live database pushes. | The short answer is "no." You can set settings in functions.php or some other system file, but there's not a default setting like database_prefix to do this. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp config"
} |
Correct Plugin File Path
>
> **Warning** : require_once(/assets/MCAPI.class.php): failed to open stream: No such file or directory in **/home2/....../wp-content/plugins/bplugin/shortcodes.php** on line **148**
>
> **Fatal error** : require_once(): Failed opening required '/assets/MCAPI.class.php' (include_path='.:/opt/php54/lib/php') in **/......./wp-content/plugins/bplugin/shortcodes.php** on line **148**
>
require_once(plugin_dir_path( __FILE__ ) . '/assets/MCAPI.class.php');
Am I not using the **correct path method**?
This file is called inside a rest API function → <
Update: If I transfer file from assets to the plugin directory then things work →
require_once(plugin_dir_path(__FILE__).'MCAPI.class.php');
but that's not the very clean method of handling files. | <
It looks like this function adds a trailing slash, so starting your string with a slash is not required try;
require_once(plugin_dir_path( __FILE__ ) . 'assets/MCAPI.class.php'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, paths"
} |
create new site subsite in wordpress multisite by subscriber user instead of network admin
How to create new site subwebsite in wordpress multisite by subscriber user instead of main admin.
I want registered user can create one sub domain instead of network admin.
i have search my there is no option to add new sub-site by sub users.
is there any option or custom code or any free plugin please let me know. | Go to **/wp-admin/network/settings.php** as a _Super Admin_ and where it says _"Allow new registrations"_ set it to one of these:
* _"Logged in users may register new sites"_ (no new users can register)
* _"Both sites and user accounts can be registered"_ (new users can register)
Both these settings allow logged in users to create new sites by clicking on _"My Sites"_ and then _"Add new"_ , which points them to **/wp-signup.php**. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "multisite"
} |
WordPress shows registration link for non logged users
I have a WordPress site and I want to add a registration link for visitors.
So, I added a menu item called 'REGISTER' with the following link:
The problem is that this link opens the registration form for both users and visitors and I want to show it only to visitors. | i fixed the problem with Nav Menu Roles plugin
I added the registration link to the menu and with the plugin and i set it to only logged out users
This way it won't show to logged users | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, login, user registration, cms"
} |
the_tags : can we insert a class
<?php the_tags( '<ul><li>', '</li><li>', '</li></ul>' ); ?>
when we use the above we get this kind of HTML →
<ul>
<li><a href=" rel="tag">first lady</a></li>
<li><a href=" rel="tag">ivanka</a></li>
<li><a href=" rel="tag">sexy</a></li>
</ul>
Is it possible that within the anchor tag we can insert a class like this →
<li><a href=" rel="tag" class="my_custom_class">ivanka</a></li>
Reference → < | Yes, it is possible.
<?php
$post_tags = get_the_tags();
if ($post_tags) {
foreach($post_tags as $tag) {
echo '<a href="'; echo bloginfo();
echo '/?tag=' . $tag->slug . '" class="' . $tag->slug . '">' . $tag->name . '</a>';
}
}
?>
The code is from another answer on Stack Overflow, see here for the source and more info | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, functions, codex, tags"
} |
How to Remove Checkbox for Excerpt Under Screen Options
In relation to How to Display Post Excerpts in Admin by Default?, how would we go about removing the checkbox for Excerpt under screen options entirely for a complete solution? | You can do this with CSS.
.metabox-prefs label[for="postexcerpt-hide"] {
display: none;
}
**In regard to adding the CSS to the admin section, you have two options:**
Option 1: Add the CSS to a stylesheet and enqueue it using the `admin_enqueue_scripts` hook.
function load_custom_wp_admin_style() {
wp_register_style( 'custom_wp_admin_css', get_template_directory_uri() . '/admin-style.css', false, '1.0.0' );
wp_enqueue_style( 'custom_wp_admin_css' );
}
add_action( 'admin_enqueue_scripts', 'load_custom_wp_admin_style' );
Option 2: Add the CSS to a style tag using the `admin_head` hook.
function remove_post_excerpt_checkbox() {
?>
<style>
.metabox-prefs label[for="postexcerpt-hide"] {
display: none;
}
</style>
<?php
}
add_action( 'admin_head', 'remove_post_excerpt_checkbox' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp admin, excerpt"
} |
How to show terms from another taxonomy
I have a taxonomy problem that I've been trying to solve for days. I'll try to explain it.
I have two taxonomies, ' **type of store** ' and ' **state** ' of a post type called ' _store_ '. I'm building a search that should display in which states, particular type of store is present. Just like which stores are in a certain chosen state.
In other words, when I choose a type of store, only states that have such stores should appear.
That way I can display the terms of both, but do not separate them.
$taxonomies = array('store_type', 'states');
$args = array(
'taxonomy' => '$taxonomies',
'hide_empty' => 'true',
'parent' => 0,
'tax_query' => array(
'relation' => 'AND',
),
);
**Can someone please help?** | Look at taxonomy parameters in WP_Query, the "Multiple Taxonomy Handling" example does pretty much what you want if I understand you correctly. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, query, taxonomy, search, terms"
} |
Are multiple values from get_post_meta guaranteed to be ordered?
You can create multiple rows in the `postmeta` table for a post with the same key, like this:
add_post_meta( $post_id, "example_key", "value1" );
add_post_meta( $post_id, "example_key", "value2" );
To retrieve the values, you can use `get_post_meta`, which will return an array:
$rv = get_post_meta( $post_id, "example_key" );
// $rv is array( "value1", "value2" )
Is the resulting array guaranteed to be ordered? In what order are the values in? Alphabetical, or date inserted? | **Yes**.
`get_post_meta()` uses `get_metadata()` which in turn uses `update_meta_cache()` to retrieve the values. In the source code we see this part (comment mine)
// $id_column is 'meta_id'
$meta_list = $wpdb->get_results( "SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list) ORDER BY $id_column ASC", ARRAY_A );
So the meta values will be ordered by `meta_id` in ascending order. Meaning, as @Jacob Peattie pointed out in comments, they will be **ordered by the date they were added**. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "post meta"
} |
Updating custom theme that is built from scratch
Is there any way to update theme from backend? I tried but wordpress shows error that folder already exists and renaming zip file creates and installs completely new theme(Which is another issue as I want to maintain version numbers on zip file names).
Anything I can do so wordpress will understand that I want to update existing theme instead of treating it as new theme? It will be better if I can update it from backend rather than go through ftp. | Right now I suggest simply uploading it via FTP. If you're not too familiar, many hosts offer "WebFTP" which is usually easier to use.
For the future you might consider GitHub Updater, check out their wiki. This basically allows you to use a new setting in style.css
GitHub Plugin URI: foo/bar
Once configured, you can use versioning on GitHub and simply update from the backend, like you're used to from other plugins & themes. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "themes"
} |
how to count the current posts terms
Hi i'm trying to figure out how to count the number of terms for the current post, i've tried using `wp_get_object_terms`() and
<?php
$title = get_post($post->ID);
$numTerms = wp_count_terms( $title->post_type, array(
'hide_empty'=> false,
'parent' => 0
) ); ?>
without any luck, does anyone have a solution for this issue?
thanks | `wp_count_terms` function counts terms in a given taxonomy (e.g. total number of categories, total number of tags).
To get what you want, get the terms for the post and just count them `count( wp_get_post_terms( $post_id, $taxonomy, $args ) );`. Or, assuming that in real life you might need those terms later:
$terms = wp_get_post_terms( $post_id, $taxonomy, $args );
$terms_count = count ( $terms ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy, terms, count"
} |
Home page returns 404
Must have inadvertently changed something recently as when visiting the base URL (i.e. the homepage) for my local development site it returns a 404. All of the other pages seem to work fine.
As per other SE posts on the topics, have tested changing the permalinks settings and the .htacess file, from what I can tell, seems to be set appropriately.
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /dwp-wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /dwp-wordpress/index.php [L]
</IfModule>
# END WordPress
The front page is set to Home, but what's strange is when this is changed to Blog, the 404 is resolved and the front-page.php is pulled appropriately.
Does anyone have any idea as to what might be causing this issue? | After checking out previous commits, I eventually found the issue to be a custom query added to functions.php which had been inadvertently added to the home page. Strangely, this hadn't been logging any errors but still caused a 404.
By adjusting the scope of the query, the issue has now been resolved. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "htaccess, 404 error, homepage, home url"
} |
Update WooCommerce Short Description using SQL
How can I update my wordpress database with a SQL query to move the [Description] field into the [Short description] and then set the [Description] blank ? | You should never change the database structure,, if you just wanna display the short description in place of description there are hooks and filters you can use alternatively you can override the plugin file that displays the single products by creating a woocommerce directory and add tha file in the same hierarchy as in the plugin templates folder. have a look at < you'll also going to find the hooks and filters to do the job if you dont want to add the woocommerce directory.
you need to update the yourprefix_posts table, the products are also wordpress post you can write
update yourprefix_posts set post_excerpt=post_content , post_content='' where post_type='product' | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "woocommerce offtopic, mysql"
} |
Don't attribute content to admin users
For security reasons, I want to make sure no content is attributed to admin users of my websites.
Essentially, I want a way to automatically change the author of any piece of content to something else (including uploads).
As an admin, when I delete a user, WordPress asks me if I want to delete all their content or reattribute it to another user.
Well, I want to automatically change the author of content from a given user (an admin user) to another user (an author/editor).
How can I accomplish this (I generally have root level access to the servers hosting the sites)? | Hook into a post status transition so that any time a post is published or updated, there's a check to see if the author is an admin. If so, update the author to a non-admin. First, get the ID of the non-admin user you want to set as the author.
// change author ID to suit your needs
$newAuthor = 3;
// hook our function to fire when any post type's status changes
add_action('transition_post_status', 'wpse_change_author', 10, 3);
function wpse_change_author($new_status, $old_status, $post) {
// only adjust published posts - which are either new or newly updated
if($new_status == 'publish') {
// check whether author is admin
if(user_can($post->post_author, 'administrator')) {
// update the post with new author ID
wp_update_post(array('ID' => $post->ID, 'post_author' => $newAuthor));
}
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "admin, author, security, permissions"
} |
return only the first two terms of custom post
hey im trying to figure out how i can display only two terms that are associated with a custom post type. I tried using `$wpdb` but that doesn't work for me since i need the term links as well. any suggestions?
thanks | Maybe this can help. First, get all the post's terms; then, cycle through them with a `foreach` loop to retrieve and echo each one's link. The last line of code will limit the cycle to the first two terms.
$terms = wp_get_post_terms(); // If you're not in the loop, you should pass the post's ID as an argument.
$i = 0;
foreach ( $terms as $term ) {
$name = $term->name;
$href = get_term_link( $term->term_id );
echo '<a href="' . $href . '">' . $name . '</a>';
if ( ++$i == 2 ) break; // Limit to first 2 tags
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, terms, limit"
} |
How to move Wordpress theme files into a subfolder without breaking the theme?
I've been coding a Wordpress theme using OOP PHP, node.js and Webpack, and between classes, node_modules, configuration files and Wordpress template files my theme's directory has become a bit messy...
Is there an easy way to move the theme's template files to an `app` subfolder without breaking the theme?
(I've found a similar question but it was asked in 2011, so hopefully something came up over time). | Out of the box WP relies on Template Hierarchy to resolve and load template. The default assumption is that (most) template _are_ in the root of the theme and follow the naming conventions.
Placing template files elsewhere essentially requires rebuilding Template Hierarchy in your code with different assumptions. This used to be crazy inconvenient, but WP 4.7 introduced `{$type}_template_hierarchy` hook, which makes it significantly easier.
As a personal aside I think native WP template simply doesn't scale meaningfully to complex use cases. If there are enough templates to clutter the directory, then I would move to a different template engine (such as Twig) altogether. Of course that is hardly mainstream technique in WP development.
I have an example of template hierarchy override in my Meadow project for Twig integration, but same works for just changing up logic for PHP templates. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "themes, filesystem"
} |
Filter the regular price of woocommerce products
Want to filter the regular price of woocommerce products.
Based on product id and their meta data I want filter the get_regular_price of that product
Something like this.
function filter_woocommerce_get_regular_price( $array, $int, $int ) {
return $array;
}
add_filter( 'woocommerce_get_regular_price', 'filter_woocommerce_get_regular_price', 10, 3 ); | Unfortunately the filter hook "woocommerce_get_regular_price" is not usable any more. There is another one alternative of that, you can use this below code to achieve your need.
function filter_woocommerce_get_regular_price( $price, $product ) {
// use $product->get_id() to get product ID
// Do any custom logical action
return $price;
}
add_filter( 'woocommerce_product_get_regular_price', 'filter_woocommerce_get_regular_price', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "filters, woocommerce offtopic"
} |
Corrupted nav-menu?
I am currently debugging a WP install with lots of plugins and Avada theme (Fusion core, Fusion Builder)
The thing is I can't edit the current Menu. When I select an item and add it, the spinner pops, unpops, and nothing more happens actually.
I digged a little and tried to delete all terms and taxonomies in database but now. I can't create nav-menu because it is created with term_id 0. Even with wp-cli, wp create menu 'test' says :
`Success: Created menu 0.` with each new invocation of the command with different menu names.
What is wrong? Anyone has tips to reinitialize menu datas ? | I resolved my issue.
This was due to the lost of indexes, primary keys and auto_increment feature in my database structure due to export/import database actions.
With bad export options, the indexes and primary keys at one point, weren't re-created during import and so on....
Always export your database with right structure options. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, menus, taxonomy, terms"
} |
read_private_pages capability not working for new role
I have created a new user role - _vendor_ \- with the capability to `read_private_pages`, but when I log in as such a user, and go to a private page I cannot see it.
Here is my plugin code:
function fc_add_role($role, $display_name, $capabilities = array()) {
if (!empty($role)) {
return wp_roles()->add_role( $role, $display_name, $capabilities );
}
}
if (!get_role('vendor')){
fc_add_role('vendor', 'Vendor', array('read_private_pages', 'read_private_posts'));
}
And when I go to my private page as a vendor, it just shows:
> **Oops! That page can’t be found.**
>
> It looks like nothing was found at this location. Maybe try one of the links below or a search?
What am I doing wrong? And how can I make it so vendor users can read private pages?
NB - When I log in as admin, I can see the private page. | Your capabilities should be a key value pair:
fc_add_role('vendor', 'Vendor', array(
'read_private_pages' => true,
'read_private_posts' => true
)); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "user roles, private"
} |
I renamed my server from http to https and now I can't login
I set up a WordPress site under a temporary domain name, using http protocol. It works fine.
Now I want to make it live under a completely different domain name, with https enabled.
My first step was to obtain an SSL certificate for the new domain name. I enabled Apache to accept https requests using the new domain name. I verified this was working by accessing the site using the new name. Of course, since the site name in WordPress general settings is the old http address, my browser was redirected there.
So I logged in to wp-admin and changed the site url fields to the new domain name (with https).
As soon as I saved the page, I was redirected to a login page (which seemed to be missing its css). But trying to login on that page just redirects back to the login page again.
I did this successfully before with another site, so I'm confused why it doesn't work this time, as I think I have been through the same steps. | Have you tried a database migration plugin? WP stores serialized data about the URLs so often simply updating the home and site_url option is not enough. Also try an Incognito window or another browser to see if you have old redirects cached. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "login, https"
} |
can the footer be included on a child theme
If the footer can be included, what must be written on the child theme `footer.php` page to get it started. I should say I am new to child themes and have already shut the site down by including the entire parent stylesheet/functions.php. After reading about that same rookie issue that another member experienced I immediately went to cPanel to delete it.
However before I upload my updated child theme, I'll wait for an answer concerning the `footer.php`. Of course I would like to edit it on my child theme to remove the WordPress branding only once. | Take the whole footer.php from the parent theme and copy it to your child theme. Your child theme will override the parent footer now. Any changes you make to that footer file in the child theme (ie removing branding) will affect the site.
This is usually better than starting with a whole new footer.php especially if the theme you are using is overly complex.
As for the style.css and functions.php. Sorry you had to go through that mess! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "child theme"
} |
Append class to posts page
I'm trying to style something unique to the Blog/Posts page, which isn't on the front page. The body tag right now looks like this:`<body <?php body_class() ?>>`
But doing this `<body <?php body_class('blog') ?>>` only returns `<body class="logged-in">` or just `<body>` if I'm not logged in.
I've tried:
<body <?php if ( is_home()) {
echo 'class="blog"';
} else {
body_class(); }?>>
It sort of works but it replaces the "logged-in" class entirely. There has to be a way to append classes to the body tag for posts pages right? | In your theme's functions file, use the `body_class` filter to add new classes:
function wpse_282694_body_class( $classes ) {
if ( is_home() ) {
$classes[] = 'blog';
}
return $classes;
}
add_filter( 'body_class', 'wpse_282694_body_class' );
If your category archives, tag archives, date archives and search results also need the same styling, which is fairly commin, check for each of them like so:
if ( is_home() || is_date() || is_tag() || is_category() || is_search() ) {}
Note that I didn't use `is_archive()`, because that would also affect any custom post types you might be using. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, blog, body class"
} |
Include only one category but Exclude if is in a category from loop
I have a products for example :
1) PROD A is in CAT A 2) PROD B is in CAT A and CAT B 3) PROD C is in CAT A 4= PROD D is in cat C
I need to show all products in CAT A but not in cat B (exclude cat b). How can i do ?
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat'
'field' => 'slug',
'terms' => 'CAT A',
'operator' => 'IN'
))); | You would use multiple arrays in the tax_query and make sure you use the AND relation so it combines them, like so:
$q->set( 'tax_query', array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat'
'field' => 'slug',
'terms' => 'CAT A',
'operator' => 'IN'
),
array(
'taxonomy' => 'product_cat'
'field' => 'slug',
'terms' => 'CAT B',
'operator' => 'NOT IN'
)
)); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop"
} |
Query all published post AND attachment with specific mime type
I need to add only specific attachments (PDF) to the query along with other CPT. But when I add mime type value to the query any other post type get filtered out.
Here is the query args
$args = [
'post_type' => ['any', 'attachment'],
'post_status' => ['publish', 'inherit'],
'post_mime_type' => ['application/pdf'],
'posts_per_page' => 10
];
How do I get other post types with attachments of specific mime type? (only pdf in this case) | First of all if `any` is used for `post_type` field there can not be any other value given in array like in the question. Below is the modified args
$args = [
'post_type' => array_values(get_post_types(['public' => true])),
'post_status' => ['publish', 'inherit'],
'posts_per_page' => 10
];
**Use`posts_where` filter**
add_filter('posts_where', 'add_search_mime_types');
$query = new WP_Query( $args );
remove_filter('posts_where', 'add_search_mime_types');
function add_search_mime_types($where){
$where .= ' AND post_mime_type IN("application/pdf","") ';
return $where;
}
The empty string on the SQL query to include post types other then `attachment`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp query, query"
} |
What does add_theme_support('custom-header-uploads'); feature do?
Whilst adding features to the `functions.php` file, I came across the following:
`add_theme_support('custom-header-uploads');`
What exactly does this do? I removed the entry, in the `functions.php` but saw no difference to the website. I initially thought it had something to do with the ability to upload header images but that is down to `add_theme_support('custom-header');`
I cannot see any meaningful information, when performing a search, across Codex. Is this some kind of depreciated feature or am I overlooking something? | It probably does nothing. I cannot find any reference in the developer resources or the theme handbook.
Also doing a quick search through WP source code shows this is only used in _wp-includes/theme.php_ , and even there only in the parts about adding/removing theme support. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "add theme support"
} |
Unable to access website admin page - 500 error - how to change landing page
Help is required to solve a problem created by a stupid mistake.
Our website is hosted by Godaddy and created with Wordpress. It had been set up and running smoothly for long.
Recently We wanted to keep the website down for some time as we wanted to modify some contents. So with a "brilliant-idea-moment", using wp-admin login, in the dashboard, the landing page name was changed from "mydomain.com" to "mydomain.com/404".
Now we are not able to access the wp-admin login page at all to revert back, as it keeps redirecting it to "mydomain.com/404/wp-admin", a page which does not exist so giving a 500 error message.
Is there anyway, we could change the landing page back to original, through hosting admin or cPanel by editing any specific file?
Your assistance would be highly helpful. | Connect to you Cpanel through godaddy and search for `PHPMyadmin`. The interface that allow you to manage your database.
Then search for a table called `wp_options` then in this table you should be able to find the url of the site in two places ( **siteurl** , **home** ) and you should be able to change it back to the domain name.
After this you will be able to access the admin again, then you should go to the permalinks settings and hit save (without doing any changes). This will correct your url rewriting. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "login, 500 internal error"
} |
Windows Azure Storage for WordPress plugin not listing blob containers
I've just installed wordpress 4.8.2, set it up for multi-site, and deployed the Windows Azure Storage for WordPress plugin version 4.0.2.
In a new sub-site, I'm trying to configure the plugin settings.
I enter the account name and key, but the Default Storage Container dropdown does not contain any items, so I can't choose any containers. It doesn't even show me the option of creating a new container.
 or if it's an incompatability between the WordPress version and the plugin. | The answer is to install the php xml package:
sudo apt-get install php-xml <br/>
sudo service php7.0-fpm restart <br/>
sudo service nginx restart
I discovered the actual problem one of the log files:
2017/10/16 22:14:07 [error] 14850#14850: *1090 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught Error: Call to undefined function simplexml_load_string() in ...
Turns out that function is supplied by php-xml | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "plugins"
} |
How to find the value of the user password in wordpress and send it to another server via rest api
If there is some variable from the user's password, I want the password that the user has entered for the wordpress account, to send to another server, so that the user can also log on to another server with the same data as on the wordpress, is there anyone a solution for this? thank you all for help | WordPress is not storing the password in the database in the readable format, so you can't simply get the password for any user. Passwords are stored in the hashed format, and they can't be reversed back to a readable format. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "php, woocommerce offtopic"
} |
How can i put php code on the wordpress page?
is it anyway possible to find a home page at all, I would like to insert php code on it, from cms I do not know if it's possible, I watched some plugins, but they do not look good to me. thank you all for help | I think using the user_registration hook is probably the best fit for what you want to do.
An example from the docs:
add_action( 'user_register', 'myplugin_registration_save', 10, 1 );
function myplugin_registration_save( $user_id ) {
if ( isset( $_POST['first_name'] ) )
update_user_meta($user_id, 'first_name', $_POST['first_name']);
}
To be compliant with the WordPress way (and be less likely to get into trouble if you change servers), you should probably use WP's HTTP API to send the XML to the other URL. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, woocommerce offtopic"
} |
WooCommerce - change child category URL structure
Let's say I have category **Foods** and it has a child: **Chicken**.
By default, the URL for Chicken category will be like: `yoursite.com/product-category/foods/chicken`.
Is there a way to make it `yoursite.com/product-category/chicken`? I want to keep the parent-child relation so I can query all Foods and list all child-categories of Foods. | Try something like this in your functions.php:
function ran_remove_parent_category_from_url( $args ) {
$args['rewrite']['hierarchical'] = false;
return $args;
}
add_filter( 'woocommerce_taxonomy_args_product_cat', 'ran_remove_parent_category_from_url' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
How to add custom classes to a Wordpress theme HTML tag?
I've been googling how to add custom classes to the HTML tag of a Wordpress theme, but it's a tricky issue to research because all results are about HTML tags in general, not the **specific HTML tag** that opens a document. I want something like this:
<html class="custom-class">
I know the `body_class` filter can be used to customize the body's classes, but there seems to be no such thing for the html tag, yet Wordpress does output some classes for `<html>`, so they must be coming from somewhere...
Any ideas? | There is no designated template tag for classes on `html` container.
For example in latest core Twenty Seventeen theme they are hardcoded:
<html <?php language_attributes(); ?> class="no-js no-svg">
For proper customization you would likely need to create a child theme and override repsective template (likely `header.php`) or settle on manipulating classes with JavaScript. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization"
} |
comment button shows only logged in users wordpress
I have a question in my blog site < . the comment button shows Registered users only. ![enter image description here](
Logged in users shows the comment button.
Other users shows only part of the button. Anyone have any idea why this thing happens? All the wordpress comments settings are fine. Is this a wordpress issue or theme issue? I used Betheme in this blog. | it's css issue. add this css your current theme style.css
p.form-submit {
clear: both;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.