INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Error:406 not acceptable
I have a wodpress site, and I have submitted it to google webmaster tools. When I search on google by my site name, the results come, and on clicking the searched result, I can open the website on my PC. But when doing the same thing on my mobile, i get this
Error 406: Not accebtable
How can can resolve it? | I had a similar problem recently with this 406 Not Acceptable error occurring when trying to update permalinks in WordPress. I also had the same problem when submitting any changes to the editor, etc. Google Webmaster tools would yield the same result.
The solution is to disable the mod_security firewall within your `.htaccess` file.
My fix was to install a plugin called "WP Htaccess Editor" (free WP plugin), then update the `.htaccess` file to the following, between the "Begin WordPress" and "End WordPress" tags:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Hope this helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "htaccess"
} |
Prevent registration except through form
I have a Formidable Pro form that handles user registrations on my site. It has a CAPTCHA. Is it possible to prevent anyone from registering by other methods (e.g. wp-register.php)?
(I've tried using plugins to stop spam registrations but there was always something that didn't quite work for me. If the CAPTCHA is enough, why complicate things by adding a new plugin?) | I found a good answer and slightly modified it on a related question . It uses htaccess, and redirects any requests to wp-login.php?action=register.
# BLOCK SPAM REGISTRATION REQUESTS (wp-login.php?action=register)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{THE_REQUEST} ^.*(wp-login.php\?action=register).* [NC]
RewriteRule ^(.*)$
</IfModule>
Notes:
1. In the answer I linked to he totally blocked these requests. However I have redirected them to the Formidable Pro signup form, as you can see in the RewriteRule.
2. As far as I know, all regsitration attempts, even wp-register.php, will go through wp-login.php?action=register.
3. I have tested signup using my Formidable Form and it's still working fine. Also, wp-login.php, including lost password, is still working. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "user registration, spam"
} |
Redirect homepage /page/1/ to /blog/page/1/
After switching from the homepage displaying latest blog posts on urls /page/1/ /page/2/ etc to a static front page with the posts displayed on /blog/page/1/ we would like to redirect the original /page/#/ to the new url /blog/page/#/
Is there a best way to do this? Perhaps a plugin, though searching has yielded little result, or htaccess redirects? | In your .htaccess file, add this code below-
Redirect 301 /
Change _mywebsite.com_ with your actual domain. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, htaccess, seo, mod rewrite"
} |
meta_query 'compare' => 'IN' not working
First of all, I know it's a duplicate, but none of the older answers were helpful.
I'm searching in posts through `post_meta`. Here's my code, which currently returns nothing.
$args = array(
'numberposts' => -1,
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'system_power_supply',
'value' => array('single', 'redundant'),
'compare' => 'IN',
)
)
);
$query = new WP_Query($args);
echo $query->found_posts;
If I remove `meta_query` it works. I'm sure of these things:
* There's no spelling mistake in the `key` or the `value`.
* post type is `post`
* There **is** a post with the value 'single' in 'system_power_supply'. However, post fields are generated by Advanced Custom Fields. | There's no easy way to search serialized values in a meta query. If the list of values isn't crazy long, potentially you could set up multiple meta queries:
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'system_power_supply',
'value' => 'single',
'compare' => 'LIKE',
),
array(
'key' => 'system_power_supply',
'value' => 'redundant',
'compare' => 'LIKE',
)
)
Or if you wanted to get super fancy, you could set it up dynamically:
$values_to_search = array('single', 'redundant');
$meta_query = array('relation' => 'OR');
foreach ($values_to_search as $value) {
$meta_query[] = array(
'key' => 'system_power_supply',
'value' => $value,
'compare' => 'LIKE',
);
} | stackexchange-wordpress | {
"answer_score": 21,
"question_score": 20,
"tags": "wp query, meta query"
} |
Adding "reply-to" in the email
So, I am trying to add "reply-to" in the order email using the `billing_email`
Here is what I have so far but the code is not written well and I am not sure how to change it.
Here is the original:
public function send( $to, $subject, $message, $headers = "Content-Type: text/html\r\n", $attachments = "" ) {
$email = new WC_Email();
$email->send( $to, $subject, $message, $headers, $attachments );
}
Then I edited to the following:
public function send( $to, $subject, $message, $attachments = "", $order ) {
$headers = array( "Reply-To: <?php echo $order->billing_email; ?>" );
$email = new WC_Email();
$email->send( $to, $subject, $message, $headers, $attachments );
}
Any suggestions?
Thanks | Not sure what the `WC_Email` class does exactly, but if the `$headers` argument is an array of headers, then you're almost there. To interpolate a variable value into a string in PHP you don't have to do the `<?php ...` stuff because it'll be rendered as is. Instead, you can use:
$headers = array( "Reply-To: {$order->billing_email}" );
Or:
$headers = array( 'Reply-To: ' . $order->billing_email );
Or:
$headers = array( sprintf( 'Reply-To: %s', $order->billing_email ) );
Also, if the billing e-mail address is user input, don't forget to validate it with `is_email()` and/or sanitize it with `sanitize_email()`.
Hope that helps. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "email, woocommerce offtopic"
} |
With two custom post types, how to make one a child of the other in the admin menu?
Been following Justin Tadlock's nice clear tutorial on how to have one custom post type act as a dropdown for another in the admin edit screen.
His example is of a restaurant CPT needing a dropdown to a neighbourhood CPT (btw, as the author points out in the comments, the reason not to just use a taxonomy is that the neighbourhood could have a bunch of custom fields not catered for by the built in taxonomy).
Here's the screenshot:
!enter image description here
The tutorial code works perfectly on our site.
My question is, to keep the admin menu clean it would be nice to have everything sit under one root entry like so:
Places
- Add New
- Neighbourhoods
I only know how to add a root level CPT. So mine looks like this:
Places
- Add New
Neighbourhoods
- Add New | In your `register_post_type` call, use the argument `show_in_menu`:
register_post_type(
'neighbourhood',
array(
'show_in_menu' => 'edit.php?post_type=place',
// other args
)
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, admin menu"
} |
add_filter does not work as expected
I have a wordpress plugin where i included this (with some changes)
$fep_files = array(
'first' => 'first.php',
'second' => 'second.php'
);
$fep_files = apply_filters('include_files', $fep_files );
foreach ( $fep_files as $fep_file )
require_once ( $fep_file );
unset ( $fep_files );
Now i added in my theme's function.php
function fep_remove ( $fep_files )
{
if ( isset ( $fep_files['first'] ) ) {
unset ( $fep_files['first'] );
}
//die($fep_files); //to check it fires
return $fep_files;
}
add_filter( 'include_files', 'fep_remove' );
It should remove first.php but it does not. i am wrong some where, but where? Is there any better way to include files where user can include/exclude any files if needed? | Your plugin code is going to run before the theme code and hence will run before anything is added to the hook. You will need to the code that processes the file inclusion to some other hook that runs after all of the plugins load, like `after_setup_theme`
This should help: Is there a flowchart for wordpress loading sequence? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "filters"
} |
Safe method to temporarily load second jquery library to wordpress
For testing (and completely temporary purposes) I want to load a jquery cdn into my wordpress header.php file. I can't determine if this is possible, and assume I'd need to setup for noconflict, etc. I've found documentation on it for the functions.php method, however the work for that would defeat the purpose of testing in header.php. Has anyone done this before? | Instead of rolling-your-own, just use a plugin designed specifically for that purpose for the CDN in question:
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery"
} |
Advanced sorting of content in wordpress
Let's just say that I have website about cars. I have already created several categories, depending on which brand the cars are. My question is simple. I would like to implement some advanced type of sort for users. Let's say, that I have already above 50 cars in my Porsche category, and I would like to give user opportunity, where he can decide to display only yellow porsches, or only porsches, which are more than 20 years old, and so on. I just started with wordpress and I have not found anything about this topic in hours of googling. I have basic skills of mysql, advanced in html, ccs I would rather find some existing plugin for this, than creating all the stuff on my own There is a typical thing, which I would like to achive on my website - < \- you can see, how you can sort replays of the games by nations, tiers, type of vehicles, and so on. Anyway, thank anyone for the answer! | All what you want to do you can get just with ordinary custom fields. I can imagine custom fields like colour, age, brand etc. and theirs filtering according to user's selection in frontend.
Please read about custom fields here
<
There are some awesome plugins for creating custom fields too. One of my favourite is Advanced custom fields
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sort, content"
} |
Changing header text from uppercase to normal
All header text is uppercase.
In main-style.css this works:
h1, h2, h3, h4, h5, h6 {
margin:0;
text-transform:none;
}
but, when I do any changes in Appearance > Customize or in Cherry Options it overrides the changes above. Also, adding the above code to style.css doesn't work.
Any help would be appreciated :) | Try adding the !important tag
text-transform:none!important; | stackexchange-wordpress | {
"answer_score": -2,
"question_score": 1,
"tags": "headers"
} |
Display Authors avatars when more than one author
On a blog, i'm using the following to display the post authors avatars:
<a href="<?php echo get_author_posts_url(get_the_author_meta( 'ID' )); ?>" style="color:#ffffff;"><?php echo get_avatar( get_the_author_meta( 'ID' )); ?></a>
But some posts have more than one author, and this only displays one avatar, how can I get this to display both authors avatars?
Thanks | Here we go, found a nice thread which gave some answers and developed this which works a treat:
if ( class_exists( 'coauthors_plus' ) ) {
$co_authors = get_coauthors();
foreach ( $co_authors as $key => $co_author ) {
$co_author_classes = array(
'co-author-wrap',
'co-author-number-' . ( $key + 1 ),
);
echo '<div class="' . implode( ' ', $co_author_classes ) . '"><a href="' . get_author_posts_url($co_author->ID) . '" style="color:#ffffff;">';
echo userphoto_thumbnail( $co_author );
echo '</a></div>';
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "author, avatar"
} |
Give Author users the right to embed
I'm trying to allow "author" users to embed in posts. I (the administrator) can iframe, embed, etc...., but authors can not.
Can someone show me to give authors 'just' the ability to embed and iframe in posts? | The capability you are after is called `unfiltered_html`. Some options:
1. Modify **author** capabilities in your theme `functions.php`. This is saved in the DB, so you can access a page, make sure it works then remove it from your `functions.php` file. A better option would be to run it on theme activation. See this page on WP Codex for options:
function add_theme_caps() {
// gets the author role
$role = get_role( 'author' );
// This only works, because it accesses the class instance.
// would allow the author to edit others' posts for current theme only
$role->add_cap( 'unfiltered_html' );
}
add_action( 'admin_init', 'add_theme_caps');
2. Use a plugin that allows you to modify it using a UI, like User Role Editor. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "author, embed, iframe"
} |
Show custom field value as a link
I’m trying to show one of my custom fields as a link that downloads a photo. I’ve entered the URL in the field value but struggling to come up with the correct html to get it to display as a downloadable link.
<?php
// Display Custom Field Value
echo "<ul>";
echo "<li>License Type: ".get_post_meta( $post->ID, 'License Type', true )."</li>";
echo "<li>Download Comp: ".get_post_meta( $post->ID, 'Download Comp, true )."</li>";
echo "</ul>";
?>
I’d like the ‘Download Comp’ to display ‘click here’ which would obviously be taken to the URL that I’ve already entered. Thanks | <?php
// Display Custom Field Value
echo "<ul>";
echo "<li>License Type: ".get_post_meta( $post->ID, 'License Type', true )."</li>";
echo '<li><a href="' . get_post_meta( $post->ID, 'Download Comp', true ) . '">Download Comp</a></li>';
echo "</ul>";
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, links"
} |
Remove / overwrite some functions in buddypress.js
What's the best practice to overwrite some JS-functions in buddypress.js?
There are some quite annoying things in there like animating the form-fields on click/blur/post which I need to remove because they absolutely don't fit our design.
Would the best be to copy the whole script into my theme and deregister / enqueue? If so, who knows the deregister-name?
Any other possibilities?
Thanks! | Usually it is `bp-legacy-js`.
But if you place a buddypress.js in `wp-content/themes/your-theme/buddypress/js/` this file will be taken instead. The handle will be `bp-parent-js`
The same goes for CSS files, if you place them in `/your-theme/buddypress/css/`.
If you place the buddypress.js in a childtheme, the handle will be `bp-child-js`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, javascript, wp enqueue script, buddypress"
} |
Include plugin form in the home page
I created a Wordpress plugin, which allows the admin to add information through a form, and it is saved in the database. I'm trying to link each photo that I upload in the Media library with a form.
In other words, my objective is that I want to put my own caption in each image of the Media library, and this caption is taken through a form.
So I have the data from the form fields in a table in my db and another table with the media pictures. How can I link them between each other?
Does anyone have an idea about what can I do? | Assuming the images are posts. Register a new post meta for them and use the ID for your form in that post meta, this will allow you to relate to the form.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, database, forms"
} |
php variable inside javascript code
I placed a javascript inside a .php file
$script = "<script type='text/javascript'>
jQuery( document ).ready( function($) {
$(document).ready(function() {
$('#particles').particleground({
dotColor: '<?=json_encode($dotcolor)?>',
lineColor: '#5cb9bd',
});
});
}
);
</script>";
and tried to use `<?=json_encode($dotcolor)?>` to echo a variable. But it isn't working.
Any idea what I'm doing wrong? | This should work:
<?php $script = "<script type='text/javascript'>
jQuery( document ).ready( function($) {
$(document).ready(function() {
$('#particles').particleground({
dotColor: " . json_encode($dotcolor) . ",
lineColor: '#5cb9bd',
});
});
}
);
</script>";
?>
**Note:** Its a better practice to enqueue Javascripts with `wp_enqueue_script()` and include dynamic strings via `wp_localize_script()`.
**Docs:** < < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript"
} |
Is there a way to know if a post has been published through XML-RPC?
It's all in the title, I'm looking for a way to know if a given post was published through XML-RPC, versus published by hand in the WP admin.
Pseudo code :
if( !wpse_from_xmlrpc( $post -> ID ) {
// Doesn't come from XMLRPC
} else {
// Comes from XMLRPC
} | You could use a custom field for a post which is saved via XMLRPC by using the action hook `xmlrpc_publish_post`. `wpse_from_xmlrpc()` could than check this custom field.
<?php
add_action( 'xmlrpc_publish_post', 'add_xmlrpc_postmeta' );
function add_xmlrpc_postmeta( $post_id ){
update_post_meta( $post_id, 'send-by-xmlrpc', 1 );
}
function wpse_from_xmlrpc( $post_id ){
$xmlrpc = get_post_meta( $post_id, 'send-by-xmlrpc', true );
if( $xmlrpc == 1 )
return true;
return false;
}
?>
More information on this hook can be found in _wp-includes/post.php_ | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "publish, xml rpc, remote"
} |
Sum of Custom Meta written by Authour
I have a custom meta call post_views_count that collects the views of all posts...
I want to create a query that pulls in all posts by a certain author, gathers the custom meta for post views and then add them all together.
End result - Total view count for all authors posts... | Maybe not the most elegant solution
$authorPost = get_posts(array('author' => 1));foreach ($catPost as $post) {
setup_postdata($post);
$ids[] = get_the_ID();
}
$idList = implode(",", $ids); //turn the array into a comma delimited list
$meta_key = 'post_view';
$allview = $wpdb->get_var($wpdb->prepare("
SELECT sum(meta_value)
FROM $wpdb->postmeta
WHERE meta_key = %s
AND post_id in (" . $idList . ")", $meta_key));
echo '
user 1 All posts View Count'.$allview .'
'; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, sql"
} |
Can I reuse the Akismet API key used on old version of my website?
I have a site with old version of Akismet plugin. I'm doing a major update/reinstall and I need Akismet API key to reactivate the Akismet plugin. I didn't find the key neither hardcoded anywhere in the plugin code nor stored in the `wp_options` table in the database, where other Akismet variables are stored. I tried to google it out and all I found was to look at the e-mail where the API key was sent. I'm not the original webmaster, so this is not possible directly. I contacted the former webmaster, but he is not responding for several weeks, so I don't expect him to send me the key.
Can I retain the key somehow, or is my only option to get a new key? | The Akismet key is connected to your WordPress.com account or to your email address.
If you need to get the key again, just have it resent to you: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "akismet"
} |
Writing editor content to a file
I have a project I'm working on where I need to write the content of the post editor to a physical file on the web server when a post is saved or updated. I'll be parsing and manipulating the content before writing, but I'm having trouble just getting it loaded into a variable. Is there a different way I should be going about this and/or is there something I'm missing? Currently the file it writes is blank, if I throw a simple string into $content it's written to the file leading me to believe get_the_content() isn't working. Any ideas?
function pht_write_file() {
$file = WP_PLUGIN_DIR."/myplugin/test.xml";
$content = get_the_content();
file_put_contents($file, $content);
}
add_action('publish_post', 'pht_write_file'); | You should hook `save_post` instead of `publish_post`. `publish_post` only runs when a post is initially published and won't catch subsequent saves.
Additionally, the `publish_post` hook passes parameters to your function and those should be used to retrieve info about the post being published rather `get_the_content()`, which only works when you're inside the loop.
I think you're looking for something like this:
function pht_write_file($post_id){
if(get_post_status($post_id) !== 'publish') return; //only run if post is published
$post = get_post($post_id);
$content = $post->post_content;
$file = WP_PLUGIN_DIR."/myplugin/test.xml";
}
add_action('save_post', 'pht_write_file');
This function will also correctly hook to `publish_post` in the case where you did mean for the text to only be saved on publish instead of on save. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, functions"
} |
Hook (or other way) to find out when another plugin is activated / installed
Is there some way to run a function when another plugin is being installed and/or activated?
Basically I need something like `register_activation_hook` only for other plugins.
The use case:
I want to check for CVE patches on my own server when a plugin is installed / activated.
The only thing I can think of right now is manually keeping track of activated and installed plugins, but this is not a very clean solution. | I believe you are looking for `activated_plugin` and `deactivated_plugin`, see the wordpress documentation: | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, hooks, installation"
} |
Anchor doesn't work if it's given in the url
I'm trying to link to a specific part of the page, but when I include anchor in the URL, server doesn't interpret it, so I'm not sure how I would go to the anchor.
If I go to <
And pick "French", the following url is produced: <
But if I try to open that link in a new tab, then I just see the initial page.(the one without anchor) I want to be able to get to the anchor from another page.
Is there another way to go the anchor by modifying the URL or the code for that page? | The Anchor will never get to your server, it is only for client use (your browser). PHP will never get the anchor, and will do nothing with it. This is more Browser related, than Wordpress or Server related. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "links"
} |
Prevent Version URL Parameter (?ver=X.X.X) on Enqueued Styles & Scripts
## Use Case
I've been experimenting with Chrome's Dev Tools Workspace features. It includes the ability to edit a file directly in Dev Tools and have the saved stylesheet refresh itself (or even compile and then refresh!).
However, as documented in the StackOverflow question "Chrome's “Auto-Reload Generated CSS” not reloading page when SASS recompiles CSS", URL parameters on the stylesheet URL prevent Chrome from noticing the change.
## Desired Outcome
That means that **only during development** , I wanted to remove the `?ver=X.X.X` from the normal stylesheet `<link>` output by `wp_enqueue_style()`. In other words, I wanted the default `href`:
to instead be this:
| ## Default `wp_enqueue_[style/script]()` behavior
The default value for the `$version` argument of `wp_enqueue_style()` is `false`. However, that default just means that the stylesheets are given the _WordPress version_ instead.
## Solution
Thanks to "Remove version from WordPress enqueued CSS and JS", I learned the undocumented fact that passing in `null` as a version will remove the version altogether!
## Example
wp_enqueue_style( 'wpse-styles', get_template_directory_uri() . '/style.css', array(), null );
## Caveat Reminder
It's worth pointing out, as noted in the question, that this should probably only be done during development (as in the specific usecase). The version parameter helps with caching (and not caching) for site visitors and so probably should be left alone in 99% of cases. | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 17,
"tags": "wp enqueue script, wp enqueue style, local installation"
} |
The hyperlink <a> not responsive with post?
I'm using semplicemente theme .(<
But in my post which have a hyperlink look like
<a href="link">conent</a>
And when i test it's responsive, everthing working great except the hyperlink.
I tried to reinstall the fresh install theme. But it still error.
Any idea? | Inspect the element once in "responsive mode" and check if no CSS is missing.
You could also post a screenshot for us to see what you mean by 'not responsive'. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "responsive"
} |
Wordpress cache login issue (w3 total cache)
I am using w3 total cache, and only few of its functions are on - browser cache, page cache. Yet when someone tries to login, seems like they have the homepage or other pages cached because they have visited them few minutes ago, and if after loging in they try to visit the same pages they appear logged out, unles the refresh the page.
The loging itself works, but it's not visible for the browser until refresh. Do you have any suggestions to which cache might be connected. Because I use the cache to speed up the website and so I need it, but if users keep complaining, I might need to turn it off since I don't want to lose the visitors. | In the Dashboard (Performance > General Settings) there's a _Debug_ section where you can turn on debugging for all the different caches, and it adds comments to the HTML source code, so you can see which pages / objects / DB queries have been cached.
If you enable debugging for _Page Cache_ , if it can't cache the page it'll say `Caching: disabled` and give you a reason, e.g. `User is logged in` (by default, pages for logged in users aren't cached.)
Remember to turn debugging off again when you've finished.
Note questions about third-party plugins are off-topic here; the best place to seek support would be the W3 Total Cache plugin page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin w3 total cache"
} |
Woocommerce where to set the Price Suffix
Short question but where in de woocommerce/wordpress environment can I define the "get_price_suffix();" function per product?
Thanks! | It's on the _Tax_ settings page and is `wp_options.woocommerce_price_display_suffix` in the database.
Please use the official site for WooCommerce and third-party plugin support, rather than StackExchange. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -2,
"tags": "plugins, woocommerce offtopic, production"
} |
Using static home page and wordpress only as a blog
Would using static home page and wordpress only as a blog increase page speed instead of using a Wordpress template to run the whole show?
Would I achieve the same effect using cache tools? | > Would using static home page and wordpress only as a blog increase page speed instead of using a Wordpress template to run the whole show?
If it did, it would only increase the speed of the homepage.
> Would I achieve the same effect using cache tools?
As a general rule yes – all cached pages (unless a user is logged in, when pages aren't normally cached) would typically be served by your cache plugin (or an advanced tool like Varnish) as if they were a static HTML file.
It's not just about the server speed, you can make a lot of difference by optimising your image sizes, reducing the number of HTTP requests, writing more efficiently javascript or CSS and so on.
Further reading: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "performance, seo"
} |
How to write specific HTML code with a specific custom field?
In my Wordpress, each post can contains 2 buttons pointing to different links.
To make it easy for the end user, I want to create a couple of **Custom Fields** where the user only needs to enter the **URL of the link for Button A or Button B** (or both), but once inserted, it will actually write the following code inside the post:
<a href='Custom Field A Value' target='_blank' class='btn btn-primary fb-event'></a>
<a href='Custom Field B Value' target='_blank' class='btn btn-primary ra-event'></a>
That would be if both custom fields are filled and inserted, it can also include only one link.
So long story short, can I hardcode HTML code around specific Custom Fields and use the value inside the HTML?
Is that even possible? | Try this :
// get_the_ID() will work if you're running within The Loop.
$fieldA = get_post_meta( get_the_ID(), 'name_of_fieldA', true );
$fieldB = get_post_meta( get_the_ID(), 'name_of_fieldB', true );
if( $fieldA ) {
echo "<a href='".$fieldA."' target='_blank' class='btn btn-primary fb-event'></a>";
}
if( $fieldB ) {
echo "<a href='".$fieldB."' target='_blank' class='btn btn-primary ra-event'></a>";
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field"
} |
How can I debug the TTFB in WP?
I'm developing a WP theme, based on _s default theme with WP 4.1.1.
I keep getting a TTFB(time to first byte) of 22s, consistently both on the front and back of the site, while on localhost.
Here's a print from DevTools: !enter image description here
I'm using the Debug Bar plugin, so I can see on the Queries and Profiler tabs that this is not a database or execution time problem(the sum of both takes 700ms). I guess it's not a rewrite problem either, since it behaves the same on the default permalink structure.
Other wordpress sites on my www don't have the same problem, so I'm discarding the server configuration. I also tried to load in incognito mode, without any difference.
Is there a way to debug this a little deeper? | Meanwhile, I found some plugins and tools that can help with this:
* Query Monitor
* Laps
* Debug Bar with some add-ons(Slow Actions, Rewrite Rules, etc.)
If you really wanna go deep, try using Webgrind. Not the most friendly tool, but it'll do the job.
Be aware that some of this tools will also have an impact on performance. | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 9,
"tags": "performance, debug, configuration"
} |
Add attribute to shortcode dynamically
I'm looking to add an attribute to a shortcode used in a post dynamically. For example, say we start with:
[shortcode-name]
I'd like to add the "attribute=xxx" portion to the shortcode so it is effectively like so:
[shortcode-name attribute=xxx]
For just the first shortcode encountered in a post. Is this possible?
Thanks! | Untested (and can't test right now) but you ought to be able to add attributes with a filter... something like:
function test_sc($atts,$content) {
// echo 'test_sc';
$atts = shortcode_atts(
array(
'foo' => 'no foo',
'bar' => 'default bar',
),
$atts,
'testsc'
);
// var_dump($atts);
}
add_shortcode('testsc','test_sc');
function test_shortcode_att_add($atts) {
# this filter should only run once (first use on page)
remove_filter('shortcode_atts_testsc','test_shortcode_att_add');
$atts['xxx'] = 'yyy';
return $atts;
}
add_filter('shortcode_atts_testsc','test_shortcode_att_add');
Of course, I don't know exactly what you attribute you are trying to add, or what kind of supporting code it might depend on. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "shortcode, customization"
} |
How to add an attribute to a user?
I have looked for an answer, and couldn't find a clear and relevant answer yet.
I want to add more attribute to the users not to display, but only store information about them. The information will be used for a background function. I know that usermeta is used to add more attributes, and I know how to access the already existing information, but I don't know how to add/create new attributes.
This piece of information can be a null string by default for every user and modified if the user enters information.
I'd appreciate any kind of help since I'm new at Wordpress. Thanks! | The easiest trick is to use the `user_contactmethods` \- the fields don't actually have to be contacts, but WordPress will do all the leg work for you (displaying the fields & saving the data):
function wpse_183763_user_contactmethods( $methods, $user ) {
$methods['my_field_1'] = 'My Label For Field 1';
$methods['my_field_2'] = 'My Label For Field 2';
return $methods;
}
add_filter( 'user_contactmethods', 'wpse_183763_user_contactmethods', 10, 2 );
If you add this code to a plugin or your `functions.php`, you'll see the new fields when editing your profile. To get the values, just use the meta API:
// With a user ID
echo get_user_meta( $user_id, 'my_field_1', true );
// Or with a WP_User object
echo $user->my_field_1; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, user meta"
} |
How to add replyToUrl schema.org to Wordpress comments?
I have the following code in my comments.php
<div class="reply">
<?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
</div>
I've tried to put the following filter, but it breaks the layout (it adds 2 lines of text/url):
function additemproptocommentreplylink( $atts, $item, $args ) {
$atts['itemprop'] = 'replyToUrl';
return $atts;
}
add_filter('comment_reply_link', 'additemproptocommentreplylink', 3, 10);
Can someone suggest how I can add that itemprop to the reply link?
Thanks | You could instead try the following replacement:
/**
* Add itemprop attribute to the comment reply link
*/
add_filter('comment_reply_link', function( $html )
{
if( false === stripos( $html, 'itemprop="' ) )
$html = str_ireplace( '<a ', '<a itemprop="replyToUrl" ', $html );
return $html;
}, 99 );
through the `comment_reply_link` filter. The HTML generation, of the comment reply link, only supports a given set of attributes and `itemprop` is not among them. That's why we try the replacement here instead. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "comments"
} |
get_template_directory() - references parent theme directory
I've got this line in the functions.php of my Child theme:
require ( get_template_directory() . '/somecode.php' );
However it's giving me the following error:
Fatal error: require(): Failed opening required <path/to/parent/theme/somecode.php>
where `path/to/parent/theme` is actually the path of the Parent theme rather than the Child theme.
Any idea why? | `get_template_directory()` gives you the path to the parent theme while `get_stylesheet_directory()` gives you the path to the child theme.
**Docs:**
* <
* < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, themes, child theme"
} |
Plugin page and capabilities
i´am developing my own WP plugin with custom functions and i would like to show the new submenu in the standard admin panel for **everyone** , who logs in. My code:
$capa = 'administrator' or 'author' or 'visitor';
$this->pagehook = $page = add_menu_page(__('Myplugin','my_plugin'), __('Myplugin','my_plugin'),$capa, $this->page_id, array($this,'render') )
As you can see, i defined 1 variable `$capa`, what can be one of the three strings. My problem is that the plugin is visible only when i´m logged in as **admin**. When I log in as visitor or author, the plugin is not visible.
Can u help me? | `$capa` is a PHP expression and will always evaluate to `administrator`. Use the capability `read` instead - every role (by default) has this. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "capabilities, add menu page"
} |
Meta Slider Lite plugin shortcode in post not working
I'm trying to implement a slider in my Wordpress post. For this I'm using `Meta Slider` plugin. When I've added a slider, I should be able to use the shortcode in my posts (`[metaslider id=21]`). If I add this to one of my post, it shows up the same way on the live page. I don't see any slider, there is just a string "[metaslider id=21]" on my page.
I checked that `wp_footer();` is implemented right before the `body` tag is ending and that the footer is implemented in every php file.
I get the post content using this way:
$args = array('posts_per_page' => 5, 'tag' => get_the_title());
$wp_query = new WP_Query( $args );
$posts = $wp_query->get_posts();
foreach($posts as $post){
$id = $post->ID;
$content = get_post($id);
echo $content->post_content;
}
It gets the content perfectly but it's not loading the slider.
Can someone please tell me the reason why? | You need to run the content through `do_shortcode()` \- at the moment you're just echo'ing the raw post content, so nothing gets parsed.
echo do_shortcode( $content->post_content );
However, you might be better off implementing a proper "loop" and using `the_content()` template tag - doing so will ensure everything runs "as normal" (firing all the typical hooks and formatting filters), accommodating for any quirks/extra hooks your slider plugin might rely on:
while ( $posts->have_posts() ) {
$posts->the_post();
the_content();
}
wp_reset_postdata(); // Restore the global post to the "current" post | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "footer, slideshow"
} |
Difference between meta keys with _ and without _
In wp_postmeta table I noticed that some of the keys are with '_' (underscore) prefix and and some are without _
What is the major difference between these fields and how they can be used while theming ?
Is there any special use of fields with _ ?
Most of the plugins used this approach to create meta keys but there is not codex on wordpress regarding meta key naming, its not sure if there is any technical difference between these key names. | The underscore prefix are private, these meta fields will be hidden and will not be shown as custom fields in the post backend screens. Those meta fields without the underscore prefix are public fields and shows up as custom fields in the post screens | stackexchange-wordpress | {
"answer_score": 21,
"question_score": 12,
"tags": "custom field, post meta"
} |
Generating dynamic css into custom file
This is about running code on wordpress . The given code runs properly outside wordpress but when I put it on theme functions file it does not do anything.
ob_start();
require('dynamic-css.php');
$content = ob_get_contents();
ob_end_clean();
$f = fopen("custom.css", "w");
fwrite($f, $content);
fclose($f);
I think I have to put this inside custom function and add hook then. | look a the 'Using a Hook' on here:
WP Codex | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, theme options"
} |
How to selected which tags to print, instead of printing the whole tag list?
When having this:
$tag_list = get_the_tag_list( '', ', ' );
I substituted the meta print:
printf(
$tag_list,
$category:list,
etc
);
by this:
$printArray_tag_list = explode(', ', $tag_list);
echo $category_list."/".$printArray_tag_list[0].','.$printArray_tag_list[1];
to print only the first two tags from the list (the first tags inserted in the post editor). Only then I realized that they are alphabetically ordered and those are not the tags I want to print.
Is there a way to print selected tags? Maybe selecting them in the custom fields? | By `get_the_tags()` you receive an array of tags attached to the current post. So you could do the following:
$tags = get_the_tags();
$tag_ids_to_print = array( 1, 2, 3 ); //List of Tag IDs which you want to be printed
$print_tags = array();
if( is_array( $tags ) ){
foreach( $tags as $tag ){
if( in_array( $tag->term_id, $tag_ids_to_print ) )
$print_tags[] = $tag;
}
}
$tag_list = '';
if( count( $print_tags ) > 0 ){
//Execute only, when tags found
$i = 0;
foreach( $print_tags as $tag ){
if( $i == 1 ) $tag_list .= ', ';
$tag_list .= '<a href="' . get_tag_link( $tag->term_id ) . '">' . $tag->name . '</a>';
$i = 1;
}
}
Docs:
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "post meta, tags"
} |
BCC email to subscribers
I have a custom post type "monthly bulletin" and need to send a blind email to subscribers when a new bulletin is published.
The code below works to send to subscribers, but emails are visible to all.
How do I amend the code to BCC subscribers?
add_action( 'transition_post_status', 'send_mails_on_publish', 10, 3 );
function send_mails_on_publish( $new_status, $old_status, $post )
{
if ( 'publish' !== $new_status or 'publish' === $old_status
or 'monthlybulletin' !== get_post_type( $post ) )
return;
$subscribers = get_users( array ( 'role' => 'subscriber' ) );
$emails = array ();
foreach ( $subscribers as $subscriber )
$emails[] = $subscriber->user_email;
$body = sprintf( 'Hey there is a new entry!
See <%s>',
get_permalink( $post )
);
wp_mail( $emails, 'New entry!', $body );
}
Thank you! | with the 4th parameter of `wp_mail()` you can extend the header of the Email. So you can use BCC there. This should work:
<?php
$bcc = 'Bcc: ';
$i = 0;
foreach( $emails as $email ){
if( $i != 0 )
$bcc .= ', ';
$bcc .= $email;
$i = 1;
}
$headers[] = $bcc;
wp_mail( '[email protected]', 'New entry!', $body, $headers );
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, email, notifications"
} |
Post Type Support Array Not Working
I am attempting to remove support from a post type, but I can't get the array to work.
I can get the string to work -- ` remove_post_type_support( 'product', 'editor' ); `
but not this array -- ` remove_post_type_support( 'product', array( 'editor','product_cat' ) ); `
nor even this array -- ` remove_post_type_support( 'product', array( 'editor' ) ); `
**FULL CODE** ` add_action( 'init', 'modify_product_type' ); function modify_product_type() { remove_post_type_support( 'product', array('editor','product_cat')); } ` | `remove_post_type_support()` doesn't support arrays. You have to unregister each feature separately.
See:
* <
* < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types"
} |
Redirect Every Instance of The Author Template Pages to Custom Author Pages
What I'm looking to do is actually a simple redirect, but for the EVERY page contained in the /author/ slug. The working slug I want to redirect to is /team/.
For example, if someone were to type in: 'www.mysite.com/author/jack-sparrow', it would automatically redirect them to 'www.mysite.com/team/jack-sparrow' (the 'team' page being a page I designed with the layout editor).
I can input these redirects manually, I'm sure, but there has to be some simple succinct bit of code unbeknownst to a noobie like me that automatically redirects ALL the author template pages and tells the site to "redirect ALL /author/[firstname-lastname] to /team/[firstname-lastname]"
I would be sincerely grateful for your help! | You do this with URL Rewriting. Locate your .htaccess file and add this line above `# BEGIN WordPress`
RewriteEngine On
RewriteRule ^author/(.*)$ /team/$1 [R=301,NC,L]
Note, if you put this inside the wordpress block it will get rewritten next time your permalinks are regenerated. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, pages, templates, redirect, author"
} |
Check if sidebar is rendered?
I want to check if there are sidebars rendered on the front end and if so output some body classes so I can style the page differently. I tried using _is_active_sidebar_ but that just returns true if the sidebar contains some widget (is active) - I want to check if it exists on the page. How can I do this?
My code looks like this:
In my single.php
<?php get_sidebar(); ?>
In my sidebar.php
if ( ! is_active_sidebar() ) {
// Add something here perhaps?
return;
}
?>
<div class="sidebar widget-area" role="complementary">
<?php dynamic_sidebar(); ?>
</div><!-- #secondary --> | If your certain sidebar widget area is page-specific then I think you need to load classes only to those pages. If so, use `is_page()` with it:
if( is_page('that-page') && is_active_sidebar('your-sidebar') ) {
$class = 'your-class ';
}
If it's true for all the inner pages other than the front-page, use:
if( !is_front_page() && is_active_sidebar('your-sidebar') ) {
$class = 'your-class ';
}
I think this _is_ the PHP way. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "sidebar, conditional content"
} |
Understanding the Template hierarchy
I've got a template called `News`.
When I go to the Dashboard and edit the Page called `News` which has a web address of `news.html` I can see it uses this template (i.e. in the Page Attributes > Template section).
However, if I then update the Template Name (i.e. in `page-news.php`) to something like `NewsTest` and refresh the News Page in the Dashboard I see that WordPress has updated the Template being used in the Page Attributes > Template section.
Here's another more specific example:
If I then edit the slug to `newsaaa` and the template name to `Newsbbb` it still shows up in the Page Attributes > Template section.
I have been working my way through the Template Hierarchy but am still a bit puzzled how exactly WordPress knows which file it should use for that Page.
Can anyone shed some light? | You need to look how page templates are saved against a page in the `wp_postmeta` table. Each page is linked to the specific template it uses and this is saved under the meta key `_wp_page_template`. You can go and have a look at your own install how you db structure looks like and how page templates are save
Wordpress does not use page slugs or page names but page id's to create the relationship to the page template assigned to it. Also, Wordpress does not use the template name to create the relationship to the page, but the page template file name. In the case of the default template, `page.php`, it is simply saved as `default` and not the file name
For that reason, you can rename the page slug and the template name to whatever you like and still have the relationship between the specific page and the template it uses.
Example:
 function, but I know that needs to be used before any other headers are sent. I can't seem to detect the terms AND use header() in the same place.
Any help is greatly appreciated!
Thanks! | There is a `template_redirect` hooks which is perfectly suitable for task like this.
1. Hook into `template_redirect`
2. Check your context (`is_single()`, etc)
3. Redirect with `wp_safe_redirect()` (if it's inside a site)
4. `die()` to prevent execution from proceeding | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy, redirect"
} |
Page editor missing Templates drop down
Update: As with so many mysteries, the cause turned out to be extremely stupid. I had the file saved in a different theme's directory. Thanks to @a4jp.com
I'm building a theme using underscores. I've created a template file and added a template header at the top.
<?php
/**
* Template Name: Featured
**/
get_header(); ?>
I'm not getting a Template drop down under Page Attributes in the page editor, so I'm not sure if there's a problem with my formatting or something else.
I did try switching themes. The drop down appears in the other theme, but when I switch back to my custom theme, it's still missing. | Maybe this will help.
<?php
/*
Template Name: Featured
*/
get_header(); ?>
Regular code here...
<?php get_footer(); ?>
If one theme works you could try replacing the files in the broken theme and test which file or files are broken. But first save the old files in a separate folder as a backup. Then you would know which file or files are broken pretty quickly. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 8,
"tags": "templates, page template"
} |
Alternatives to site_url() and get_template_directory_uri()
The problem I'm having is that my Wordpress is set up on localhost, but when I view the site from another computer,
"<?php echo get_template_directory_uri();?>/image.png"
will return
"
which of course doesn't load. But it all works fine when the Wordpress is viewed locally, or put onto a web server and viewed from any computer.
Similar issue with `site_url()` | Do you have to use localhost for any particular reason? The easiest fix for this will be to make those functions work correctly by putting a real hostname or ip address into the site address field in WordPress settings. Look in Settings > General Settings. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "urls, localhost, site url"
} |
Destroy user sessions based on user ID
I want to programatically log a specific user out of our WordPress system based on their user ID much like the 'Log Out of All Sessions' button in the WordPress user editor section.
How am I able to do this? | OK, simple solution after digging in the WordPress code.
// get all sessions for user with ID $user_id
$sessions = WP_Session_Tokens::get_instance($user_id);
// we have got the sessions, destroy them all!
$sessions->destroy_all();
This will log the user with ID `$user_id` out of WordPress.
**Use case:** My use case for this is when a user is approved moderation, but then the situation changes and they are declined, they will be 'kicked' from the system if they have any active login sessions. | stackexchange-wordpress | {
"answer_score": 18,
"question_score": 7,
"tags": "session, logout"
} |
Set user role on registration so can upload file to own media library area
I need my users to be able to upload files to the media library and therefore need to somehow automatically set the user role to something other than the default "subscriber" when they register.
I know in Settings > General you can set the ‘New User Default Role’, however if I change this to a role that allows user uploads this gives access to the main media library. If they could upload to their own media library that would be great but I don’t want everyone seeing everyone elses files in the media library.
I am using Buddypress but can't find any documentation on this and so have installed the Members Plugin to see if this would help but I am still struggling to find out exactly how this would be implemented.
Any help would be greatly appreciated. | I used the below code in the end. Hope someone finds this useful.
/* Display only user-uploaded files to each user in Media Library for file upload form*/
function user_restrict_media_library( $wp_query_obj ) {
global $current_user, $pagenow;
if( !is_a( $current_user, 'WP_User') )
return;
if( 'admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments' )
return;
if( !current_user_can('manage_media_library') )
$wp_query_obj->set('author', $current_user->ID );
return;
}
add_action('pre_get_posts','user_restrict_media_library'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users, buddypress, user registration, members"
} |
media sideload image not working with JPG file
`media_sideload_image` function not working for image url with JPG extension, its working fine for jpg (< and png (< but not with JPG (<
following is the error returned
[errors:WP_Error:private] => Array
(
[http_404] => Array
(
[0] => Not Found
)
)
[error_data:WP_Error:private] => Array
(
) | You should check for the special characters in url, sometimes url structures may contain special characters like space, &, ' .
use `str_repalce` to replace known special characters or `urlencode`.
media_sideload_image works properly with JPG as well so either url contains special characters.
If you can access image through url there is not a permission issue as well which blocks image download sometimes. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "uploads, media"
} |
Templates for Mobile Site
Is there any built-in method for displaying a different template based off of ~~browser size~~ device (i.e. mobile device detection)?
I've done some research and all I can find is a ton of plugins that do way more than I need them to. I essentially just need a way to add a /mobile directory to my theme, and display that theme for mobile users. | I ended up adding this to my head:
<?
if (wp_is_mobile()) {
include(TEMPLATEPATH . "/mobile/index.php");
return;
}
?>
And it worked out fine for my purposes. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "templates, mobile"
} |
getting a blank login page :( any way I can fix this without having to do a clean install?
here's the site: www.evolvtec.golocalexpert.com
Parse error: syntax error, unexpected '}' in /home2/inbrazil/public_html/evolvtec/wp-content/themes/Divi/epanel/custom_functions.php on line 1264
Here is the custom_functions.php line 1264:
function et_add_responsive_shortcodes_css(){
global $shortname;
if ( 'on' == et_get_option( $shortname . '_responsive_shortcodes', 'on' ) )
//responsive css if needed} | (See comments by others for your PHP error - though I'd recommend a good editor or IDE to help you spot syntax errors quickly and tidy the code for you as you type.)
Re: the question title, no, you usually don't have to do a clean install if there is an error with a theme and you find yourself locked out of the main site **and** `/wp-admin`.
There's a simple way to reset to the default WordPress theme (e.g. `Twenty Fifteen`).
* In (S)FTP etc., rename the theme directory from `Divi` to `Divi-temp`
* You should now be able to access `/wp-admin` again
* You'll see this message: "The active theme is broken. Reverting to the default theme."
* Now fix your theme / restore a working copy from a backup and re-enable it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, themes, parse"
} |
Are widget arguments always set inside My_Widget::widget()?
Specifically, are the `before_widget`, `after_widget`, `before_title` and `before_title` array keys always set inside `My_Widget::widget()`?
I'm wondering if statements such as the following are necessary (inside `My_Widget::widget()` for example)?
$args['before_widget'] = ! empty( $args['before_widget'] ) ? $args['before_widget'] : '';
$args['after_widget'] = ! empty( $args['after_widget'] ) ? $args['after_widget'] : '';
**Note:** My `My_Widget` class extends `WP_Widget` in case you were wondering. | This is mostly a case of trusting the arguments. Or not trusting.
* You can assume that you have received meaningful arguments, ready to be used.
* You can assume they are arbitrary and possibly grossly invalid.
I would say in this specific case it hangs if the code is public or private. In private site you have the full control over it, from sidebar registration to widget output.
Making widget for public distribution, I reason, would require much more strict checks and making sure it doesn't fall apart on receiving unexpected inputs. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, widgets"
} |
How to check if a rewrite rule exists
A common problem with rewrite rules added in a theme is that there is no obvious hook on which you can flush the rewrite rules. The problem is getting harder when you update a theme with new code that includes new rewrite rules.
It seems like a good solution to the problem might be to detect if the rewrite rule exists and if it doesn't to flush the rules. So how can I check if a rule already exists? | If I understand correctly then you can hook into the rewrite api/process and flush or manipulate the rules that way? Read: **Plugin Hooks** on this page
Maybe something like:
// flush_rules() if our rules are not yet included
function my_flush_rules()
{
$rules = get_option( 'rewrite_rules' );
if ( ! isset( $rules['(project)/(\d*)$'] ) ) {
global $wp_rewrite; $wp_rewrite->flush_rules();
}
}
add_action( 'wp_loaded','my_flush_rules' ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "rewrite rules"
} |
How to add new CSS file to new PHP file
I've made a new template file for Wordpress constructing the elements of the page via PHP and Wordpress recognizes the template as such.
Then I wanted to include a CSS file for said template (same folder) and went with the standard:
<link rel="stylesheet" type="text/css" href="style.css">
but for some reason the PHP file does not load the linked CSS settings. if I add
<? include('style.css') ?>
the content of it gets printed onto the page, meaning the php file can read it. So why doesn't it load the CSS settings?
Thanks for any help | CSS links are relative to the current request URI, not your PHP file. Use an absolute path like:
<link rel="stylesheet" href="<?php bloginfo( 'template_url' ) ?>/themesubfolder/style.css" /> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, templates, css"
} |
Add shortcode support to custom field
I'm using CMB2 and I have a wysiwyg field, and I want to display a formiddable form in it by shortcode, but the shortcode is not rendering, but does render in a normal page or post.
How do I enable shortcode rendering on these kind of custom fields? | @see <
Searches content for shortcodes and filters shortcodes through their hooks:
echo do_shortcode(
get_post_meta(
THE_ID_OF_YOUR_POST,
THE_NAME_OF_YOUR_CUSTOM_FIELD,
true
)
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "shortcode, plugins"
} |
Visual Editor - Colorize Shortcodes
I want to highlight shortcodes in the WordPress visual editor in a specific color. E.g. I Have the following Shortcodes
[shortcode1] Some text [/shortcode1]
...
[shortcode2] Some text [/shortcode2]
and want to give each of them a unique color, so the user could easily see what he should change.
I have found some solutions to syntax highlighting the HTML Editor but no one for the visual editor itself. | Managed to get a working solution.
What you need:
TinyMCE Advanced plugin
What you should do:
Customize the Visual Blocks Plugin that comes with the TinyMCE plugin and add css classes for each element you would to highlight (just loop through all p elements and parse the innerHTML and check if it contains your specific pattern).
Finally it looks something like this: !enter image description here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "wp insert post, wp editor"
} |
Shortcodes: override a shortcode / change shortcode on the fly
I've done a plugin where you can add shortcode like this: `[myplugin xx]` (where `xx` is a number which calls a specific content `xx`).
I have to do a multilingual version of my plugin, so here's my trick: my client writes content `xx` for language #1 and content `yy` for language #2.
Then, in an article, he would have to add something like:
[multilingualmyplugin #1 xx][multilingualmyplugin #2 yy]
and then I should just have to write a plugin that is called and change the content _before_ Wordpress calls my first plugin to either `[myplugin xx]` or `[myplugin yy]` depending on the domain name. Then Wordpress would call the plugin.
Is it possible and if so, where should I look? | Here's what I've done:created a shortcode where I do `[myplugin language="fr" id="5"][myplugin language="us" id="8"]` and then, when this page is called, it calls myplugin twice. If it's _not_ on the right page, my plugin returns nothing. So, when this page is called:
* if it's on a domain like "mydomain.fr" I just call `do_shortcode("othershortcode 5")`
* if it's on a domain like "mydomain.us" I just call `do_shortcode("othershortcode 8")`
It works like a charm! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode, multi language"
} |
Grabbing the page template name?
I am attempting to compare a username to a page template name. I found the following code:
get_post_meta( $post->ID, '_wp_page_template', true );
But this isn't quite what I am looking for. This returns the filename of the page template, IE:
templates/page-products.php
What I am looking for is the actual template name defined in the page template here:
/*
Template Name: products
*/
Is this possible? | An alternative to @Ben Cole that's less intensive (especially if you have several page templates), but not as awesome because it doesn't use the `WP_Theme` object ;)
function wpse_184317_get_template_name( $page_id = null ) {
if ( ! $template = get_page_template_slug( $page_id ) )
return;
if ( ! $file = locate_template( $template ) )
return;
$data = get_file_data(
$file,
array(
'Name' => 'Template Name',
)
);
return $data['Name'];
}
And in use:
echo wpse_184317_get_template_name(); // Template name for current page
echo wpse_184317_get_template_name( 14 ); // Template name for page ID 14 | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "page template"
} |
Pass the_post() as a parameter
I would like to take the following code sample
<?php while ( have_posts() ) : the_post(); ?>
<h2><?php the_field('title'); ?></h2>
<p><?php the_field('desc'); ?></p>
<?php endwhile; ?>
and convert it to use a function rather than putting all my code in my archive file. I would like to pass the the_post() as a parameter so I have access to all of the fields for a given content type.
function formatMyCustomPost($thePost) {
$html = "<h2>" . get_field('title') . "</h2>";
$html .= "<p>" . get_field('desc') . "</p>";
return $html;
}
and call it like this
<?php while ( have_posts() ) : the_post(); ?>
<php echo formatMyCustomPost(the_post()); ?>
<?php endwhile; ?>
Is this possible? | You may not need to pass in `the_post()`. Calling `the_post()` sets up the global $post object, and `get_field()` may also be accessing the global $post object | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, loop"
} |
Best location for theme translation files
I usually store language files in `/languages` folder that is located in theme folder and it's also recommended location by WordPress as well. However, it still doesn't look like the best solution because files will be overwritten after theme updates.
`load_theme_textdomain` function allows to specify a different location and I've been thinking to put languages folder inside of `/uploads` folder in order to prevent overwriting after theme updates. That folder will be created right after theme activation and language files will be copied there.
My question is, do you think this is a good solution or there is a better way that I'm missing?
I appreciate your insight about this matter. | ### Own theme
If you are using your own theme, no need to worry about, because `/languages` folder is in your control that way. :)
### Other's theme
But your concern is about other's theme and you want to apply your translations into that theme, then the best way is to make a **Child Theme**. Because you are actually _modifying_ that theme. Make your languages files and put them into your child theme's `/languages/` folder, and that's all.
If the parent theme is already translation-ready, it'll catch everything. But if it's not, then make a `functions.php` and show the translation-files' path:
load_theme_textdomain( 'theme-textdomain', get_stylesheet_directory() . '/languages' );
Note the `get_stylesheet_directory()` here, it's because we are showing the active theme's path. :) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "themes, translation, localization"
} |
Post with Custom Permalinks
My permalinks are set like:
`
Everything works fine.
But I am looking for a way to set the permalink like the following for only some posts (10-11 posts).
`
I want this because I am merging two WordPress websites and I don't want to loose the posts of the other website which are already published on Facebook etc with the old permalink structure. | You could use the Rewrite API. Since you have a fixed set of posts you could do the following:
add_action( 'init', 'rewrite_old_slugs' );
function rewrite_old_slugs(){
$post_slugs = array(
'post-1' => 1,
'post-2' => 2
);
foreach( $post_slugs as $slug => $new_id )
add_rewrite_rule( $slug . '?$', 'index.php?p=' . $new_id, 'top' );
}
I've created a post_slugs array where the array keys are the old slugs and the array values are the post ids.
If you go this way, you have to go to Settings > Permalinks and hit the update-button, so the rules are active.
This solution works for posts. If you need it for pages, you need to rewrite the URLs to
index.php?page_id= | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "permalinks"
} |
Multisite > Edit Site > Themes - what are these themes?
I'm looking at the Dashboard of a specific site in a Multisite setup using WordPress 4.0.1.
If I go to Edit Site (by mousing over the Home icon at the top) the Info tab gives some information about the current site.
However if I go to the Themes tab it lists some Themes. There's a line at the top that says "Network enabled themes are not shown on this screen.". None of these listed Themes are the Activated Theme for the current site. Why are they listed? | I do not currently have access to a multi-site, but as far as I remember: Each site in the multi-site install can have their own theme; same with the plugins. However, you can install themes in the main site profile and it will display as optional themes for all the other sites in the multi-site install.
I am not sure I answered your question. Please elaborate and/or include screenshots if I missed. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, themes"
} |
Separated Comment from Post
I'm designer with little knowledge of wordpress (newbie >_<)
i use Worpress starter theme from : html5blank.com
i want to separate **COMMENT** section from **POST** section, this still on one single.php page. I have look link but didnt worked for me ( look like because theme hirarcy of Twenty Eleven and my theme (html5blank) diferent ),
here the design of the web : <
* POST section
* Related Post section
* **Comment section ---> (1) i want to separated this** | ahaaa :D it's success, I use CSS. Here the screenshot !Separated comment from post page
the code i use on **single.php** :
<!-- post section -->
<section class="post-section all-round grid">
<div class="content_wrapper">
<!-- YOUR CONTENT -->
</div>
</section>
<!-- end .post-section -->
<!-- comment section -->
<section class="comment-section all-round grid">
<?php if ( comments_open() || get_comments_number() ) : ?>
<?php comments_template(); ?>
<?php endif; ?>
</section>
<!-- end .comment-section -->
<?php endwhile; ?>
<?php else: ?>
**CSS code :**
/* SECTION TO SEPARATE POST AND COMMENT */
.post-section, .comment-section {
background-color: white;
width: 900px;
margin:20px auto;
}
the schema :
* LOOP
* < Post >
* < Comment Section >
* END LOOP | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "theme development, comments"
} |
How to trace shortcode to its functionality
I am trying to modify a plugin and I need to trace its shortcode to the functionality page(s). Is there a way to parse a shortcode? | What I always do is, I search the files...
So I use the "Search in files"-function in Notepad++ (which I am using) and limit the search to the directory, where I think, I will find what I am looking for.
So, probably, you know already the plugins directory. You enter this information into the folder input line e.g.:
c:/xampp/htdocs/wordpress/wp-content/plugins/plugin-with-sortcode/
When I am looking for a function I search
function NameOfFunction(
Shouldn't I find it, I try sometimes without the `function` part.
You are searching for a shortcode, you could try things like
add_shortcode( 'nameOfshortcode'
add_shortcode('nameOfshortcode'
add_shortcode( "nameOfshortcode"
You see, I alter the quotation marks as well as the spaces. If the first doesn't work maybe the second or the third spelling.
Hope this helps. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "shortcode"
} |
Trying to run website a php file is blank
I have a local copy of a website I am working on and I just found that the index.php files are almost empty. They contain only an opening php tag followed by a commend that says: "Silience is golden."
This is the strangest thing, why could this be and what can I do to fix it? | That's normal and expected inside the `wp-content`, `themes`, and `plugins` directories. Their presence is to prevent listing of directory contents if people navigate to those directories via http. There's nothing wrong there and no fix is required. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
How to register a menu based on a ACF condition
I am trying to register a Wordpress menu, depending on a ACF field condition.
$logo = get_field('logo','options');
if ($logo) {
register_nav_menus(array(
'brand_centered_left' => __('Brand Centered Navigation (Left)', 'roots')
));
}
However, if I test this code, the navigation does not show. It seems like ACF and functions.php does not work well together, but im not sure.
I am adding this code in my nav.php (which is an include in my functions.php file).I am using Wordpress + ACF 5.0 and Wordpress Roots theme.
Any ideas?
Edit
* * *
So I tried calling the field directly:
if (get_field('logo','options')) {
register_nav_menus(array(
'brand_centered_left' => __('Brand Centered Navigation (Left)', 'roots')
));
}
and it works! But then again if I try just using $logo it won't work.
Weird! | Ok, so the problem was that I was adding the variable outside the function. After some cleanup, code looks like this and it works!
function roots_setup() {
// Variables
$header_type = get_field('header_type','options');
if (($header_type)=='brand-centered') {
register_nav_menus(array(
'brand_centered_left' => __('Brand Centered Navigation (Left)', 'roots')
));
register_nav_menus(array(
'brand_centered_right' => __('Brand Centered Navigation (Right)', 'roots')
));
} else {
register_nav_menus(array(
'primary_navigation' => __('Primary Navigation', 'roots')
));
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, menus"
} |
Why does my site show the correct front-page when you arrive at the site, but not when you click 'home'?
I have a website (derbyskillbuild.org.uk) and the 'home' button leads to a diffent page than the 'front-page':
* When you arrive at my website, it displays the correct front-page.php with the loop on the right hand side.
* When you click 'home' in the navigation, a standard page is displayed without the loop.
Why? | Welcome to stackexchange. When asking a question please try to be as specific in your question as possible. Try describing what you want to know – also using screenshots or wireframes is ok – but please avoid forcing others to ckick on a link to understand your question. Questions like "How can I do this?" are usually not very likely to get a lot of attention from the community.
That said – I did click the link – and I see two pages: the "home" page and the _front–page_.
If you want the "home" button to direct users to your _front–page_ , you can do this in Wordpress's admin interface under `Appearance > Menus`. Basically there are various ways to to this – here's two approaches, leading to the same ersult: Depending on how your site is / your menus are configures I would either make the " _home_ " button link to "/" manually, or add a new custom button "home" (linking to "/") and remove the old one (linking to "/home"). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "frontpage, menus"
} |
How to get the post type from a category id?
I am trying to find out the post type from a category id.
Suppose that, when i am opening a category page
localhost/project/foobaar/category/pen
I want to know the post type to which category - pen is attached to. I have two custom post type named "book" and "copy" If category pen is associated with book, then it should return the post type as "book" Similarly if category is pencil, then it should return "copy" as i have used pencil category in "copy" post.
I was trying to do something like this as (i have the category id stored in variable but assume category id of pen is 12)
$args = array (
posts_per_page => 1,
category => '12' // category id of pen
);
$posts = WP_Query( $args );
And from $posts I could get one post from which I could knew, but $args is using default post_type as 'posts' and my posts can be anything.
Thanks | You can just grab the first post from the main query and see which post type it is:
if ( have_posts() ) {
$post_type = $wp_query->posts[0]->post_type;
}
If you run this code directly in a main template file you should be fine, but if it's in a function you will need to call `global $wp_query;` first. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, posts, categories, taxonomy"
} |
Display a post via template
I want to display a single post in the sidebar-area (not the sidebar itself) and can't seem to get it working. I know the post_id (it's 1571 btw), so I looked around and only found this link from 7 years ago: Display Posts from a specific Category in the Sidebar
So after looking around, I found the useful functions "get_posts()" and "get_post()". First one requires an array which is not what I want as it is a single post. Second one.. well that's where I am so far:
<?php get_post('1571');?>
Can anyone please help me with this?
**edit01:** I am able to display the post's title by using
`$post_id_1 = get_post($my_id);` `echo $post_id_1->post_title;` | `get_post()` returns a post object. So you can try the following
$post = get_post( 1571 );
setup_postdata( $post );
the_title();
the_content();
wp_reset_postdata(); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, templates, sidebar"
} |
Showing a Thickbox (tb_show) does nothing
I'm trying to add a media uploader to a widget/plugin and I'm at the stage where I need to add a picture from the media library (or upload a new one).
I added some javascript and added an event to a button in the plugin. This event gets fired (because the alert is displayed), but the thickbox does not show up.
Here's the JS code:
jQuery(document).ready(function() {
jQuery('.upload_image_button').click(function() {
alert('This alert is displayed');
tb_show('Upload a Image', 'media-upload.php&type=image&TB_iframe=true', false);
return false;
});
});
Why isn't the Thickbox displayed?
_WordPress version 4.1.1_ | Answer can be found here: <
Even though the problem described isn't exactly the same as I had, the code posted in the answer still helped me as that code actually does exactly what I needed.
I also think that I didn't originally find this answer as it's on the regular Stack Overflow and not the Wordpress part of it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "widgets, thickbox"
} |
Woocommerce Filter Main Loop by Tag
**Two questions:**
1. How can I modify the query results of the archive and search pages exclude the product-tag "audio"?
2. How can I make the Recent Products shortcode of Woocommerce exclude the product-tag "audio"?
_I've created my another shortcode that will display the audio products separately._ | **First Question:** Solved by copying and modifying the "archive-product.php" template file.
if(is_product_tag(array('audio'))) :
include 'archive-product-audio.php'; // includes custom loop
else:
// default archive loop
endif;
**Second Question:** Solved by simply filtering the Recent Products shortcode via "function.php".
add_filter('woocommerce_shortcode_products_query', 'removeAudioTags');
function removeAudioTags($args){
$args['tax_query'] = array(array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => array('audio'),
'operator' => 'NOT IN'
));
return $args;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode, tags, woocommerce offtopic"
} |
How to request admin-ajax.php correctly when wordpress URL and site URL are different?
When _site_url()_ and _home_url()_ are different, how a request should be directed to _admin-ajax.php_ (both in front-end and admin)? Using A. `admin_url('wp-admin/admin-ajax.php')` or B. `home_url('wp-admin/admin-ajax.php')`
Usually method A is used. However for some websites this request gives error 404 in front-end. Method B does not work when wordpress is located in some sub-directory with respect to home_url().
Is there any method that works in all the cases when site_url() and home_url() are different?
See also here for the differences between site_url() and home_url(): What's the difference between home_url() and site_url() | `admin_url()` should be used.
> However for some websites this request gives error 404 in front-end
`admin_url('admin-ajax.php')` should point to an actual file (`admin-ajax.php`), as such WordPress won't pass it through `index.php`, and so it _shouldn't_ lead to the theme's 404 page. (Unless the file has been deleted).
... unless you have a `.htaccess` file which is redirecting the user away from `wp-admin` (for example) (a recent client of mine had been doing this to whitelist IP addresses that could reach `wp-admin`). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, ajax, front end, wp config"
} |
How to trigger WooCommerce order complete email?
I want to be able to trigger the WooCommerce order complete email at a different stage in the WooCommerce checkout process. So I've disabled WooCommerce order complete email from the backend and am now looking for a line of code that will trigger the email at the point that I want. I've done a bit of research and I've found how to _remove_ the order complete email but not how to trigger it manually. Any tips?
Thanks! | You can try this
$mailer = WC()->mailer();
$mails = $mailer->get_emails();
if ( ! empty( $mails ) ) {
foreach ( $mails as $mail ) {
if ( $mail->id == 'customer_completed_order' ) {
$mail->trigger( $order->id );
}
}
} | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 12,
"tags": "php, woocommerce offtopic"
} |
how to create shortcode in wordpress
So I have the following code:
<span class="delete"><a onclick="return confirm('Are you sure?');" href="<?php echo wp_nonce_url( add_query_arg( array( 'action' => 'my-delete-product', 'product_id' => $post->ID ), my_get_navigation_url('products') ), 'my-delete-product' ); ?>"><?php _e( '', 'my' ); ?></a> | </span>
It is a simple button.
I want to make this into a shortcode so that I can use it anywhere where appropriate.
Any suggestions?
Thanks. | You can create your short code just few steps.
function short_codeFunction_name( $atts, $content=null ) {
shortcode_atts( array(), $atts);
$rowin = '<div class="row">'.do_shortcode( $content ) .'</div>';
return $rowin;
}
add_shortcode( "your_shortcode_name", "short_codeFunction_name" );
1. Then you can access `[your_shortcode]Here your content[your_shortcode]` format inside the Post,page etc.
2. add this function inside function.php in active theme directory.
3. use inside your theme directory | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, shortcode"
} |
Why would this IF statement not work?
I've placed the following conditional statement in my footer.php file but it isn't working. I want it to show the footer on every page except for single.php and the services.php template:
<?php if (!is_single() || !is_page_template('services.php')) {?>
<footer>Content</footer>
<?php } ?> | You need to use the `AND` (`&&`) operator to make this work. As your condition stands, it will return true no matter which page you are on. The `OR` operator only needs one true to execute where as the `AND` operator needs all conditions to be true to execute
I just have one other concern here as you are loading your footer conditionally, and that is, you should make sure that you remove `wp_footer()` from that condition, you should not load it conditionally as this will break many scripts that is loaded in the footer. So make sure that you don't load `wp_footer()` conditionally | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, conditional tags, footer"
} |
Main menu gets replaced when second menu is created
I have a menu (main menu) and i call it with `<?php wp_nav_menu( $args ); ?>`. It works normally, and is set to Primary Location.
But when I create another menu, the new one replaces the main menu. The theme is custom made, so obsiously is something I'm missing about WP menus. Aany help is much appreciated. | Maybe your second menu has the same id as your main menu when you registry these menus. One more thing, make sure that you go to Dashboard > Appearance > Menus, tick to the box Location for the menus properly. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "menus"
} |
Finding and removing unnecessary redirects
I have a bunch of redirects to sites like sharethis, media6, and some random character urls. Most of these are leading to a blank pixel or each other. I know a lot has to do with facebook and needed resources but how would I find out where these are being loaded from? So I can figure out what plugin is causing them and remove it if its not necessary.The last three are the main problem. But when I search the source I can not find them so it has to be some JS thats loading them. Also is there an easy way maybe at the server level (nginx) to access all these resources from my server through a cache or something? Short of changing the code to load them locally.
| I ended up solving this using the WP-Do-Not-Track plugin. I was able to black list all the addresses I did not want loaded. it works great and does not seem to change my page load speed.
A lot more than add to any was causing these. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "url rewriting, html"
} |
Advanced Custom Fields: Conditional Statement with Select
I've set up a select field labeled "asset_type" with two values: "image" and "video". I then have two fields that rely on conditional logic to be displayed. If "image" is selected from the select I show the "image_asset" field, and if "video" is selected from the select I show the "video_asset" field. Reading through the docs and a few other stack questions, I thought I had the logic setup correctly, but for the life of me can not get the content to display. This is what my code looks like:
<?php if(get_sub_field('asset_type') == "image") { ?>
<div><?php the_sub_field('image_asset'); ?></div>
<?php } ?>
<?php if(get_sub_field('asset_type') == "video") { ?>
<div><?php the_sub_field('video_asset'); ?></div>
<?php } ?>
Any help or advice is greatly appreciated, thanks! | Just for the sake of closing the question:
<?php if(get_sub_field('asset_type') == "Image") { ?>
<div><?php the_sub_field('image_asset'); ?></div>
<?php } ?>
<?php if(get_sub_field('asset_type') == "Video") { ?>
<div><?php the_sub_field('video_asset'); ?></div>
<?php } ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "advanced custom fields, conditional tags"
} |
PHP inside echo HTML?
I am a little bit confused about the following code:
<?php
if (is_home() ) {
echo '<div id="bg" style="background:url("assets/img/header_1.jpg");">';
} else ( is_page( 52 )) {
echo '<div id="bg" style="background:url("assets/img/header_2.jpg");">';
}
?>
It is supposed to change the header background for different pages.
The code itself works, because CSS classes were imported correctly. Unfortunately "/assets/..." doesn't work so I suppose I need this function:
<?php echo get_template_directory(); ?>
How can I implement it properly inside echo? | You can concatenate strings with the result of a php function:
echo '<div id="bg" style="background:url(' . get_stylesheet_directory_uri() . '/assets/img/header_2.jpg);">';
Codex: `get_stylesheet_directory_uri()` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "conditional tags"
} |
How can I count only guests comments?
I need to ignore counting author replies within comments number function, for example If I have 9 replies (comments) which 4 of them appertain to post author, I would display 5 comments as comments number in my post.
Do you know any method to do it?
Thanks in advance. | You can use these inside `the loop`, or in `comments.php`
//The author of current post
$author_ID = get_the_author_meta("ID");
//The current post ID
$p_ID = get_the_ID();
//Number of guest comments
echo count(get_comments(array(
'post_id' => $p_ID,
'author__not_in' => array($author_ID)
)));
More: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "comments, count"
} |
How get posts from a subcategory of a category by name?
I'm trying to create a subcategory template of a defined category. For example, for each one, I would like to check if his subcategory `Photos` exists and to get posts of this.
Here is my category tree:
— Category Sessions
— — Subcategory Session 2015
— — — Subcategory Photos
— — — Subcategory ...
— — — Subcategory Videos
— — Subcategory Session 2014
— — — Subcategory Photos
— — — Subcategory ...
— — — Subcategory Videos
— — Subcategory Session 2013
— — — Subcategory Photos
— — — Subcategory ...
— — — Subcategory Videos
If subcategory `Photos` of **this** session category exists :
My idea is to have a query such as :
`$wp_query = new WP_query(... Session 20XX/Photos ...&showposts=20);`
Is there a way to do that please? | // Getting Parent ID
$parent = get_term_by( 'name', 'Session 2015', 'category');
// Checking if SubCategory Exist.
$term = term_exists('Photos', 'category', $parent->term_id);
//if Exist Do the query
if ($term !== 0 && $term !== null) {
$query = new WP_Query( 'cat='.$term['term_id'] );
}
References:
* `term_exists`
* `get_term_by` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "wp query, categories"
} |
How to get the current user post and it's ID?
I have a site setup so users can publish a post via the frontend, what happens is, there post is posted as a status, 'Pending Review, in a custom post type.
How can i get the post ID for this particular post the user has just published?
The posts author status is also set to the particular user that submitted the post.
I can get the author's ID using this.
$user_ID = get_current_user_id();
Hope this makes sense and thanks for the help. | So digging around a little i couldn't find a solution where the WP_Query wasn't used, so i just stuck with the query method, Using WP_Query this snippet will display the latest post that is published by the user that is logged in.
$user_id = get_current_user_id();
$args=array(
'post_type' => 'POSTTYPE',
'post_status' => 'published',
'posts_per_page' => 1,
'author' => $user_id
);
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
the_title();
endwhile;
Hope this helps someone.
Cheers
Matt | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, get posts"
} |
How can I delete all inactive widgets?
I want to cleanup all inactive widgets. I tried following snippet as suggested by this answer Script to remove all inactive widgets?.
$sidebars_widgets = get_option( 'sidebars_widgets' );
$sidebars_widgets['wp_inactive_widgets'] = array();
update_option( 'sidebars_widgets', $sidebars_widgets );
I also tried deleting option `sidebars_widgets` directly from the options table.
But after page is refreshed, old value is restored with all inactive widgets. How can I remove all those inactive widgets at once? Thanks in advance. | You should do it with `after_setup_theme` action:
function remove_inactive_widgets() {
$sidebars_widgets = get_option( 'sidebars_widgets' );
$sidebars_widgets['wp_inactive_widgets'] = array();
update_option( 'sidebars_widgets', $sidebars_widgets );
}
add_action( 'after_setup_theme', 'remove_inactive_widgets' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "widgets, admin, wp admin"
} |
I want to develop a theme using WordPress. Which theme should I start from or develop from scratch?
I want to develop a WordPress theme similar to another theme present on the internet. Shall I use the default WordPress theme to start from or start from scratch?
Please guide me. | Go with WordPress TwentyFifteen or any other default theme.
You don't have re-invent the wheel, you will save a lot of time. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes"
} |
Read post meta values, only if posts are public
I want to retrieve meta_values applied to posts.
Currently I execute the following query
global $wpdb;
$table = $wpdb->prefix.'postmeta';
$values = $wpdb->get_results(
"SELECT meta_value FROM $table WHERE meta_key = '$metakey' GROUP BY meta_value",
ARRAY_A);
This returns all possible `meta_values`. Is there any possibility to retrieve only the `meta_values` of posts with `post_status` **published** (and not **private** ). | Yes, do an `INNER JOIN`, something like this should work:
$values = $wpdb->get_col($wpdb->prepare("
SELECT meta_value FROM $wpdb->postmeta
INNER JOIN $wpdb->posts
{$wpdb->posts}.ID = {$wpdb->postmeta}.post_id
WHERE meta_key= %s
AND {$wpdb->posts}.post_status='publish'"
,$metakey
));
I changed `$wpdb->get_results()` to `$wpdb->get_col()` since it looks like you are just selecting a single column of data as an array. I also added `$wpdb->prepare()` since that is generally best practice. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "post meta, wpdb, select"
} |
Mobile navigation is shown, but standard navigation does not disappear
I have setup that website berlin-permanent-makeup.de and the mobile navigation kicks in, as soon as the screen is smaller than 800 px wide.
So far, so good. My problem is, the standard navigation does not disappear.
That means, I have now the same navigation twice. Once in ugly broken words, once in the mobile button menu.
You can see for yourself on the above-mentioned link.
Thank you in advance. | In that case, you should try below
.nav-holder { display: none; }
on media.css line no. 115 | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, navigation"
} |
current_post not working - give me -1 for every post
I try to get the current post index number and echo the number of this lesson(post)in a series of lessons(category).
I'm inside the loop on single.php page
my code looks like this:
$args = array(
'cat' => 22,
);
$query = new WP_Query( $args );
echo $query->current_post;
echo $query->post_count;
the "$query->post_count" works great and give me the number of the posts that are inside this category, but the "$query->current_post" don't work and give me "-1" all the time in every post...
what i'm doing wrong? | What you are seeing is totally expected as you are trying to get the value of `$current_post` outside the loop. Before and after the loop, the value of `$current_post` will always be set to `-1`.
To get the proper value, you need to check `$current_post` inside the loop, the first post will be `0` and this will increase by one on every iteration of the loop.
For more info on creating the `Post X of Y` thing, check out these site searches on this issue | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp query"
} |
wp_nav_menu work in functions.php but not in the theme
I use `wp_nav_menu` with this code in `functions.php`:
register_nav_menus( array(
'sidebar_menu' => 'Sidebar menu',
'topmenu' => 'topmenu',
) );
$args = array(
'theme_location' => 'topmenu'
);
wp_nav_menu( $args );
This code works. The menu will show up before everything else in the theme. Now I want to menu inside my `header.php` for example and I try to move the code there:
$args = array(
'theme_location' => 'topmenu'
);
wp_nav_menu( $args );
I expected the code to work here as well but it does not. The menu is empty. The function `register_nav_menus` is still in the `functions.php`. The `header.php` is loaded correctly.
**The code below returns true in the`header.php`**
if ( has_nav_menu( 'topmenu' ) ) {
echo 'true';
}
Why does the menu show up empty? | I had a `pre_get_posts`. What I missed was this:
&& $wp_query->is_main_query()
This prevents the `pre_get_posts` to run on the menu query.
**Full code**
add_action("pre_get_posts", "custom_front_page");
function custom_front_page( $wp_query ){
if( is_admin() ) {
return;
}
if( is_front_page() && $wp_query->is_main_query() ) {
$wp_query->set('post_type', 'produkt');
$wp_query->set('page_id', '');
$wp_query->is_page = 0;
$wp_query->is_singular = 0;
$wp_query->is_post_type_archive = 1;
$wp_query->is_archive = 1;
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, theme development, menus"
} |
get_posts with multiple categories
If I do a get_posts() with category set to 1,2 I will get all posts in category 1 OR 2. If i want all posts whit both categories, that is 1 AND 2, how do I make that request? | As documented in the codex you could use the following
`$query = new WP_Query( array( 'category__and' => array( 2, 6 ) ) );` //post has to be in category with ID 2 AND 6 | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 5,
"tags": "wp query, categories, get posts"
} |
PHP error when trying to upload .mp3 files via Media Library
When I'm trying to upload a sound file (mostly .mp3's) via the media library, I get the following errors:
Warning: require(/path/to/website/wp-includes/ID3/getid3.php): failed to open stream: No such file or directory in /path/to/website/wp-admin/includes/media.php on line 2997
Fatal error: require(): Failed opening required '/path/to/website/wp-includes/ID3/getid3.php' (include_path='.:/usr/share/php:/usr/share/pear') in /path/to/website/wp-admin/includes/media.php on line 2997
First I thought there is a permission error, but after an hour of checking every file/folder permission, I didn't find anything out of order (files 644, folders 755).
I also tried to search on google of course, but I didn't find any forum topics related.
Any ideas? | Found the problem. It was a problem with my host, in the path the ID3 folder name was uppercase, while on the server for some reason it was lowercase, this is why it didn't find it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "uploads, media, errors, media library, fatal error"
} |
how to add wp-user fields to front-end form
I've found all kinds of information on how to add user-meta fields to a front-end form. However, I can't find how to add email and the change password.
I found the form fields in user-edit.php, but what to use in place of update_user_meta()? | Something like this should point you in the right direction:
function updateUser($newPassword = '', $newEmail = ''){
$update = array();
if(!empty($newPassword))
$update['user_pass'] = $newPassword;
if(!empty($newEmail))
$update['user_email'] = $newEmail;
if(!empty($update)){
$update['ID'] = wp_get_current_user_id();
return wp_update_user($update);
}
return;
}
See `wp_update_user()` for more info on how that function works. You should also verify the source of the post data with a nonce. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, profiles"
} |
how to read database fields
Can someone please explain how to read the letters, numbers, and colons in the wordpress database?
For example:
a:1:{s:13:"administrator";b:1;}
in the wp-capabilities table.
Thanks! | Those are php serialized constructs. The one you have there is an array. If you are looking to read them as a human, it breaks down like this:
Array: a:size:{key definition;value definition;(repeated per element)}
String: s:size:value
There are other possibilities that you can read more about here.
Generally, you should never modify these directly since unless you do it perfectly you will break the record. To manipulate them with php you'd `unserialize()`, manipulate, and then re`serialize()`. e.g.
//get $my_serialized_variable from database
$value = unserialize($my_serialized_variable);
$value[] = $element_i_want_to_add;
$serial = serialize($value);
//write serial to database
If you absolutely have to modify it in the database, use a tool like this to make sure you have a valid serial. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "database"
} |
Can not manually create a database ( db, user, pass ) for a plugin
So I was working on a plugin and I needed to cache some third party API access, and I needed to manually create a database upon plugin activation or upgrade.
The caching stuff needs a database host ( localhost I guess ), a username and a pass, as in the code:
mysql_connect($db_host, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
I have followed many tuts in terms of creating databases, but I couldn't end solving my issue.
Any thoughts ?
Regards,
Thank you lots! | As per GentlemanMax's comment, you'll want a table.
There's a really useful guide in the Codex (which also goes into how to do DB upgrades / migrations.)
One thing I'd emphasise: make sure to use `$wpdb->prefix` in the table name because not all sites will have tables beginning `wp_*`.
Also, if you're ever planning to distribute your plugins to other people, remember not every WordPress cloud hosting services will allow their customers to use custom tables (some of the larger ones allow the standard WordPress tables or preapproved plugins only – which is irritating but worth bearing in mind.) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, database, sql"
} |
How to make a widget expand wider than the column width when editing its settings in the admin
The WordPress Text widget expands horizontally beyond the margin of the sidebar when added to a sidebar and opened in the admin and I am trying to apply that function to a widget. I see inline css is being dynamically injected when the widget tab is opened and inserts as
div style="z-index: 100; margin-left: -88px;" id="widget-50_text-4" class="widget open"
and though the widget, when opened, is wider than the sidebar, I am not seeing any width property. I figure it is being done with javascript and I have achieved the similar behavior using jQuery .css() but it is not screen size responsive as is the WP text widget, and I had to insert a width value.
Is there an add_filter function to execute this action?
!Image Example | This can be set by passing arguments to the $control_options of the parent widget constructor, which is the fourth argument. Here is an example constructor:
class Custom_Widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
function __construct() {
$widget_options = array(
'description' => __( 'Featured Pages Widget.', 'affiliate' )
);
$control_options = array(
'width' => 750
);
parent::__construct(
'custom_widget', // Base ID
__( 'Custom Widget', 'text_domain' ), // Name
$widget_options,
$control_options
);
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "filters, widgets"
} |
Remove "nofollow" from widget_text
How can I remove rel "nofollow" from a widget_text? I'd like to try a solution without install a plugin. Thanks. | It sounds as though a plugin or theme function is already adding 'nofollow' to the widget, so it might be a case of needing to remove a plugin not add one.
It might be being added in your Theme's functions file with the following function: wp_rel_nofollow
You could try searching for that function thought your plugins and themes. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "nofollow"
} |
pre_user_query meta_query admin user list
I'm attempting to use `pre_user_query' to change the query to include some`meta_query` variables.
My goal is to only display users in the user list if they share a common `meta_value` with the current logged in user...
function modify_user_list($query){
$user = wp_get_current_user();
if( ! current_user_can( 'edit_user' ) ) return $query;
$user_id = $user->ID;
$user_branch_number = get_user_meta($user_id, 'user_branch_number', true);
$query->query_vars['meta_key'] = 'user_branch_number';
$query->query_vars['meta_value'] = $user_branch_number;
$query->query_vars['meta_compare'] = '=';
}
add_action('pre_user_query', 'modify_user_list');
If I `print_r` the query it will show that the `query_vars` have been updated appropriately, but the user list in the admin panel is unaffected - same old list of every single user. | You are using `pre_user_query` according to WordPress documentation
> Fires after the WP_User_Query has been parsed, and before the query is executed
Then you should use `pre_get_users` just like `pre_get_posts` when your arguments have some meaning to WordPress.
> `pre_get_users` Fires before the WP_User_Query has been parsed
Replace your hook with
`add_action('pre_get_users', 'modify_user_list');` | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "users, wp user query"
} |
Proper way to set up rewrite with Wp
This seems to be modding my .htaccess with every page view. What is the standard way of setting up a rewrite? This is what I have so far:
if(!function_exists('some_rewrite')){
add_action( 'init', 'replacement_rewrite' );
function replacement_rewrite( )
{
global $wp_rewrite;
$wp_rewrite->add_permastruct('typename','typename/%year%%postname%/' , true , 1);
add_rewrite_rule('typename/([0-9]{4})/(.+)/?$','index.php?typename=$matches[2]', 'top');
$wp_rewrite->flush_rules();
}
} | See `flush_rules` in Codex:
> Because this function can be extremely costly in terms of performance, it should be used as sparingly as possible - such as during activation or deactivation of plugins or themes. Every attempt should be made to avoid using it in hooks that execute on each page load, such as init.
Only flush rules when they change, not on every page load. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "url rewriting, htaccess"
} |
How do you access the Product Short Description in a WooCommerce email template?
I would like to output the Product Short Description beneath the product name inside the order items table inside WooCommerce emails. I think I know where to place code inside the email template file, but I don't know how to access the description of an item. I don't see any mechanism to retrieve it. What do I need to do to echo out the field?
Thanks in advance! | I finally tried using `var_dump()` on `$item` and `$_product`, which are both used in the `email-order-items.php` template. `$_product` revealed a `post` object, which itself has a `post_excerpt` property, which looks like it holds the contents of the "Product Short Description" from the WooCommerce product form.
So, to add the description beneath the item name, I added this to my code:
`echo '<br/>' . $_product->post->post_excerpt;`
Voilà! The short description appears in the email!
Hope this helps someone else! Took me a couple hours of frustration to get it. | stackexchange-wordpress | {
"answer_score": 19,
"question_score": 9,
"tags": "templates, email, woocommerce offtopic"
} |
Can't understand $atts in functions?
I'm not sure if I don't fully understand the basics of functions in php or maybe it is WP convention that I am not sure of. My question is why use an argument in a function when it is not going to be used?
take the following code for example.
add_shortcode( 'tf', 'ch2ts_twitter_feed_shortcode' );
function ch2ts_twitter_feed_shortcode( $atts ) {$output = '<a href=" Feed</a>';
return $output; }
$attr is not even used but still passed as an argument? Please explain. | In general, if arguments is not used or the defaults values are to used of an argument/parameter, you don't have to write it out, they can simply be omitted. The only time when you have to pass any value to an argument is when a function expect a valid value to be passed to it in order to properly execute, something like `get_terms()` which expects the first argument to have a valid taxonomy value
In your example, using shortcodes, it is not necessary to pass `$atts` as you are not expecting any values from attributes and you have not set up any attributes inside your shortcode function. Your shortcode simply returns a static value. In a case like this, you can simply just omit `$atts` | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "shortcode"
} |
Removing Custom Permalink Structure for Custom Post Type
I'm using a custom permalink structure for posts, which is domain.com/blog/%postname%/. However, I have a custom post type called 'events', and I don't want to use the default custom permalink structure for this custom post type, as domain.com/blog/events/ doesn't make sense. I want to just use domain.com/events. How can I override the custom permalink structure for a custom post type? I've found plugins that will allow you to set a custom permalink structure specifically for custom post types, but they won't allow me to remove the base permalink structure, only extend it. | Setting `with_front` to `false` solved the issue. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, permalinks"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.