INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Hide a certain category name from Related Posts
I am trying to alter a plugin that has this code to display Related Categories names under the post:
<?php if ( count( get_the_category() ) ) : ?>
<span class="cat-links">
<?php printf( __( '<span class="%1$s">See related Videos</span> %2$s', 'posts-in-page' ), 'entry-utility-prep entry-utility-prep-cat-links', get_the_category_list( ', ' ) ); ?>
</span>
<?php endif; ?>
Can someone please tell me how I can alter this code to exclude one Category name from the list that it generates...?? The category name that I want to exclude is "TopONLY" and its ID is 11. | $d = get_the_category();
$glu = [];
foreach($d as $rst ):
//exclude category name
if($rst->name != 'Sticky'):
$glu[]="<a href=".get_category_link( $rst->cat_ID ).">{$rst->name}</a>";
endif;
endforeach;
//error_log(print_r($glu, true).'/n', 3, WP_CONTENT_DIR.'/debug.log');
echo "These are the categories". implode(', ', $glu);
I'm a beginner. Hope this will help! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, customization"
} |
Update post_content everytime a custom post is opened in backend
I need to implement a function that substitutes the post_content of the current custom post as soon as it is opened in admin editor. Its purpose is to have updated informations inside the content until the post becomes "published".
What is the correct action/hook that allows me to get the informations about the currently opened post and modify it?
I have developed this function but it is not working well:
function save_team() {
$post = get_post();
$ID_post = $post->ID;
$team = get_post_meta ($ID_post, ‘hometeam’, true);
if($post->post_type == "game" && $post->post_status == "draft"){
$post_content = $post->post_content;
//code that modifies post_content here by adding $team at some point
$my_post = array(
‘ID’ => $ID_post,
‘post_content’ => $post_content,);
wp_update_post( $my_post );
}
} | The `content_edit_pre` filter might be what you are looking for. This filters the content of a post before it's retrieved and output in the editor.
So you might be able to do this:
function save_team( $content, $post_id ) {
$team = get_post_meta ($post_id , 'hometeam', true);
if( get_post_type( $post_id ) == "game" && get_post_status( $post_id ) == "draft" ){
//code that modifies post_content here by adding $team at some point
$my_post = array(
'ID' => $post_id,
'post_content' => $content,);
wp_update_post( $my_post );
}
}
add_filter( 'content_edit_pre', 'save_team', 10, 2 );
The post ID and content are passed to this filter, so there's no need to use `get_post();` here.
As a side note, you should not use `‘` and `’` as quotations. Use `'` or `"` instead. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "posts, filters"
} |
Enqueue new login style sheet
i tried to enqueue a new login stylesheet called login_styles.css.
This is the code i have used:
function my_logincustomCSSfile() {
wp_enqueue_style('login-styles', get_template_directory_uri() . '/login_styles.css');
}
add_action('login_enqueue_scripts', 'my_logincustomCSSfile');
Its placed in my child-themes functions.php.
The css file is totally empty. How do i go about this?
The file is placed in same folder as functions.php | Replace `get_template_directory_uri()`, that's for your parent theme's directory, with `get_stylesheet_directory_uri()` since you want to target the file within the child theme's directory.
Or better yet, just use `get_theme_file_uri( 'login_styles.css' )` if you want to search for it, first in the child theme's directory, else in the parent theme's directory. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "login, wp enqueue style"
} |
Should i use usermeta or taxonomy (or even custom taxonomy)?
i have been researching much about taxonomies and usermeta. So taxonomies are to categorize things up for posts (animals, plants..). That makes it easier to search posts through them.
Now here is my question: I want to add custom user fields like **gender, university, age** etc..
Should i define them as usermeta, taxonomy (categories: gender->male,female) or custom taxonomy?
At the end i will have a overview of all existing users to search them by gender, university etc. Also the admin can always add a new university for example.
So which way is the most common?
I hope you guys can help me out for my decision.
Thanks in advance | If it is an information about a user (probably displayed on on profile pages, or other user centric places), use user meta.
If it is a way to have a collection of users..... hmmm wordpress sucks in this. Best option is probably to add a relevant role.
Taxonomies in general are geared toward creating collection of content, and users are just not content, therefor while you can force some DB model that will let you use taxonomies, this is not going to be fun at all. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "taxonomy, user meta"
} |
Use the wp-admin translations on the front end
Currently I'm working on implementing the user profile form on the front end. Unfortunately the front end core translation file (`wp-content/languages/lang_LANG.po`) doesn't have any of the translated strings displayed on the user profile page. Those translated strings are located in `wp-content/languages/admin-lang_LANG.po` and since the filename starts with "admin", my best guess is that this only is loaded when visiting a wp-admin page (when `is_admin()` returns true).
Thus how do I load the text domain of wp-admin when you're not viewing a wp-admin page? | Best way around it would probably be to manually call `load_textdomain()` on the corresponding MO file in your theme's `functions.php`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "translation, textdomain"
} |
I can't install theme: theme install failed
The package could not be installed. The style.css stylesheet doesn’t contain a valid theme header.
What do you guys think went wrong? | Your theme’s stylesheet must contain a commented-out header with the theme’s name:
/*Theme Name: nameoftheme*/ | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -1,
"tags": "themes, installation, css"
} |
Users table association with users_metadata table appears broken
I noticed an issue after deploying a custom theme build to a Go Daddy Managed WordPress installation (client's request, RIP) wherein users created by the admin account in the WP back-end weren't showing up in the list of users.
They appear in the users database, but there appears to be no associated references in the `users_metadata` table (there are entries for the admin account, but that's it).
The users table says it has no primary key assigned - I'm not sure if that's part of the problem. I'm assuming that the user ID should be the primary key but clearly I'm no SQL pro here.
My client needs to be able to create users so his staff can upload content. What tree should I be barking up to fix this problem? | In the users table the primary key should be ID (auto-increment) and the `user_login`, `user_nicename` and `user_email` fields should be indexed.
In the `usermeta` table the `umeta_id` should be primary key (auto-increment) and the `umeta_id` and `meta_key` fields should be indexed. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, database, users, phpmyadmin"
} |
Stop forcing certain paths to end with a forward slash
As far as I understand, WordPress prefers a trailing slash at the end of your URL.
However, it applies this rule also to ` so I get a 301 Redirect to ` Unfortunately, Google Search Console now complains of:
> Content mismatch between AMP and canonical pages (Critical)
And my "error" is the HTTP 301 redirect for ` but the actual contents for ` How can I resolve this? For reference, my `.htaccess` for the root directory is the standard:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
I tried inserting `RewriteCond %{REQUEST_URI} !^/amp$`, but that didn't work. How should I resolve this? | The problem was not in my redirects, but instead it is a bug/lack of a feature in the existing AMP for WP plugin. The issue is described here and the bug fixes are shown here if you want to be brave and patch the plugin directly. I can vouch that this works for my root directory issue for the current `0.9.58.1` release.
If you don't feel brave, as far as I can gather from the GitHub page, this fix should appear in version `0.9.59`, which might be in a couple of weeks or so. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "redirect, htaccess"
} |
How to periodically roll back WordPress to a fixed point in time?
I have a demo WordPress site that showcases a plugin I created. The plugin lets users interact with content from the front-end and could potentially result in a nightmare of content bloat over time. I'd like to periodically roll back the entire WordPress database to a specific date or backup on a weekly basis. I have looked for plugins that do this - there are auto backup plugins, but I couldn't find any auto restore plugins. I know this is possible because I've seen it done on various other WordPress demo sites in the past. | First take a SQL dump of the database in the state you want it. Then you'd write a script that accomplishes the following:
1. Put the WP install into maintenance mode by creating a file in wp-content with the filename `.maintenance` and contents "Briefly unavailable for scheduled maintenance. Check back in a minute." (or your preferred text)
2. Drop all the tables and recreate them from your SQL dump.
3. Delete `/wp-content/.maintenance`
Finally hook your script to a cron job in the interval you're looking for. It's best if this script runs completely independently of WP using a system cron job, because there are fewer moving parts and things that could go wrong than if you're trying to do it from within a running WP environment. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp cron, backup, phpmyadmin"
} |
How to force download a plugin generated file?
I have a plugin that generates a CSV file with information from the blog. Now I want users to be able to download this file.
For example when they visit < they get the force download.
I found this solution:
add_action('template_redirect','yoursite_template_redirect');
function yoursite_template_redirect() {
if ($_SERVER['REQUEST_URI']=='/downloads/data.csv') {
header("Content-type: application/x-msdownload",true,200);
header("Content-Disposition: attachment; filename=data.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo 'data';
exit();
}
}
But that method is based on a function in the `functions.php` of the template, but how can I force download a file from a plugin perspective? | That function should work equally well if included in a plugin. `template_redirect` is an action that fires any time WP parses a URL, it's not exclusive to themes. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, url rewriting, headers"
} |
How can I use a variable to include a linked image?
I have a help page added to my admin, with screenshots of various config settings.
The screenshots are located in a subfolder (several levels deep) of the theme.
Currently, to insert linked thumbnails I'm using this...
<a href="<?php bloginfo('template_directory')?>/path_to/image.png">
<img src="<?php bloginfo('template_directory')?>/path_to/image.png"></a>
For simplicity, I'm wondering if/how I can use a $variable to set the path to the appropriate subfolder, and use it (rather than the full path).
My limited knowledge is enough to echo such an url...
$url = bloginfo('template_directory'). '/extras/config/screenshots/plugins';
echo $url;
But I don't know enough to use it to add the image and link. | You are most of the way there, you simply have to echo it into the include:
<a href="<?php echo $url;?>/image.png"><img src="<?php echo $url;?>/image.png"></a>
If you are already echoing this whole line, then you simply concatenate the variable:
echo '<a href="'.$url.'/image.png"><img src="'.$url.'/image.png"></a>'
Do some reading on PHP "concatenation" :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp admin"
} |
Remap URLs from Relative to Absolute
I'm wrapping up a port from Jekyll to WordPress and have several thousand relative URLs I need to remap so they're absolute within my posts.
**Actual URL examples:**
/gangs/gangster-disciples
/housing-projects/cabrini-green
/hoods/bridgeport
**Expected URL samples:**
Dax isn't turning up anything useful based on my search phrases and I'm not able to find any plugins or similar questions to study.
Short of writing some update queries I'm curious to know if there's a more streamlined solution available I may be overlooking, such as a plugin-based solution. What's the easiest way to remap the example relative URLs to absolute? | WP CLI is a great tool for performing common admin and maintenance tasks on a WordPress install. It has a large range of commands that among other things allow you to install plugins, regenerate thumbnails, and in your case, perform a search and replace on the database.
When migrating from dev to production I'd normally run the following command to update URLs in the database:
wp search-replace '//dev.example.com/' '//www.example.com/'
With your existing URL structure you'll probably need to include the `href="` in the search and replace string like so:
wp search-replace 'href="/' 'href=" | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "url rewriting, migration"
} |
Filtering posts by custom field value not working
I have a custom post type called Location with a custom field called City. I also have taxonomies on that post type called Specialties. The specialty filter works just fine with the `tax_query`, but I can't get the custom field to filter.
This is not working, and neither is just about everything else I've been trying:
$args = array('post_type' => 'location',
'tax_query' => array(
array(
'taxonomy' => 'specialties',
'field' => 'slug',
'terms' => $specialty,
)),
'meta_query' => array(array('city' => $location,'compare' => '=',))
); | Your `'meta_query'` value is wrong - it should be:
'meta_query' => array(
array(
'key' => 'city',
'value' => $location,
'compare' => '=',
)
);
Anyway, you don't need to use `'meta_query'` in this case where you have to filter by just **one** meta field... So for a little more optimized code, try replacing your `$args` with the following:
$args = array(
'post_type' => 'location',
'tax_query' => array(
array(
'taxonomy' => 'specialties',
'field' => 'slug',
'terms' => $specialty,
)
),
'meta_key' => 'city',
'meta_value'=> $location,
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "wp query, custom field, taxonomy"
} |
How can I exclude only a specific sub category post from category display?
It's similar to Exclude sub category posts from category display but I want it only for a specific post. This post appears in multiple categories and subcategories, but I only want it to be shown in subcategories, not categories. | Ended up doing this (if the relevant post's ID is, for example, 5):
function filter_posts($query) {
if ( $query->is_category() && $query->is_main_query()) {
$this_category = get_queried_object();
if (0 == $this_category->parent) // Category has no parent
$query->set('post__not_in', array('5'));
}
}
add_action('pre_get_posts', 'filter_posts'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, categories"
} |
Can backlinks to my site increase my chances of plugin rejection
I am creating a custom plugin. I want to add a custom support functionality in it. This will definately create backlinks for my website.
Can adding this functionality be the reason that my plugin can be rejected from wordpress | If you are not creating plugin which will put link back to your site automatically without user consent I do not see a reason why that will be problem. WordPress community can reject your plugin if it is spam or have issues with security.. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
Remove genesis_404 hook from genesis_loop
I am using the genesis theme and I want to make a custom 404 page. For that, I wish to remove the default 404 hook and implement my own. In my plugins functions.php I added my action:
add_action( 'genesis_loop', 'genesis_customizations_404' );
And in the function I added the remove:
function genesis_customizations_404() {
echo 'test';
remove_action('genesis_loop', 'genesis_404');
}
But this is not working. I also tried moving the `remove_action()` to my functions.php file, without succes. | I found a solution for this problem:
For some reason, the `add_action()` and `remove_action()` had to be contained inside another action, `genesis_meta`:
add_action( 'genesis_meta', function () {
if (is_404()) {
remove_action( 'genesis_loop', 'genesis_404' );
add_action( 'genesis_loop', 'genesis_customizations_404' );
}
}, 11); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "hooks, actions, genesis theme framework"
} |
An unwanted inline style is added to my body tag
I have made my theme and installed it on my host, but there is a problem with my body tag. it gets an automatic inline style which looks like below in **Google Chrome** :
<body style="">
And in **Safari** looks like this:
<body style="">
This causes my website show a blank space before my top menu. and It really bothers me. How can I get rid of this unwanted and automatically added inline style?
> For more information, when I delete this styling using the **_inspect element_** section of my Browser(chrome or safari) that blank space disappears. but I don't know how to get rid of that style forever. | After searching a lot, I realized that elements inside my head tag are shown inside body tag and head tag contains nothing in my generated HTML code.
This happened because I had used UTF-8-BOM encoding and by changing it to simple **UTF-8** everything was fixed. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, templates, html, css"
} |
How do I get variables from my plugin's settings page?
I am currently working on a plugin, and I want to add a settings page. I've already found out how to create the settings page, but how do I get the content from the settings page into a variable so I can use it? | Turns out it a lot simpler than I though. When you use `register_setting("something", "name")` then to get it in the plugin, just use `get_option("name")`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development"
} |
How to pass orderby params to $wpdb->prepare()?
When passing values like 'ASC' or 'DESC' to prepare like:
[...]
$order = 'DESC';
[... (the whole query)], $order); // (as a prepare param)
it doesn't work because the resulting query from something like:
[...] group_concat(p.id ORDER BY p.post_date %s)
Will be:
[...] group_concat(p.id ORDER BY p.post_date 'DESC')
While should be:
[...] group_concat(p.id ORDER BY p.post_date DESC)
How to solve? | You don’t need to use `$wpdb->prepare()` for `ORDER BY` clauses. `$wpdb->prepare()` will always quote your variables.
Supposing you receive the ordering in the request, you can prevent SQL injection by not using the user entered value at all:
$sql = "SELECT....";
if ( 'asc' == $_GET['order'] ) {
$sql .= ' ORDER BY p.post_date ASC';
} else {
$sql .= ' ORDER BY p.post_date DESC';
}
$wpdb->prepare( $sql , $value_parameter ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp query, sql, wpdb"
} |
how to output tags that has specific value in slug
How can i output tags thats has value "-en" in slug I have slug which looks like this "term1-en","term1-de" and so on. And how can i correctly only those tags that has "en" in their slug.
This what i tried so far.
$tag = post_tags();
foreach($tag as $tags) {
if(strpos($tags->slug, '-en') !== false) {
echo $tags->name;
}}; | Maybe you should re-consider your tag structure, if you must search for sub-strings, to be able to use it. Otherwise you can try e.g.
$terms = get_terms(
[
'taxonomy' => 'post_tag',
'search' => '-en',
]
);
that performs a wildcard (`*`) search for `*-en*` within the term's _name_ or term's _slug_. Also note the support for `name__like` and `description__like` input arguments.
If there are large number of tags, then obviously we don't want to fetch thousands of tags, at once. We could limit that number with the `number` input argument and also use the `offset` for paging. Hopefully the page number argument will be supported soon. The `count` argument only returns the tag count. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "tags, slug"
} |
Unable to install and upload theme due to php.ini file
Issues with uploading my theme to localhost using WAMP Server on Windows 7 Home version.
I've changed the limit to _635mb_ in the php.ini. However, there seems to be TWO php.ini files. These are currently situated:
_C:\wamp64\bin\php\php5.6.25_ AND _C:\wamp64\bin\php\php7.0.10_.
So, I changed the limit on both php.ini files (as I had no idea which one was the correct one to copy across) to the size of the zipped theme folder being 635 MB (666,161,152 bytes), and copied them both (at separate stages and overwrote) into the folder _C:\wamp64\www\lps\wp-admin_ where apparently they are to reside.
I'm trying to upload the theme _< but to no avail. The theme is Uplift_v1.3.62.
I would be extremely grateful for some advice. BTW, I restarted WAMP Server each time I changed the files. | You should upload the theme manually to the server - copy the theme folder to your system folder corresponding to this URL:
After you're done copying the files, you will get the option to preview or activate the theme in the admin:
Also, make sure you copy only the theme source folder, and not the whole documentation, with PSDs and so on. If you're not confident that is the right folder, check to see if it contains **style.css** \- that's a file that should be directly in the theme folder, not any subfolders. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "localhost, phpmyadmin, php.ini"
} |
header background color changed after drop & import database in phpmyadmin
This is what I did in phpmyadmin.
1. Export DB in .sql format
2. Drop all tables
3. Import the exported DB
The database should be same, but the website looks weird as below... how come...?
Before (black header)
 ` function, fired on admin or on frontend... So I think you can check if the update is done via the admin, then if true, deactivate the email this way...
if ( is_admin() )
add_filter( 'send_password_change_email', '__return_false' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "admin, email, password"
} |
How to wrap meta values seperated by comma in <span>?
I was able to display the single value of my custom meta field with comma separated using this code:
$ct = get_post_meta($post->ID, 'ct', true);
echo $ct;
And here's an output:
> USA, UK, China, Hong Kong
I needed the output to be:
<span>USA</span>, <span>UK</span>, <span>China</span>, <span>Hong Kong</span>
Is it possible? If so, a sample code would really help a lot or any reference you might know. | If you are storing your meta values as a single string separated by commas, you can use the native PHP `explode()` to store them in an array:
$ct = get_post_meta($post->ID, 'ct', true);
// Store them in an array
$country_array = explode(',' , $ct);
// Run a loop and echo them
foreach( $country_array as $key => $country ){
echo "<span>{$country}</span>";
echo ( ( $key < ( count( $country_array ) -1 ) ) ? ', ':'' );
}
This might cause issue if you have a value like this:
> Hong kong, China
Better yet save them as an array, instead of a single string.
Even better is to use custom taxonomy named `country`, and then use `the_terms()` to output them. This function allows you to add separator and before & after texts:
the_terms( $post->ID, 'country', '<span>', ',', '</span> ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom field, post meta, meta value"
} |
Is there any way to allow users to access content before it's published?
I have a blog and I make posts daily, and I would like for users to be able to access posts one day before they are published. How can I do that? | You can use this in a template file:
$tomr = getdate(time()+86400); //utc=gmt time in seconds, add 24 hours = 86400 seconds
$args = array(
'post_status' => 'future',
'date_query' => array(
array(
'year' => $tomr['year'],
'month' => $tomr['mon'],
'day' => $tomr['mday'],
'column' => 'post_date_gmt' //since we are using the gmt timestamp
),
),
);
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts()) {
$query->the_post();
//display post data
}
//restore original post data if it's required after this loop
wp_reset_postdata();
} else {
//no posts found
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, users"
} |
How can I make css inline?
How can I make all the css in the `twentyseventeen` theme appear inline? I already tried putting the following in header.php:
<style>
<?php include("/wp-content/themes/twentyseventeen/style.css");?>
</style>
and it did not work. | For some reason, taking out the beginning `/` solved my issue:
<style>
<?php include("wp-content/themes/twentyseventeen/style.css");?>
</style>
After doing this, I removed it because I realized how much slower it made the page load. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css"
} |
Can I place Google Fonts at the bottom of the page? I tried but it doesn't work
I'm not sure why but I tried to place Google Fonts at the bottom of the page (in the Javascript section) but it doesn't want to load the font.
What should I be looking for that might be preventing that?
My logic is that I need so speed up my site and placing the fonts at the bottom of the page I am sure will be better.... | There are various ways to accomplish this, but I think it's neatest and "most WordPress" to enqueue the fonts in your functions file, and then you can specifiy that they should load in the footer using the appropriate parameter:
function wpb_add_google_fonts() {
wp_enqueue_style( 'wpse-google-fonts', ' '', '', true );
}
add_action( 'wp_enqueue_scripts', 'wpse_add_google_fonts' ); | stackexchange-wordpress | {
"answer_score": -1,
"question_score": -1,
"tags": "fonts"
} |
Safe to remove this: <?php comments_template(); ?> when using a 3rd Party Comment App?
I am using Disqus for my comments on WordPress.
I am correct in thinking that I can remove this line or is that just plain wrong? I am referring to this:
<?php comments_template(); ?>
I am probably wrong because how else would the comments know where to load right? | From the Disqus plugin core:
// Only replace comments if the disqus_forum_url option is set.
add_filter('comments_template', 'dsq_comments_template');
Which certainly implies that Disqus uses the `<?php comments_template(); ?>` include to include it's own files, so I would advise leaving it where it is :) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "comments"
} |
Where are image paths to product category images stored in WordPress database
I am using WooCommerce I purposely deleted all my unattached image in media without realizing it was going to delete all product categories images
Luckily I have a back up database and all the images
But I cant seem to find where the path to the product categories images are being stored in the database
I looked all over
wp_termmeta
wp_terms
wp_term_relationships
wp_term_taxonomy
And it doesn't seem to be there can anyone guid me in the right direction. | Category images are stored as attachments, which is a post type. You'll find them in wp_posts with a post_type "attachment". The guid field contains the location of the image. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "database, sql"
} |
How do I get Roboto Google Font to display normal font-style?
I added the following code to functions.php to install Roboto Google Font for my WordPress website. For some reason it appears to be italic and not normal font-style when I edit the CSS property.
function google_fonts() {
$query_args = array(
'family' => 'Roboto:300'
);
wp_register_style( 'google_fonts', add_query_arg( $query_args, " ), array(), null );
}
add_action('wp_enqueue_scripts', 'google_fonts'); | What you are experience is probably issue with something else. If you try and access this link:
Directly, you can see that all the font families have a normal style. You might have another CSS rule overriding them. Check for that, and also refresh your browser's cache.
The second note is, you are only registering the styles. You have to also enqueue them using `wp_enqueue_style`. So your code should be like this:
function google_fonts() {
$query_args = array(
'family' => 'Roboto:300'
);
wp_register_style( 'google_fonts', add_query_arg( $query_args, " ), array(), null );
wp_enqueue_style('google_fonts');
}
add_action('wp_enqueue_scripts', 'google_fonts');
Right now I'm guessing you are using some other enqueued google font. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "php, functions, css"
} |
wp_embed_register_handler is not working
I used this function for other video hosts, but for some reason, now it's not working. This is the direct and embed code of the video
<IFRAME SRC=" FRAMEBORDER=0 MARGINWIDTH=0 MARGINHEIGHT=0 SCROLLING=NO WIDTH=640 HEIGHT=360 allowfullscreen></IFRAME>
and this is my registration function.
add_action( 'init', function()
{ wp_embed_register_handler(
'vidoza',
'#
'vidoza_embed_handler'
);
} );
function vidoza_embed_handler( $matches, $attr, $url, $rawattr )
{
$embed = sprintf(
'<IFRAME SRC=" FRAMEBORDER=0 MARGINWIDTH=0 MARGINHEIGHT=0 SCROLLING=NO WIDTH=640 HEIGHT=360 allowfullscreen></IFRAME>',
esc_attr( $matches[1] )
);
return apply_filters( 'vidoza_embed_handler', $embed, $matches, $attr, $url, $rawattr );
}
I am not able to get it to work. | You are trying to match the `r2jeim68kuq6.html` part, but you're not allowing dots in your regex pattern here:
'#
You can try e.g. (removing the `A-Z` too because of the case-insensitive `i` search):
'#
if `.html` is a standard extension and where you also adjust the iframe source to:
src="
Hope it helps! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "embed, oembed"
} |
Can I use Symfony components in a plugin that I want to submit to the WordPress plugin repository?
Can I use Symfony components in a plugin that I want to submit to the WordPress plugin repository?
I do not want to be rejected because of the license. | Yes, Symfony components are licensed under MIT these days. They are compatible with GPL, which is a requirement of the official WP repository.
Do note that as number of plugins using common PHP components is increasing, so does possibility of version and other conflicts between them. Since WP lacks dependency management, at some point you might have to handle such issues yourself in your plugin. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, plugin development, plugin recommendation, licensing"
} |
Taxonomy Relationships
I've created two taxonomies:
* Make
* Model
This is for a CPT Vehicles. It goes without saying, Make would be your make (Honda / Toyota / Ford / etc) and then one would select the Model based on the Make.
How do I setup the relationship between Make and Model? Or have I gone about this all wrong and it should in fact be a single taxonomy 'Make & Model'?
Im not looking for:
Vehicle CPT
|-> Make
|-> Model
Im looking for:
Vehicle CPT
|-> Make
|--> Model | Taxonomies are not child of each other unlike terms, which can be. Take a look at this flowchart:
` function at the codex, and register your taxonomy as hierarchical, then create sub taxonomies as model. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom taxonomy, taxonomy"
} |
Trying to load different syles for 404.php page
I've created a `404.php` page and my theme correctly loads that page when an error is made. My question is - how do I style it? I notice that the body tag like this:
<body class="error404">
So should I call that in an enqueue to load some css, perhaps something like this:
// Error 404
if ( is_page(404)):
// Load Newsletter Main CSS
wp_enqueue_style( '404 css', get_template_directory_uri() . '/css/404.css', array(), null);
endif;
My question is - how should I associate the `404.php` page with a css stylesheet?
Thanks | You have 2 options here.
## Use Built-in Classes
As you already mentioned, WordPress automatically adds classes to body, based on the current page. You can use it to style your elements differently, or even use your own different classes in your `404.php`:
.error404 p {
// Some different classes here
}
## Enqueue Your Styles Only for 404 Page
You can check whether the page is a 404 error or not, and then enqueue your styles:
add_action('wp_enqueue_scripts','enqueue_my_script');
function enqueue_my_script(){
if( is_page_template('404.php') ){
// Enqueue your style here
}
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "wp enqueue script, 404 error, wp enqueue style"
} |
Decrease stock quantity when a variation is sold using Woocommerce
I am sure I must be something wrong or omitting the correct way to do it, but each time I sell a variation of my product, the stock decreases for that variation, but the total stock value for the mother product remains the same. Is there any way I can decrease the global stock of the product each time a variation is sold? Thanks in advance for any tip in the right direction | In a variable product, stock management works only for the variation, not for the main product. So you should disable 'Manage stock' in the 'Inventory' tab and use only the one IN the variation. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "woocommerce offtopic"
} |
How can I display a list of only categories which are marked as 'featured' in the backend?
I am trying to find a way to mark certain categories in the backend with some sort of 'featured' flag. I would then retrieve those selected categories and display them on a page.
I couldn't find any featured category plugin which does this; I'm wondering if there is a simple way to do this in WP core.
Note: I don't want featured category index pages, widgets, category images, etc. I simply want to be able to check a box (or similar) next to certain categories, so they are marked as special. Then I need to create a query to retrieve only those.
Is this possible? | Yes! Register a taxonomy.
I usually call it something like "Promotions." (this allows for more to be added easily in the future) From there, create the term "featured."
In your template, uses `wp_query` to display your featured articles, taxonomy parameters | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, categories, taxonomy"
} |
Rewrite rule not redirecting correctly
I'm using the `Rewrite Plugin` from the Wordpress plugin site here: Wordpress Plugin Page
I'm trying to get the following URL `homes-for-sale-details/4420/217007490/177/Fb-landing-page` to pull up a custom PHP page in the subdirectory `propertylisting1`. So this is my rule:
`^homes-for-sale-details/4420/217007490/177/Fb-landing-page(.*)$`
And I have it redirecting to `propertylisting1/index.php`
It seems to work because when I go to that URL it actually detects it, but it doesn't display the page I want it to display, it redirects me to the home page, completely redirects me.
$ propertylisting1/index.php?success=$1
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
As you'll notice, I had to place it in-between the conditions for not found, and the base rewrite rule.
This way works perfectly fine and doesn't break any of Wordpress' own rules in the process. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "url rewriting, rewrite rules"
} |
Function for widget titles
I am trying to get a function working with a conditional statement if that is possible. I can get the function working without the statement..I need it to determine whether or not the widget title is empty and if it is, to ignore the function, if it is not, it should use the function below. This function will insert an image as the title using the prefix title_(imagename).png
Thank you!
`function html_widget_title( $title ) { $output = '<img src="/images/title_'.$title.'.png" alt="'.$title.'" title="'.$title.'"/>'; return $output; } add_filter( 'widget_title', 'html_widget_title' ); ` | You can modify your filter function to add the condition:
function html_widget_title( $title ) {
if ( '' != $title ) {
$output = '<img src="/images/title_'.$title.'.png" alt="'.$title.'" title="'.$title.'"/>';
return $output;
} else {
return $title;
}
}
add_filter( 'widget_title', 'html_widget_title' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets"
} |
How to have two galleries side by side?
I have two galleries on one page, but one is on top of the other. How can I make them appear side by side? I need them to stay as two different galleries, so combining them isn't a solution. | Assign each of those 2 galleries a div and in the css add:-
.gallery-1 {
width: 48%;
float: left;
}
.gallery-2 {
width: 48%;
float: left;
position:relative;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "gallery"
} |
How to exclude authors from get_pages()
I am trying to filter the results for the wp_dropdown_pages function by author, here is what I have so far.
$dropdown_args = array(
'post_type' => $post->post_type,
'exclude_tree' => $post->ID,
'selected' => $post->post_parent,
'name' => 'parent_id',
'show_option_none' => __('(no parent)'),
'sort_column' => 'menu_order, post_title',
'echo' => 0,
'authors' => '-11',
);
wp_dropdown_pages( $dropdown_args );
When I try this the dropdown does not show up, what am I doing wrong here? | <
this function does not take exclude author args. If you want to exclude a specific author and want to display all pages. Then you can do this easily by `WP_Query`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, wp admin"
} |
Edit Parent page drop menu when creating a page
Please can someone tell me how to remove all items from the 'Parent' drop down when creating a page apart from a few items? (Loop through and remove all that are the ones I want). | You can use the page_attributes_dropdown_pages_args filter to remove whatever you want. It's based off of the wp_dropdown_pages() arguments so you can use the `exclude` parameter to remove certain pages or a fake parent to remove all the pages:
/**
* Filter the arguments of Page Attributes Parent Dropdown
*
* @param Array $args - List of wp_dropdown_pages() arguments
* @param WP_Post Object $post - Current post object
*
* @retun Array $args - List of wp_dropdown_pages() arguments
*/
function admin_page_attributes_meta_filter( $args, $post ) {
$args['exclude'] = array( 1 ); // Exclude page ID 1 from the dropdown list
/*
* Uncomment to exclude all pages
* $args['child_of'] = -1;
*/
return $args;
}
add_filter( 'page_attributes_dropdown_pages_args', 'admin_page_attributes_meta_filter', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "pages, metabox, page attributes"
} |
Beginner's question about shortcodes
I know i'll get bombarded for this question but the truth is I researched and found nothing.
I'm not a WP expert or anything, i just found my ways to design WP themes. But there is something i never got straight.
**_WHY IN HECK SHORT-CODES DON'T WORK FOR ME._**
When i mean shortcodes i mean the ones provided by a plugin, not created by myself what it makes it probably dumber.
**Example:**
I write in a page or a post:
[audio src="
I see the audio controls in the WP editor, but in the browser i see the text, not the audio.
**2nd example:**
I just tried to use a WPForms shortcode in order to display a contact form.... I see the text, not what the shortcode should be doing.
Up to this point my solution if I need to run a shortcode is creating a page/post template and do:
<?php echo do_shortcode('[My_shortcode]'); ?>
Thanks a lot and sorry for the dumbest question. | It looks like theme issue. Switch to default WordPress theme and check it. I have tested it on WordPress Twenty Seventeen theme.
For testing:
1) Add below code in theme `functions.php`
// Sample shortcode [testme]
function testme_cb( $atts ) {
return 'Working? Maybe.';
}
add_shortcode( 'testme', 'testme_cb' );
// Enable shortcodes in text widgets
add_filter('widget_text','do_shortcode');
* * *
2) Goto `Appearance -> Widgets` and add shortcode `[testme]` in Text Widget.
 Check it on frontend.
 or _e() as per requirement. Now in future to avoid others in my team to add strings without making available for translation(bare strings), I want to add a code that runs may be on pushing the code(in my git repository) and throws exception mentioning the bare strings. | There is no way to know if string should be translatable or not (should a `'fail'` in a json response be translatable?). Some things just need proper code review and can not be automated. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, translation, localization, parse, xgettext"
} |
Get specific value from variable to use in query
I would like to create a custom query where the post ID is equal to a value which is stored in a variable. If I do a var_dump of the variable I can see the ID that I want to use.
However I don't know how I can target that specific ID and use it in my query. I'm really new to this more advanced PHP work and I'm probably searching with the wrong search terms to get the answer.
This is a part of the var_dump of the $account where the ID is 164.
object(WP_Post)#4451 (24) { ["ID"]=> int(164)
This ID should be used within the query to target the specific post ID like:
$args = array(
'post_type' => 'account',
'p' => $account->ID,
);
Can this be done? And if so, how can alter the query to do this?
Edit: Updated the query above with the correct code. Also updated the right variable name in the original question.
Thanks in advance. | Very simply use `get_post()`...
$my_post = get_post( $account->ID ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, variables"
} |
Enque script based on url paramater
I'm using the following to enqueue a script in admin.
function add_admin_scripts( $hook ) {
global $post;
if ( $hook == 'post-new.php' || $hook == 'post.php' ) {
if ( 'custom' === $post->post_type ) {
wp_enqueue_script( 'myscript', get_stylesheet_directory_uri().'/js/custom.js' );
}
}
}
add_action( 'admin_enqueue_scripts', 'add_admin_scripts', 10, 1 );
But I want to enqueue when `action=edit` is in the URL parameter.
>
Is this possible? | There are a couple of ways to do this. The easiest way is to use `$_GET`:
if ( ( $hook == 'post-new.php' || $hook == 'post.php' ) && $_GET['action'] == 'edit' ) {
// Enqueue your scripts here
}
You can also use the `get_current_screen();` function instead of using a global variable. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp admin, actions, wp enqueue script"
} |
Dropdown menu not displaying Wordpress
A customer has just complained that they're unable to select sizes of a product. Upon looking the drop down menu isn't working.
<
It's happening in the backend too when I go to click the dropdown to change the heading too!
I've checked and there is no CSS blocking this.
Not sure what's happening here! | This is a CSS issue not related to WordPress maybe to Woocommerce, try adding:
.select2-container{ z-index:10000; }
the number seems high but i tried different ones thats the one that works.
 | The filter you are looking for is `save_post`. This filter is triggered each time you save a post.
add_action( 'save_post', 'my_function' );
function my_function( $post_id ){
// Do your stuff here
}
This filter passes the post's ID to the callback function, so you have access to everything you need. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "filters, admin, actions"
} |
Modify query posts
I don't want to use pre_get_posts.
$args = array(
//'posts_per_page' => $posts,
'post_type' => 'post',
'post_status' => 'publish',
'paged' => $page,
);
Now I want to modify `posts_per_page` to do that I have done
$args['posts_per_page'] = 3,
Finally `$query = new WP_Query($args);` But no luck. Should I use pre_get_post? | You have php syntax error. Anyway you can both use
$args['posts_per_page'] = 3;
or
$args['posts_per_page'] = array('3'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query"
} |
Giving my members privet data!
I sell Services on my website, usually after people pay me and I confirm their payment I sent them the data that require for using my APP it's like username and password and list of servers that they can use. I send them these info by e-mail, is it possible to build login area to make these info privet in their login area! or is there any plugin for that? | If you want you can do that. Have a dashboard build for each user using WordPres.
There are plugins which can atleast get you started:
<
<
Now create a template where you display your services as per the payments. Also make sure you have a login criteria added the template. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugins"
} |
How to apply a custom skin to WP_Editor / TinyMCE?
I'm trying to apply a skin to a custom `wp_editor()`, but it does not seem to apply whatever I do.
The skin is generated from the TinyMCE LESS files, per instructions on <
In my theme's folder I have a folder called `/css/tinymce` containing the following files:
> _content.inline.min.less_
>
> _content.min.less_
>
> _skin.min.less_
This is how I'm calling wp_editor, with the `skin_url` setting for TinyMCE, but it does not seem to apply the skin.
$settings = array(
'media_buttons' => false,
'textarea_rows' => 1,
'quicktags' => false,
'tinymce' => array(
'toolbar1' => 'bold,italic,undo,redo',
'statusbar' => false,
'resize' => 'both',
'paste_as_text' => true,
'skin_url' => get_template_directory_uri() .'/css/tinymce'
)
);
echo wp_editor('', 'custom_editor, $settings); | Apparently, the default WordPress style files overwrite a custom TinyMCE skin. So what you need to do is deregister WordPress's TinyMCE skin.
Since I needed the custom skin to only apply on the front-end on my website, I wrapped it inside an `!is_admin()` conditional.
function remove_editor_buttons_style() {
// If not on wp-admin
if ( !is_admin() ) {
wp_deregister_style( 'editor-buttons' );
}
} add_action( 'wp_enqueue_scripts', 'remove_editor_buttons_style' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "tinymce, wp editor"
} |
Should I always prefer esc_attr_e & esc_html_e instead of _e?
I am working to internationalize my plugin. As I can see on Wordpress site about esacaping, it says you should always use it. But as I can see in many popular plugins, they have used _e instead apart from few specific cases. So should I always use escaping or not for all strings, if not then for what specific cases should we use it? | Always escape output unless you have a **great** reason not to.
The main thing that you lose when escaping translated strings is the ability to use html tags and html entities in the original string and translations, but you should probably not get into a situation in which translators are required to know html just in order to translated several words in the first place.
If for whatever reason you have to include an html entity as part of the string you can use `printf`/`sprintf` to give the translator some flexibility on the location of such an entity in string with something like
`printf('%s&%s',esc_html__('first part','td'),esc_html__('second part','td'))`
where `&` is just an example for an html entity.
Obviously there might be more complex scenarios that might be impossible to escape in a sane way, but your guiding light should be to always escape by default. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin development, translation, localization, escaping"
} |
Hooking into the init action will fire it too frequently?
> " _Note that I don't recommend hooking the **add_custom_rewrite_rule** into the **init** action as it will fire too frequently. This is just an example. A better place to apply the function would be on theme activation, plugin activate, perhaps the save_post action, etc. Depending on what you need to do, you may only need to fire it once or just a few times._"
I found this recommendation here. In my WP installation I use a third part plugin that is hooking into the **init** action to change a custom post type slug. Is this a problem? | It really depends on your situation. Whenever you add a rewrite rule and flush the permalinks, it will stay there till the next change/flush of the permalink's settings.
If it's vital for your rules to exist, you can check if it exists on init, and then add it if it's not there. Take a look at this answer to get a glimpse of how to check if a rewrite rule exists.
If it's not really necessary for your rules to exist ( for example, you are just doing it for SEO purpose ), you can hook into another action that doesn't run each time a page loads, such as plugin activation. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "hooks, actions, rewrite rules, customization"
} |
Excerpt isn't working or am I missing something?
I thought that by default when you loop content (like blog posts) in a WordPress the content is limited to 55 characters. I have not touched my functions.php file yet for when I loop the posts the article/ content is published in full.
My loop is like this - should the content tag be different?
<?php
if( have_posts() ):
while( have_posts() ): the_post(); ?>
<h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
<p>Posted on: <?php the_time('F j, Y'); ?> <?php the_category( ', ' ); ?></p>
<p><?php the_content(); ?></p>
<hr>
<?php endwhile;
endif;
?>
Thanks for all help. | No it's not. The length limit is for excerpt, which should be called manually. To get the excerpt in your loop, you should use:
<p><?php the_excerpt(); ?></p>
Instead of:
<p><?php the_content(); ?></p>
If you thought of this because of the option in the reading section of settings:
.
Is there some way I can mass select just the recently imported posts? Or some way I can programmatically do this is I know the post's database ID? (since all the imported posts are the most recent items in the database, I can get their IDs pretty easily). Is there a way I can, at import time, say "put all the posts you're going to import into this category"? Is there some solution I'm not thinking of | It's not a super sexy solution, but I ended up installing the Reveal IDs plugin, which let me sort by ID. Then, using _Screen Options_ , I maxed out the number of posts to display until all the recently imported items were showing. This allowed me to make a mass edit on the posts to drop them into the new category I wanted.
Unfortunately, by default, Apache and PHP didn't like the super long POST urls that resulted. I also had to (temporarily) max out a few URL related apache config variables.
# Apache Configuration
LimitRequestLine 40000
LimitRequestFieldSize 40000
and a similar PHP ini setting
max_input_vars=40000
Once I made my edits I removed these variable customizations to prevent future DDOS style abuse of my system. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, import, tumblr"
} |
wp_enqueue_style specifics for overwriting plugin styles
I'm trying to add some custom CSS to dictate a very small part of a plugin's look. I don't want to dequeue the whole think (I don't think) as I'm happy with the rest of it.
I found this answer here which would appear to be exactly what I need: <
However I'm new to WP and I have not even the faintest idea of where I would put that second lot of code.
wp_enqueue_style(
'my-styles',
get_template_directory_uri() . '/mystyles.css',
array('plugin-style-handle')
);
Can anyone point me in the right direction? | Put this code in your current active theme **function.php** file.
function wpdocs_theme_name_scripts() {
wp_enqueue_style('my-styles',get_template_directory_uri() . '/mystyles.css',array('plugin-style-handle'));
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugins, css, wp enqueue style"
} |
Loop inside query
I have an array to store taxonomy and term for query, but I can not use foreach to loop my array inside my tax_query. I got 505 internal.
$query = array(
'post_type' => $post_type,
'posts_per_page' => -1,
);
$query['tax_query'] = array(
'relation' => 'OR',
foreach($taxonomy_arr as $t):
array(
'taxonomy' => $t[taxonomy],
'terms' => $t[value],
'field' => 'slug',
),
endforeach;
);
the foreach or the query works fine on its own but does not work when I loop inside. Please give me advice. Thanks | This is a PHP syntax error - you can't nest a `foreach` _inside_ an array, you use it to _build_ the array:
$query = [
'post_type' => $post_type,
'posts_per_page' => -1,
'tax_query' => [
'relation' => 'OR',
],
];
foreach ( $taxonomy_arr as $t ) {
$query['tax_query'][] = [
'taxonomy' => $t['taxonomy'],
'terms' => $t['value'],
'field' => 'slug',
];
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "loop, query"
} |
How to hook into creating a category?
I want to do some stuff when a category is created the only hook i could find is
add_action( 'edited_category' , 'custom_term_saved', 10, 2 );
but it is only called on edit form saved not on create form saved | There is a hook that can be used for any taxonomy, `create_{$taxonomy}`, which in your case, is a category. So, it would be `create_category`:
add_action( 'create_category', 'my_function', 10, 1 );
This is triggered by `wp_insert_term()` at line 2142. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, hooks"
} |
Hide Price on one specific Woocommerce Single Product page
I need to hide the price on 1 specific Woocommerce Single Product page. I have tried a couple different code snippets I found but I am doing something wrong and nothing so far has worked. Can anyone give me the correct code to do this? | Use `woocommerce_get_price_html` filter hook this way:
add_filter( 'woocommerce_get_price_html', 'hide_price', 99, 2 );
function hide_price( $price, $product ) {
if ( 'your_product_slug' === $product->get_slug() ) {
$price = '';
}
return $price;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "woocommerce offtopic"
} |
User Directory without a Plugin
_GOAL:_ Develop a password-protected user directory without a membership plugin. The login credentials are the same for everyone.
_QUESTION:_ Will this strategy keep the info private, or am I missing something?
1. Create a custom post type with options:
'public' => true,
'has_archive' => false,
'exclude_from_search' => true,
'publicly_queryable' => false,
2. create a password-protected page with a custom page template, displaying the custom post type query (the list of addresses).
3. add a password form to the custom page template, like so:
global $post;
get_header();
if ( ! post_password_required( $post ) ) {
// …
} else {
echo get_the_password_form();
}
Additional Notes:
* Custom Post Type paired with Advanced Custom Fields will set up fields for address, phone numbers, names, etc.
* An editor (or two) will keep the directory up to date | You might want to read this post about passwords protected posts. In short: Do not use them.
> QUESTION: Will this strategy keep the info private, or am I missing something?
No, it won't. It will even leak info to search engines and index those.
What you _can_ do is to just require the actual _user login_ in your template:
// @link
if ( ! is_user_logged_in() ) {
// @link
wp_login_form();
// "outer template"
wp_footer(); # etc.
return;
}
// Other template code | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "login"
} |
URL issue after migrating to dev site
I recently migrated a live wordpress site, watershedgeo.com, over to a development site using the temp url, <
I finally got it launched but the images and links don't show, they're all broken, but a lot of the images are showing their alt text. Here's the weird thing:
If I inspect the images in chrome, they show the temp url as the src of the image, but if I change the root before wp-content to watershedgeo.com, they show up. However, if I inspect the images on the live site, they show the source as <
Is there a plugin or a way that I can change it so all the images use 1qy8tt40p7n9v7tao3knw537.wpengine.netdna-cdn.com as the root so the images can show for development? All folders match, it's just the root that needs to be changed
The temp url is what is in the site url for the database and the wp-config.php file. | Although you can use phpMyAdmin to dig into the database to change things, I always use the WP Clone plugin to easily move a site from development to production. Install the plugin on both source and target systems, then backup the source, and restore to the target. It's here < .
Everything is moved for you, with URL adjustments, and other stuff done for you. Easy peasy.
Of course, you can do it more 'manually', but the plugin works well and fast for me (being somewhat lazy). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "urls"
} |
Filter posts by multiple custom taxonomy terms using AND operator in REST API v2 (WordPress)
I've created a custom post type called 'events'. I've also created a custom taxonomy called 'event_categories' containing the 12 months of the year.
I am trying to get 'events' held in August AND (not OR) September (term IDs 41 and 42) using the following urls:
`/wp-json/wp/v2/events?event_categories=41,42`
`/wp-json/wp/v2/events?event_categories=41+42`
For some reason these urls return the same results and don't use the AND operator. They both use the OR operator and return events that are in either August or September.
I've also tried the following urls below but neither utilise the AND operator:
`/wp-json/wp/v2/events?filter[event_categories]=august,september`
`/wp-json/wp/v2/events?filter[event_categories]=august+september` | I think I know the fix. I noticed that the plus sign (+) in the url arguments was automatically being stripped and converted into a space.
My arg values 'august+september' were becoming 'august september' after decoding. I found out that '%2B' is the code equivalent of the + symbol.
So, instead of using: `/wp-json/wp/v2/events?filter[event_categories]=august+september`
Use: `/wp-json/wp/v2/events?filter[event_categories]=august%2Bseptember` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 5,
"tags": "rest api, multi taxonomy query"
} |
How to hide sensitve page from google spiders and non-membres in wordpress!
I have a page that contain all my servers data, it really sensitive information. Is there any strong way to hide it from google spiders and non login users.
I found small solutions that's hide the page, but not secured at all, if someone search in the website directory he will get access to that page easily. Any hints here?! | Use password protection mechanism
Alterative you can use wordpress hook in your theme to show your post/page only for administrators this way:
add_action('wp', function() {
if(is_page('my-data') && !current_user_can('manage_options'))
die("123")
});
Note: don't use this code. It is just for demonstration. Better use hook `template_redirect` or something else.
We need more info about your environment to answer more specifically.
Perhaps the best option for you would be set password by http-server. For apache using .htacces with something:
AuthType Basic
AuthName "restricted area"
AuthUserFile .htpasswd
require valid-user | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "seo"
} |
Using URL rewrite to add custom URL for custom post type
I'm using ACF to make a multilingual site. My custom post URLs must work both with and without `/en/` as prefix. E.g. `mysite.com/posttype/any-slug/` and `mysite.com/en/posttype/any-slug/` must display the same post.
I've tried using this rewrite rule in functions.php (and some variations of it), but have trouble getting it to work:
add_action('init', 'add_my_rule');
function add_my_rule() {
add_rewrite_rule('^en\/posttype\/[.+]$','index.php?pagename=$matches[1]','top');
}
I've noticed there's other questions with similar titles, but the cases seem to be different from this one. | `pagename` assumes the `page` post type. You need to use the custom post type query var in your rule instead. Presumably you also want to detect that this is a request for `en`, you can add your own rewrite tag to store that, then add that to the rule:
add_action('init', 'add_my_rule');
function add_my_rule() {
add_rewrite_tag('%my_language%', '([^&]+)');
add_rewrite_rule(
'^en/posttype/([^/]*)?/?$',
'index.php?posttype=$matches[1]&my_language=en',
'top'
);
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "url rewriting, slug, rewrite rules"
} |
Exclude pages with certain template from wp_list_pages
Before you mark this as duplicate I have tried every method in all the other questions and non of them have worked.
I am trying to exclude any page with the page template page-noindex.php from the wp_list_pages(); query.
The below code does not work and when I echo out $the_query it just displays 'Array'.
<?php
$the_query = array(
'post_type' => 'page', /* overrides default 'post' */
'meta_key' => '_wp_page_template',
'meta_value' => 'page-templates/page-noindex.php'
);
$args = array(
'exclude' => $the_query,
'title_li' => '',
'sort_column' => 'menu_order, post_title',
'post_type' => 'page',
'post_status' => 'publish'
); ?>
<?php wp_list_pages($args) ?> | Daniel, `exclude` parameter doesn't accept array.
Use your code this way:
$exclude = [];
foreach(get_pages(['meta_key' => '_wp_page_template', 'meta_value' => 'page-templates/page-noindex.php']) as $page) {
$exclude[] = $page->post_id;
}
$args = array(
'exclude' => implode(",", $exclude),
'title_li' => '',
'sort_column' => 'menu_order, post_title',
'post_type' => 'page',
'post_status' => 'publish'
);
wp_list_pages($args);
I think you can refactor it better for your needs | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, templates, page template, wp list pages, exclude"
} |
How to remove the author pages?
I submitted my site to Google and now the author page is showing up in the search results.
How do I prevent my and others author names from showing up in search results?
It would be best to disable completely the path "/author/" all together because it's not a blog but a product site (it only has pages).
I did a search earlier and saw that there are plugins to do this but I'd rather not install a plugin (sometimes they are not updated) if there is another way but will if I have to.
I also searched through the source code of the pages and did not see any links to the author page. | The above answer is good, but if redirecting to home page, it should specify a 301 status and exit after.
add_action('template_redirect', 'my_custom_disable_author_page');
function my_custom_disable_author_page() {
global $wp_query;
if ( is_author() ) {
// Redirect to homepage, set status to 301 permenant redirect.
// Function defaults to 302 temporary redirect.
wp_redirect(get_option('home'), 301);
exit;
}
}
wp_redirect() documentation < | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 21,
"tags": "author"
} |
Does WordPress store the username as a primary key in the database?
Does WordPress store the username as a primary key in the table in the database? I'm wondering why WordPress prevents admins from changing their username and this is the only thing I can think of.
PS There are many valid reasons to change a username. For example, the easy install program created a WordPress install and used the default username "admin". | WP is not likely going to add this feature...
From < the main reason given by Nacin is:
> This is a caching issue. Additionally, it also breaks URLs and such, which is why I don't think administrators should be able to do it either. Seems simple enough to relegate to a plugin, or a straight DB edit. Suggesting wontfix. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "database, users"
} |
responsive screen not working
i already try to make this responsive like this: < i want it like shrink like an image, whatever screen in it, it will match in the position, imagine i put in every box image, but seems fail. < | To get responsiveness similar to the image link you gave, you need to set `width=100% and height=auto` for the image.
In your jsfiddle example, you did the width part okay (defined it as a % of available space) **but** you are fixing the height - both for the outer box as well as the inner boxes. So no matter what you do, the height will stay the same. That will give distorted images when scaled.
So if you want responsively scaled images,
* Define one of the two (height or width) as a % of available space (you did this right)
* Define the other as auto - so that it scales properly
* Adjust the rest of the design to suit (so that other elements don't walk out of your layout). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "customization, css, responsive"
} |
How to make container class in PHP
so, i have this part of code from a custom_functions.php that has classes, now i want to make a container to those classes, but i do not know how to do that in php.
if ($slide_title) {
$strret .= '<a class="'.$slide_linkurl.'"><h2>'.$slide_title.'</h2></a>';
$strret .= '<p>'.$str.'</p>';
$strret .= '<a href="'.$slide_linkurl.'" class="da-link">'.$slide_linktext.'</a>'; | You can do this using below code.
if ($slide_title) {
$strret .= '<div class="container">';
$strret .= '<a class="'.$slide_linkurl.'"><h2>'.$slide_title.'</h2></a>';
$strret .= '<p>'.$str.'</p>';
$strret .= '<a href="'.$slide_linkurl.'" class="da-link">'.$slide_linktext.'</a>';
$strret .= '</div>';
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, functions, css"
} |
Contact Form 7 in Multisite
I am using wp engine for my WordPress multisite project.
I created a Contact form using contact form7 in one site, the contact form not reflecting in another site, do I have to setup any configurations.
I want to get all submitted contact form details at a single place for that I am using "Contact Form Advanced Database". | The only thing that multisite networks share are users, Contact Form 7 forms will not be shared between sites. You will need to create a new form in each site | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "multisite, plugin contact form 7"
} |
Check get_post value after wp-admin login
I want to check get_option value after login to wp-admin.
I have save the date in get_option. I want to check if value in get_option is same as current date after wp-admin login.
if same then i want to show admin notice.
Everytime when i logged in to wp-admin it checks the get_option value.
Here is my code for admin notice. **I have no idea how can i check the get_option value after wp-admin login.**
function sample_admin_notice__success() {
?>
<div class="notice notice-success is-dismissible">
<p><?php _e( 'Done!', 'sample-text-domain' ); ?></p>
</div>
<?php
}
add_action( 'admin_notices', 'sample_admin_notice__success' );
Any help would be appreciated. | You just use a normal if statement around the notice so that it only appears if the value of your option matches the current date.
function wpse_277689_admin_notice() {
if ( get_option( 'expiry_date' ) === date( 'd/m/Y') ) :
?>
<div class="notice notice-success is-dismissible">
<p><?php _e( 'Done!', 'sample-text-domain' ); ?></p>
</div>
<?php
endif;
}
add_action( 'admin_notices', 'wpse_277689_admin_notice' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, wp admin, hooks, login, actions"
} |
Why doesn't my insert query work?
I'm trying to insert to the table in my wordpress database but for some reason it's failing all the time.
$table_name = $wpdb->prefix . "wp_list_press";
$res = $wpdb->replace( $table_name, array(
'pr_id' => $da,
'pr_title' => $t,
'pr_link' => $str,
'pr_date' => $date,
'pr_text' => $tx,
'pr_desc' => $desc,
'pr_image' => $im,
'pr_pdf' => $pd,
),
array(
'%d',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
));
if ( $res ) {
print( "Success" );
} else {
print( "Failed" );
} | You have the following for the table name: `$wpdb->prefix . "wp_list_press"`
Check your actual prefix and table name. In a WP installation using "wp_" as the prefix, the above would result in "wp_wp_list_press". Is that the table name in the db or is it just "wp_list_press"?
If the table in the db is "wp_list_press" then the above should be `$wpdb->prefix . "list_press";`
Not sure if this is contributing to the issue or not, but your data array has fewer elements than your format array. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wpdb"
} |
Auto-detect the redirect url from the original url
is there any way to get the redirect url in PHP when all you have is the origin url? For example: \- You create an article that has a slug of `test-redirect`. \- Inside the article editing screen you change that slug to `test-redirect-new` If all you have is ` is there some function in which you can pass ` and get back ` Is there any way to access it via wp_remote_get? Thanks in advance for any help you can provide. | You can simply write your own function this way:
function get_old_link($url) {
global $wpdb;
// get only url path
$parse = parse_url($url);
$path = trim($parse['path'], "/");
// get last part as slug
$arr = explode("/", $path);
$slug = end($arr);
// find post id by meta_key and meta_value
$row = $wpdb->get_row("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_old_slug' AND meta_value = '{$slug}'");
if(!empty($row->post_id))
return get_permalink($row->post_id);
}
Note: it is possible to make this function better. I only want to show you the direction. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "redirect"
} |
How do I conditionally enqueue script for CPT single post type with plugin?
I'm writing a plugin that defines its own CPT "properties" and I want to enqueue a script specifically in single posts.
It runs without my attempt at a conditional statement just fine but I don't need it to load on every page so I'd like to make this conditional.
This code is in my plugin root just after my includes.
if ( 'properties' == get_post_type() ) {
if (wp_script_is('owl.carousel.js', 'enqueued')) {
return;
} else {
wp_register_script('owl.carousel.min.js', plugin_dir_url(__FILE__) . 'js/owl.carousel.min.js');
wp_enqueue_script('owl.carousel.min.js');
}
}
I've also tried `is_sigular('properties')` but that didn't work either.
I must be missing something silly... | Make sure your code runs in `wp_enqueue_scripts` action hook.
Also checkout your script handle `'owl.carousel.js'`. In `wp_script_is()`, it is not the same than in the 2 later functions in which you enter it as `'owl.carousel.min.js'`.
add_action( 'wp_enqueue_scripts', 'enqueue_properties_scripts' );
function enqueue_properties_scripts() {
if ( 'properties' === get_post_type() ) {
if ( wp_script_is( 'owl.carousel.min.js', 'enqueued' ) ) {
return;
} else {
wp_register_script( 'owl.carousel.min.js', plugin_dir_url( __FILE__ ) . 'js/owl.carousel.min.js' );
wp_enqueue_script( 'owl.carousel.min.js' );
}
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "plugin development, wp enqueue script, conditional tags"
} |
Front end post editor which is actively developed
I'm trying to find a simple editor for posting content from the front end of a community site.
I will only need to submit one post type (defined in the site configuration) and posts will contain text and images only.
I have seen numerous front end editors, but they are either not supported anymore or cost a fortune.
Can anybody suggest a front end post editor which is still receiving updates in 2017? The closest I found to what I'm looking for was Raptor, but that is not longer available.
Any help would be appreciated. | You can use default wp_edtior in your templates to give opportunity your users posting content.
This forum is not good place to find turnkey plugin | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "front end"
} |
I'm having a problem viewing the Youtube video
I'm having a problem viewing the Youtube video.
In my single-custom I am using:
<? Php
echo wpautop ($post-> post_content);
?>
And when I put the Youtube link he is not showing the video but only his link.
What could be wrong? | You should use the_content function to process embeds. Another way is to apply the_content filter.
apply_filters( 'the_content', $post->post_content' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "single, youtube, post content"
} |
CSS added through customizer neglects the need of a child theme?
Many developers know that if you change the style.css of a theme, and then the theme gets updated, your changes will be deleted.
The traditional solution for that is creating a child theme inheriting everything from the parent theme, while changing the child theme's CSS.
But what about a case when I change the CSS of a theme from Wordpress itself, as can be done from the Wordpress customizer?
Will this CSS also be changed if the theme is updated? I would bet it won't 99.99% but it wasn't clear from any documentation I've read so far. | The mods you enter into the Customizer are kept safe over upgrades, as they are saved into the database. But styles are not the only reason for a need of a child theme. Often you need to add functions/hooks and several other customiziation which - in that case - need a specific child theme. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, customization, css"
} |
Duplicator live to wamp https to http
sorry for my english... So I want to get my data from a https live site back to localhost. Using duplicator plugin works fine exept that I run (especially in Chrome) to a problem with absolute setted image links, wich refer to < ... .
I wonder if someone is out there who knows a solution for this issue.
Many thanks in advance | Try to edit your `wp-config.php` and add the lines:
define('WP_SITEURL', '
define('WP_HOME', '
with https or http. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugins, database, migration, https, http"
} |
what is the difference between uri and path?
I am new in WordPress theme development and I've got a problem! what is the difference between get_theme_file_path() and get_theme_file_uri()? both of them return the same thing! | The function `get_theme_file_uri` returns http url like
The function `get_theme_file_path` returns file system url to file as
/home/mysite/www/wp-content/theme/... | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 0,
"tags": "theme development"
} |
Creating an .ics calendar subscription service with wordpress
At the moment I just have a static page with a link that when clicked will download all the events I have on my .ics file to a phone's calendar. Ideally what I would like is for people to be able to subscribe to my calendar so the events update automatically if they change.
To do this I need to allow people to subscribe to the calendar using the URL of the file rather than clicking on a link. Is there a way to allow visitors to my WordPress site to access www.mydomain.com/calendar.ics? | Found a solution. Went into the media library and found the URL of the file in there and now it works. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads, filesystem"
} |
Share taxonomy between user and posts?
I'm in need of a taxonomy that can be shared between users and posts. Is this possible and if so how? I read that you can set up taxonomy for users, but is it possible to share it with a post type? My use case is a company employees list where employees are divided into different departments, corresponding to a post category for each department.
I want to be able to check which department current user belongs to, and show posts belonging to the same taxonomy term.
Or is there perhaps some other way of setting this up that might be easier or more natural? | No you can't, for a simple reason:
> This term says that ID `1` is in the `food` category, but is that user 1 or post 1?
The ID provides no context, it's an object ID. As a result, there's no way to tell if that ID is a post ID or a user ID. This is why multiple post types can share a taxonomy as they're all posts, but you can't mix posts and users
## Sidestepping the Issue
Use 2 taxonomies and a little magic! Create one for users, and one for posts, where every term exists twice in both with the same name/slug. Then use hooks and filters to create and update terms as they're modified in either taxonomy.
I anticipate that this might lead to the question of how to query for both at the same time. I'm afraid that's not possible. Instead, `get_objects_in_term` can get you the relevant users, and `WP_Query` can fetch the posts | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom taxonomy, taxonomy, users"
} |
customize_preview_init: listening for any changes from Customizer preview area
I know I can listen for specific setting changes from the previewer by adding the following JS to the **`customize_preview_init`** hook:
wp.customize( 'setting-ID', function ( value ) {
value.bind( function( val ) {
// things go here
} );
} );
But can I easily listen for _any_ changes? Or a group of changes? For example, I have a ton of settings that are all named something like: `my_settings[setting_a], my_setting[setting_b]` | Yes. You can bind to the `change` event on the entire `Setting` collection (`wp.customize`) as follows:
wp.customize.bind( 'change', function ( setting ) {
if ( 0 === setting.id.indexOf( 'my_settings[' ) ) {
doSomethingWithSettingValue( setting.get() );
}
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, theme customizer, previews"
} |
How insert a DIV at top of current theme?
I would like to insert a full-width DIV at the topmost location in the site I'm building. The project is in overtime. All the other work is done, but I have been asked to add a small logo and a single link on top. This would be on all pages, so it's a modification to the header. I've looked at several plugins, but they seem to be creating a "notification bar" by positioning and z-index. The theme we're using is Velux, a child of Primer. | As I can see in wp-primer-theme sources: there are `do_action( 'primer_body' );` on the top of content and `do_action( 'primer_before_header' );` just below.
You can update your child theme functions.php with your own action
add_action('primer_before_header', function() {
echo '<div class="logo"></div>';
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
How to use esc_attr__() function properly to translate a variable that contains string?
I am trying to develop a theme and trying to escape a string using `esc_attr__()` fuction. Here is how I implemented it.
$title = stoic_get_the_site_title();
echo esc_attr__($title, 'stoic');
But Themecheck plugin is giving me this error:
WARNING: Found a translation function that is missing a text-domain. Function esc_attr__, with the arguments 'stoic'
What is the proper way to do it so that Themecheck doesn't show this type of error? | If you have static text with dynamic content then you can use.
` printf( esc_attr___('static text goes here with %s', 'text-domain' ), $title ); `
If you have only $title then no need to translate it.
Just escape it.
` echo esc_attr( $title ); `
* * *
Note `esc_attr`, `esc_attr__` and `esc_attr_e` used for escaping dynamic values from HTML element attributes.
E.g.
` `<div class="<?php echo esc_attr( $class ); ?>">` `
And `esc_html`, `esc_html__` and `esc_html_e` used for escaping dynamic values from HTML content.
E.g.
<div> <?php echo esc_html( $title ); ?> </div> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "theme development, localization, validation, sanitization"
} |
How to add text before posts
This is the picture of my site.) : ?>
<div class="head-title">
<p class="about-me">your text</p>
</div>
<?php endif; ?>
Please, note, that if you want to get updates your theme, you should create child wordpress theme with custom header.php file | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, customization, text"
} |
Counting posts with argument without retrieving the posts
I have a quite extensive database, 30000+ items, and using this:
$args = array(
'posts_per_page' => -1,
'post_type' => 'books',
's' => $s
);
$post_counts = count(get_posts($args));
seems to take forever.
I solved this particular case with:
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'books' AND post_status = 'publish' AND post_title LIKE '%".$s."%'");
But I have many queries that I'd like to count without having to write them by hand. Is there any way to count the posts with the $args using wordpress native functions without having to store the whole querie but only the count? | Here's one thing you could do. Create a WP_Query object but only include ids:
$args = array(
'posts_per_page' => -1,
'post_type' => 'books',
's' => $s,
'fields' => 'ids',
);
$query = new WP_Query( $args );
$post_counts = $query->post_count;
wp_reset_postdata();
By using `fields => ids` you're only returning the IDs. Also, WP_Query already does a count and supplies it as a property: `post_count`. Finally, since we are using a WP_Query we need to reset the globals with `wp_reset_postdata()`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wpdb, get posts, count"
} |
human_time_diff() returns "48 years ago" for all comments
Trying to make a custom comments box. When I go to display the time when the comment was post (ie, 2 days ago, 3 hours ago, etc.) I get the same for every comment on every post: "48 Years"
$args = array(
'number' => '4',
'post_id' => $id, // use post_id, not post_ID
);
$comments = get_comments( $args );
foreach ( $comments as $comment ) :
// get the comments contents
echo $comment->comment_content;
// human readable time when it was posted
//
// this is where we get the "48 years" as when it was posted
//
echo human_time_diff( $comment->comment_date, current_time( 'timestamp', 1 ) );
endforeach;
Whats up with that? | You should use `strtotime` to turn the comment's date into a string that can be compared with the current time. In your case, you should use:
echo human_time_diff( strtotime( $comment->comment_date ), current_time( 'timestamp', 1 ) ); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "comments, date time"
} |
Order by the results of a function with WP_query
I am attempting to order the results from WP_query by a custom value. Specifically, I want to use the name field, however, the name field is going to be made up of many words separated by spaces. I specifically want to order by the last word in the name field.
Currently, my query args are this:
$args = array(
'post_parent' => $post->ID,
'order' => 'ASC',
'orderby' => 'name',
'post_type' => 'page',
'posts_per_page' => 8,
'paged' => get_query_var( 'paged' ),
'meta_key' => 'team_school',
'meta_value' => $school_type
);
I have seen information on the `meta_query` argument but nothing that indicates I can do what I am looking to do. | @JasCav Here is something to put you in the right direction. Maybe someone can edit where needed.
// args
$args = [
'post_parent' => $post->ID,
'post_type' => 'page',
'posts_per_page' => 8,
'paged' => get_query_var( 'paged' ),
'meta_key' => 'team_school',
'meta_value' => $school_type,
'orderby' => 'wpse_last_word', //<-- make filter for ordering!
'order' => 'ASC'
];
// query
$the_query = new WP_Query( $args );
add_filter( 'posts_orderby', function( $orderby, \WP_Query $q )
{
if( isset( $args['orderby'] ) && 'wpse_last_word' === $args['orderby'] )
{
global $wpdb;
$orderby = " SUBSTRING_INDEX( $wpdb->postmeta.meta_value, ' ', -1 ) ";
}
return $orderby;
}, PHP_INT_MAX, 2 );
Referenced from < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, order"
} |
Enqueueing common php scripts in a plugin
I have a plugin rejected by wordpress.org, one of the resasons is this:
> ## Unsafe Requiring of Common Libraries Since you're using a common library, it's important that you enqueue it safely. Example(s):
>
> require_once('jsonld.php');
>
> Since that is a common library, you need to detect IF the code is already included and not re-include it, as doing so will cause conflicts if two people call the same defines and functions.
I understand about enqueueing jQuery and CSS - but this is a PHP script with multiple functions.
1. If this script is common do I need to just reference it in the WP Core?
2. Otherwise do I need to just look at the functions I'm calling and wrap them in a class (I'm uncertain about this) or can I refer to the whole php script?
3. What is the standard way of doing this?
Thanks
Dan | 1. No, it just means it's used by many plugins, not that Core includes it.
2. Many of the functions in that library seem to use the `JsonLdProcessor` class that is also in that library, I'd check for that before including:
if ( ! class_exists( 'JsonLdProcessor' ) ) {
require_once( 'jsonld.php' )
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, wp enqueue script"
} |
Show admin bar only for some USERS roles
I have 4 users roles on my wordpress platform (role1, role2, role3, role4)
I'm looking for to show front-end top bar only for Role1 Role2.
how can i add a condition on this code to show it only for this 2 roles?
function wpc_show_admin_bar() {
return true;
}
add_filter('show_admin_bar' , 'wpc_show_admin_bar');
thanks | You can disable the admin bar via function:
show_admin_bar(false);
So with that in mind, we can hook into `after_setup_theme` and hide the admin bar for all users except `administrator` and `contributor`:
function cc_wpse_278096_disable_admin_bar() {
if (current_user_can('administrator') || current_user_can('contributor') ) {
// user can view admin bar
show_admin_bar(true); // this line isn't essentially needed by default...
} else {
// hide admin bar
show_admin_bar(false);
}
}
add_action('after_setup_theme', 'cc_wpse_278096_disable_admin_bar');
I am only using `administrator` and `contributor` as example. You can of course change this and add more roles. | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 5,
"tags": "users, admin bar, user roles"
} |
Wordpress doesn't respect "ver" parameter in styles
My Wordpress server prints the enqueued styles without version parameter, making them cached forever. My local installation prints the styles as they should look, with "ver" intact. Does not matter if the styles are in parent or child theme. | Okay, the "disable all plugins and turn them on one by one" helped. It was "SmartPayCard" plugin. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "css"
} |
Are the default entries for a user in wp_usermeta documented?
On a fresh vanilla install of wordpress users have default entries like nickename, first_name, last_name and so forth in wp_usermeta. I'm not sure if that changes often or at all but I can't seem to find any documentation what the default entries are.
I would have expected it here: <
Is the default set documented and where?
Reason for asking: I'm building a plugin to replicate settings to other users but would like to exclude the default entries (or at least annotate on them or treat them differently). And to maintain the plugin, I'd like to be able to look those up in case there are changes. | You may want to take a look at the code itself:
<
The above links to a documented list of the meta generated when WordPress generates a new user in the `wp_create_user` function.
From these comments I pulled a quick list:
> user_pass, user_login, user_nicename, user_url, user_email, display_name, nickname, first_name, last_name, description, rich_editing, comment_shortcuts, admin_color, use_ssl, user_registered, show_admin_bar_front, role, locale | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "user meta, customization, documentation"
} |
Why the Path is different with the one coded in rest
Reference URL from where the code is taken: Writing WP REST API Endpoint in 2 minutes
add_action( 'rest_api_init', function () {
register_rest_route( 'tomjn/v1', '/test/', array(
'methods' => 'GET',
'callback' => 'tomjn_rest_test'
) );
} );
function tomjn_rest_test() {
return "moomins";
}
Based on the above code the path should be this →
> <
then why this:
> <
With what logic is this portion coming up →
> /wp-json/
This was the Primary question from where my learning started. | No it shouldn't.
The first parameter is called namespace. It's like the scope for your functions such as this:
function my_function(){
$data = 0;
}
You can only use `$data` inside that function. Same goes with the REST endpoints. The path `/test/` will be available only under its specific namespace.
You should choose a unique namespace for your plugin or theme, and build different paths for different endpoints.
The second argument is the path. It's like branches of a tree. Imagine a tree as a namespace, and its branches as paths. You can climb the tree, and then choose a branch to harvest the fruits.
However, both of these are under the scope of rest route, has a base of `/wp-json/` if you have pretty permalinks enabled, or `/?rest_route=` if you are using plain permalinks.
Check the code reference about `register_rest_route()` for more details. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "rest api"
} |
Delete Wordpress posts from URL list sql query
Is it possible to delete a huge number of wordpress posts through SQL query using phpmyadmin by using a permalink list of posts that I want to delete ? | Yes you can. To delete posts with inherit post meta, use following code:
DELETE
p,pm
FROM wp_posts p
JOIN wp_postmeta pm ON pm.post_id = p.id
WHERE p.post_name IN ('post-1', 'post-2', 'post-3')
Pass slugs array to WHERE clause.
If you want to delete only posts w/out postmeta (for some reason), use this code:
DELETE
FROM wp_posts
WHERE post_name IN ('post-1', 'post-2', 'post-3') | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, sql, phpmyadmin"
} |
How to dublicate WC Product title to shortdescription field?
Need dublicate (copy) WC Product title to short description field. Please help with a function. | Use the below action in your `functions.php` in Current theme for duplicate Product title in Short description field.
<?php
add_action( 'publish_product', function ( $post_id ) {
global $wpdb;
$wpdb->update(
'wp_posts',
array(
'post_excerpt' => get_the_title( $post_id ),
),
array( 'ID' => $post_id )
);
}, 10, 2 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Set_post_thumbnail not resizing images
I'm currently trying to resize all the featured images on my theme to 1140 x 500. I've placed this code in my function.php file
if ( function_exists( 'add_theme_support' ) ) {
add_theme_support( 'post-thumbnails' );
// Default Post thumbnail dimensions (cropped)
set_post_thumbnail_size( 1140, 500, true );
}
And this code in my loop.
<?php if ( has_post_thumbnail() ) { // check for feature image ?>
<div class="post-image">
<?php the_post_thumbnail(); ?>
</div><!-- post-image -->
<?php } ?>
Thanks for any help. | Setting the size itself does not crop the existing images. You need to regenerate the existing thumbnails too.
There are a couple of plugins for this, but I personally downloaded and used Regenerate Thumbnails. Install the plugin, and head over to `Tools > Regenerate Thumbnails`. There you can regenerate thumbnails for images that exist in your media library, replacing the old thumbnails. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "post thumbnails"
} |
How to search users globally on a multisite install?
I'm using the REST API to create/update/delete users on a multisite install in order to sync data with a 3rd party resource. When I am checking whether to update or create a user, I'm using the `search` parameter to search on usernames, which works fine on a single site, but if a user exists in the system on a different site, how can I tell beyond trying the insert, which triggers a _Username is already in use_ error? I've found this proposed change, which looks to be exactly what I need, but it hasn't made it into code yet. How can I achieve this? I don't mind writing a custom endpoint and doing it in PHP, but I can't find any functions that allows searching globally for users. Even `WP_User_Query` appears limited to one blog at a time. | It appears you can do this using a `blog_id` of `0`:
$args = array( 'blog_id' => 0 );
$users = get_users( $args );
var_dump( $users );
If you want to search for a specific user, the process is similar:
$args = array( 'blog_id' => 0, 'search' => '{username to search for}' );
$users = get_users( $args );
var_dump( $users );
I discovered this while poking around in the `wp-cli` source code (since I knew that `wp user list --network` would return a list of all the users on a Multisite network). It's corroborated by a user comment on the `WP_User_Query::prepare_query()` documentation. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "multisite, users"
} |
How to exclude products by tag from woocommerce shop page?
I want to remove certain products by their tag from woocommerce Shop page query. Anyone can tell me how to do that? Thanks! | Add this to your functions.php
function custom_pre_get_posts_query( $q ) {
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => array( 'banana' ), // Don't display products with the tag "banana"
'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "wp query, woocommerce offtopic, tags"
} |
how can i add extra parameter to edit post link?
i'm just reseach wordpress for few days. But i don't know what keyword to reseach this problem:
I have 2 post module called hotel and room . In hotel page when i edit , it have a button to redirect to add new room in room module . this link is :
example.com/wp-admin/post.php?post_type=room&hotel_id=30
But when i edit a room , this link is:
example.com/wp-admin/post.php?post=31&action=edit
HOw can i add extra parameter to room edit to seperate which is room edit , which is hotel edit . Example:
example.com/wp-admin/post.php?post=30&action=edit (hotel)
example.com/wp-admin/post.php?post=31&hotel_id=30&action=edit (room)
Can anyone give me a solution or keyword to research . Thanks for reading | The `get_edit_post_link` filter lets you modify that value. This is applied any time `get_edit_post_link` function is called, which admin uses, as well as themes on the front end.
function wpd_edit_post_link_filter( $link, $post_ID, $context ){
if( 'room' == get_post_type( $post_ID ) ){
$link = $link . '&fubar=baz';
}
return $link;
}
add_filter( 'get_edit_post_link', 'wpd_edit_post_link_filter', 10, 3 );
You can use the `$post_ID` to fetch info about that particular post, and `get_current_screen` might be helpful to decide when to apply the filter. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post editor"
} |
How to get the Woocoomerce subtotal value without tax in the hardcode?
I'm trying to find the subtotal value without tax in the hard-code. I want to use the value after people have completed an order and run some code there.
I thought it was `$order->get_line_subtotal();` but that gave 0 as value when I used it in the `wp-content/plugins/woocommerce/templates/checkout/thankyou.php` file. | `$order->get_subtotal()` should get you totals before taxes, coupons and shipping. It's a method of `WC_Abstract_Order` which is extended by the actual `WC_Order` class. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "php, code"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.