INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Why does Jetpack insert it's script outside the <html> tag?
I went to validate my HTML with the W3C validator and I got this error:
Line 463, Column 77: Stray start tag script.
…t src=" type="text/javascript">
This script is insterted by the Jetpack plug-in for the statistics, but it is inserted outside of the html tags, which ruins my validation!! Any ideas how to fix that?
Thanks. | Make sure your theme calls the `wp_footer()` function before the closing body tag, and scripts will be output in the correct location. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin jetpack"
} |
Script dependencies for post.js
I have already got the built in meta boxes displaying on the front, but some of them require the accompanying `wp-admin/js/post.js` to function correctly. I'd rather not rewrite anything here and just include what is already written. The problem is there are variables in the file which must be declared somewhere else, `postboxes` for example. Does anybody know where in the core files this file and/or it's dependencies are defined?
If anybody is wondering, this is part of a front end administration plugin. | Because of the dependency handling built into the script registration system you should only need ...
wp_enqueue_script('post');
... to load all of the required scripts, which is exactly what the Core does.
But just loading the scripts isn't going to make everything work. That form is actually loaded by `wp-admin/post.php`, which `require`s `wp-admin/admin.php` which `include`s and `require`s other things, some of which `include` and `require` still more things. I am honestly not sure what all has to be done-- never been a fan of the "front end posting" idea-- but this is not a small project or a simple one.
I guess that does answer this question though:
> Does anybody know where in the core files this file and/or it's dependencies are defined? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, metabox, core"
} |
feed appearing different in the three main browsers
My blog feed appears diffenently in the three main browsers:
* in IExplorer it is perfect;
* in Chrome it appears as a xml file in source view
* in Firefox it appears like the result list from a search in the blog (first lines of the posts without any html formatting)
Why? | Your feed is just an XML file. If you try to look at a feed in a web browser, each browser shows the feed in a different way. Some will just show the raw XML code, and others will try to display something more human-readable and meaningful to an end user. Sometimes the browser will even offer some choices for subscribing to the feed. But it is up to the browser.
The feed isn't really for web browsers anyway; it is intended to be read by a news reader, which will read the XML file and show you each post in whichever way is appropriate for the news reader you are using. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "feed"
} |
Do we have to register JQuery if we want to use it in wp_enqueue_script()?
Or is it registered by default?
I am enqueuing a script with wp_enqueue_script()
wp_enqueue_script('validation', ' array('jquery'));
But I get this error in the console:
> `Uncaught TypeError: Property '$' of object [object Object] is not a function`
Also do I need to put the absolute path to link my js, or can I use a relative path? Relative to what? | You don't need to register it but in your own js file, replace the first `$` to `jQuery`.
jQuery is loaded in No Conflict Mode
jQuery(document).ready(function($) {
// Your code here. Use $ as normal.
});
And if you use anonymous functions, do it like this
(function($) {
// Your code here. Use $ as normal.
})(jQuery);
Also, you need to use relative paths. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp enqueue script"
} |
WPDB SQL query with prepare() returning variable, not db value
I have been trying to get this to work for awhile now and I cannot seem to get any farther on my own. It seems to work fine as a normal SQL query but not within the WP framework using prepare(). Basically I am trying to insert a PHP variable within the SQL query but instead of returning the value I SELECTed, the function returns the value of the variable.
I have searched for others having the same problem but most of them are dealing with problems with LIKE and the % wildcard. I cannot figure out what my problem is.
I am using a bbPress variable which is the forum id.
Any help would be appreciated.
global $wpdb;
$countquery = $wpdb->get_var($wpdb->prepare(
"SELECT meta_value FROM $wpdb->postmeta
WHERE meta_key = '_bbp_forum_subforum_count'
AND post_id=%d", bbp_forum_id()));
echo $countquery; | The function `bbp_forum_id()` will directly `echo` its value, you want to use `bbp_get_forum_id()` which will `return` the value for use in the context of an API call. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "database, wpdb, sql, variables, bbpress"
} |
Query_posts works when appending via AJAX call wp_query doesn't?
I'm appending some posts on a click event to a twentyeleven child theme. For some reason though it only works when I use the query_posts loop and not a wp_query loop. For instance here's my wp_query loop:
$args = array('year' => $year,'monthnum' => $month);
$loop = new WP_Query($args);
if($loop->have_posts()) {
while($loop->have_posts()) {
the_post();
echo get_template_part( 'content');
}
} wp_reset_query(); //doesn't work
Then here's the query_posts:
query_posts(array(
'year' => $year,
'monthnum' => $month
));
// our loop
if (have_posts()) {
while (have_posts()){
the_post();
get_template_part( 'content');
}
}
wp_reset_query();
I've been told to avoid query posts like the plague so I'd rather use wp_query. Any thoughts on why this is happening? | Calling `the_post()` operates on the global `$wp_query`, for your custom query you need to call the method of the query object: `$loop->the_post()`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query, query posts"
} |
How to use same theme in different languages?
I have a network of wordpress sites
For example
rara.org (English) rara.org/fr (French)
Now I want to use the same theme which is lets say "Mytheme" for both but I also want the in the french site words like "Search" is in french, the dates that are shown are in french and so on.
How can I achieve this? Please help me out. | Just set a different language for each site in `wp-admin/options-general.php`. WordPress will load the matching language file for theme if it exists.
Be aware, you must have these languages installed to get the setting. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite"
} |
Collect user custom field in product page woocommerce
I have a custom user field named "weight" and I need to collect this information in woo product page.
How can I do that? | < you can also get all the detail manually from here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom field, plugins"
} |
Verify Values Using Settings API
I have recently been working on a WordPress plugin using the Settings API. The only problem i found with it is that the user can manually edit the value in the input tag. I was wondering if there was a way to check the before saving it. | That's exactly what the sanitize callback is for in the call to `register_setting()`:
<?php register_setting( $option_group, $option_name, $sanitize_callback ); ?>
That third parameter, `$sanitize_callback`, is a filter callback to which the user settings are passed after submitting the settings form, and before saving to the database.
The settings are passed as an array. The correct way to use the sanitize callback is to **whitelist** the settings: take the user input, sanitize/validate it, and return a sanitized, whitelisted array. That way, if unexpected data are passed, they are simply ignored. And if the user enters invalid or insecure data, those data are validated/sanitized.
To provide more specific direction, we'd need to know more specific information about the settings being saved. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "options"
} |
Should I delete the default themes?
when managing a Wordpress site it gives me great pleasure to see nothing needs updating. Should I delete the default themes or is it best to leave them there?
By default themes I mean: Twenty Eleven Twenty Twelve Twenty Thirteen
Or should I just update them and keep them there for possible troubleshooting in the future? | I keep the default themes in place, and keep them updated.
The WordPress Foundation will keep those themes updated with any security issues, so as long as you keep them updated on your site, I'm not concerned with security problems.
The advantage that you have by keeping them is for testing. When you are troubleshooting an issue, it is very nice to be able to switch temporarily to Twenty Twelve and confirm or eliminate your theme code as the cause of the problem. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 13,
"tags": "customization"
} |
(Plugin) Icon needed beside the post title
I need a plugin to do some posting like this. The icon "Hot!" will appear in front of the post title. Please suggest me any plugin for this. !enter image description here | This can be done easily by using the filter the_title. Below is the custom code which you can use in your theme's functions.php file.
function new_title( $title ) {
$new_title = 'nic ' . $title;
return $new_title;
}
add_filter( 'the_title', 'new_title' );
The above will add " **nic** " prior to post title.
Similarly you can use the icon image in place of the text 'nic' and style accordingly to achieve what you are looking for.
Hope it helps! Thanks | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugins"
} |
wp_enqueue_script : how to change loading order of scripts?
I would like to know how to list all scripts loaded on a page, ranked by order and change this order. | When you take a look at the source of `wp_enqueue_scripts()` (or the register-sister), then you'll see that there's the `global $wp_scripts` handling all the heavy stuff.
Basically the global is just an instance of `WP_Scripts`, which is a child of `WP_Dependency` and you can use all the magic from there if there's no higher level API available.
To see all registered, enqueued, etc. scripts, simply
var_dump( $GLOBALS['wp_scripts']->registered );
or do the same with `enqueue`. Luckily you got one argument to actually sort your stuff: `dependencies`. So if you want to be one script loaded _after_ jQuery has been loaded, simply add a dependency of `array( 'jquery' )` when registering or enqueueing your script. That's the way you order them in WordPress: Make them dependent on each other. Btw, the dependency name _always_ simply is the name it was registered with, called the "handle". | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 7,
"tags": "javascript, wp enqueue script"
} |
Override the wp_siteurl and wp_home not work
I created a wordpress site and name hostname as x.co.uk, x.com, x.in...
In wp-option table the site and home url as x.co.uk. I want dynamically for loading other host name also.
So dynamically set WP_SITEURL, WP_HOME, i override the wp-config as
define('WP_SITEURL', ' . $_SERVER['SERVER_NAME'] );
define('WP_HOME', ' . $_SERVER['SERVER_NAME'] );
but when i call home_url() it always return x.co.uk hostname
Thanks Advance | > So dynamically set WP_SITEURL, WP_HOME, i override the wp-config as
define('WP_SITEURL', ' . $_SERVER['SERVER_NAME'] );
define('WP_HOME', ' . $_SERVER['SERVER_NAME'] );
> but when i call home_url() it always return x.co.uk hostname
`home_url()` does not make use of any WordPress constants. It uses a call to `get_option( 'home' )`. To use WP_HOME instead, short circuit `get_option()`:
add_filter( 'pre_option_home', 'wpse_114486_change_get_option_home' );
/**
* Change get_option( 'home' ) and any functions that rely on it to use
* the value of the WP_HOME constant.
*
* This is not fully tested. Many WordPress functions depend on the value of
* get_option( 'home' ). The ramifications of this filter should be tested
* thoroughly.
*/
function wpse_114486_change_get_option_home( $option ) {
if ( defined ( 'WP_HOME' ) )
return WP_HOME;
return false;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "wp config"
} |
custom post scheduler for drafts
I have a lot of posts everyday to publish. Now, I am thinking to schedule all those posts which I saved them as drafts. So, I tried to make a custom post scheduler. Here is what I tried,
$time = strtotime('+5 min');
$args = array('post_type' => 'post','post_status' => 'draft');
$draft_posts = get_posts( $args );
foreach($draft_posts as $posts) {
$my_post = array(
'ID' => $posts->ID,
'post_date' => date('Y-m-d H:i:s', $time),
'post_status' => 'future');
$my_post->edit_date = true;
wp_update_post( $my_post );
$time += 5400; // every 1.5 hr
}
As soon as I run this, all drafts are published instantly at same time, rather than an interval of 1.5 hr. Can anyone please tell where is the problem? | You're treating `$my_post` as an array, and then an object. Try moving 'edit_date' into the array.
Also keep in mind that 'post_date' should be in your blog's timezone. `date` will give the date-time in UTC timezone. See `date_i18n()` (codex: <
From what I can see, everything else is corret. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, wp update post"
} |
Remove border attribute from Pin It Button image to pass HTML5 validation
I am using the Pinterest "Pin It" Button plugin < which uses this code on my blog pages:
<img border="0" class="pib-count-img" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" />
`border="0"` is causing my blog to fail HTML5 validation. I keep getting the error: 'The border attribute is obsolete. Consider specifying img { border: 0; } in CSS instead.'
How can I remove the `border` attribute from the image used for the Pin It button so that my blog pages pass HTML5 validation? | That code is behind a paywall but assuming that is follows the free version fairly closely, that attribute appears to be hard-coded and I don't see a filter.
That is a lot of code to dig through and it would be easy to miss something, but I don't think you can alter that without hacking the plugin. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, validation, html5"
} |
An image on my site is showing as the wrong image
I have an image on my site, which is showing up as the wrong image. When I "inspect element" in chrome, and click on the link to the image, it shows up as the right image.
How can this be?
Here's the page: <
The image is the blue triangle that appears when you scroll down.
The image: <
Thanks!! | You are only seeing the top of the image, because your background image is much larger than the size you have for #smoothup in the css:
in style.css `#smoothup {height: 40px; width: 90px;}`
The actual image is 122 x 105.
You need either:
1: modify the css defining #smoothup to fit the size of the background image
or
2 modify the background image to fit the size of the container
or
3: use CSS3 `background-size` to scale the background image (not supported in IE8 and below) and would look wrong because you are not matching the aspect ratio.
If you are deliberately scaling the image down for retina display, you put it in the code as an `img` element and scale down with css, but **maintain the aspect ratio** | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, css"
} |
Thickbox in Plugin settings page?
I adding the default wordpress thickbox in the admin page to show some information inside the div. Everything seems ok when i click that link it appear in popup now
<a class="thickbox" href="#TB_inline?height=300&width=400&inlineId=simple_div" title="Select Bar Style" >Popup Load</a>
But actually what i am trying is to show this popup when that plugin settings page load. I tried this way like what i mentioned here is
<script language="javascript">
jQuery(document).ready(function() {
tb_show("testing", "#TB_inline?height=300&width=400&inlineId=simple_div");
});
</script>
But it shows like dim in settings page of my plugin how can i show the div content inside the popup automatically on settings page load.
Any suggestion would be great. | <script language="javascript">
jQuery(window).load(function() {
tb_show("testing", "#TB_inline?height=300&width=400&inlineId=simple_div");
});
</script>
Hi According to the brasofilo suggestion I did this and make it as workable | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, jquery, thickbox"
} |
Does settings API create settings on run time?
I'm tweaking a plugin and I'd like to have an option value different for each backoffice user.
Currently the options are defined using the `add_settings_field` method that is performed in the `admin_init` hookup.
My question is, could I register a new set of settings by prefixing my settings using the current user ID?
Such a way, if valid, could help to solve other problems, such:
* How to Set an Individual Homepage for Each User?
* < | Yes, you can and it's easier using a Class. In the `admin_init` hook (where the Settings API is being registered and defined) set a class property based on the user ID:
$this->prefix = 'uid_' . get_current_user_id() . '_';
Then, in the rest of the code, refer to your option name as `$this->prefix . 'option_name'`.
The result in the table `wp_options` will be `uid_1_option_name`, `uid_2_option_name`, etc. And each user will have its own settings.
A Gist with a working example. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "plugin development, settings api"
} |
What is full URL for a post?
What page is used for a post in Wordpress? For example,
www.mysite.com/some-post-title/index.php
The index.php isn't valid. What is actually after the last slash? | There is nothing after the slash. Do not see the address as something like a directory structure. It is just an address, a unique string to tell WordPress which content it should load.
That content will be loaded into any template, and that template again could be composed of multiple separate files from the theme. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "pages, title"
} |
Wp set post terms not work
My code is not working, it does not add the taxonomy
add_action('init', 'post_test', 10);
function post_test() {
$empty = get_page_by_title('Produto teste', OBJECT, 'produtos');
if(empty($empty)) {
$insert_post = array(
'post_status' => 'publish',
'post_type' => 'produtos',
'post_title' => 'Produto teste',
);
$post_id = wp_insert_post($insert_post);
if ($post_id) {
wp_set_post_terms($post_id, array('metais'), 'categoria-produtos'); // tag metais id is 108
}
add_post_meta($post_id, 'fornecedores', '5948'); // id do fornecedor
add_post_meta($post_id, '_fornecedores', 'field_52377232eb265');
}
}
why not work? | As stated in the `wp_set_post_terms` Comment:
> This function will only work on the native post type. For a taxonomy on a custom post type use wp_set_object_terms()
`wp_set_object_terms` | stackexchange-wordpress | {
"answer_score": 22,
"question_score": 4,
"tags": "terms"
} |
WP Google Fonts question
I'm using Google Webfonts on my Wordpress site (WP Google Fonts plugin) and was wondering whether those fonts are stored on Google server or are uploaded from the server my website is on?
I love some of those fonts, but in my case no love could stand the test of few hundred kilobytes each time someone visits my website.
Thanks in advance for your help. | google web fonts are saved on google's servers not your's, when you apply a font to your site the stylesheet link will be included in your document's head section, the stylesheet and font will be directly downloaded to client's (visitor) browser, there is nothing any bandwidth usage from your server for the google web font.
oh yes just a few bytes, which are a line of code in your document's head section to include a link to css file.
read more here | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins"
} |
Is there a better, more efficient way to get the post id outside the loop?
Right now I am using:
$wp_query->post->ID;
I want to know if there is a better way for getting the post id that consumes less resources? | An alternative to your way would be to access the `$post` global:
global $post
echo $post->ID;
But
1. It won't make a noticeable difference, either way
2. If you want to increase efficiency, you ought to be looking elsewhere...
**EDIT** , pertaining to comments:
> what about `get_the_ID();`?
\--> Needs to be run _inside_ the Loop.
> i have tried both options (get_the_ID and accessing $post global) both give me a wrong id.
If the latter is the case, you, or some plugin you are using, has not properly reset postdata.
> You say to look elsewhere... where should I be looking?
I have no idea what it is you are writing. But if you experience resource bottlenecks or inefficiency, retrieval of the current post ID is likely not the cause. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "posts, id"
} |
Permalink/Pagination issue: Category base name same as page name
I currently have a page called "Blog" (slug "blog"), which loads a index.php. All posts in index.php belong to only one post category. A sidebar on index.php contains category links (via wp_list_categories) which load archive.php for that given taxonomy.
The problem I am running into is that I currently have the category base name set to the same slug as the page: "blog". I am aware that this can cause issues with the rewrite rules, but for the most part everything looks fine. The only issue is with pagination pages for index.php (mysite.com/blog/page/2 does not work while mysite.com/blog/foo-category/page/2 works fine).
Is there a rewrite rule that can help with my current situation? And if so some help would be appreciated.
If this is a bad idea, please speak up as well. I was hoping to achieve a somewhat RESTful url structure, but wordpresses permalink structure doesn't appear to be the most flexible.
Thanks | This is untested, but should work for you. Visit the permalinks settings page to flush rewrite rules after adding:
function wpa_fix_blog_pagination(){
add_rewrite_rule(
'blog/page/([0-9]+)/?$',
'index.php?pagename=blog&paged=$matches[1]',
'top'
);
}
add_action( 'init', 'wpa_fix_blog_pagination' ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "permalinks, rewrite rules"
} |
Media library orphans
I have this conditional statement that checks if an image has been added to a custom post type and if it hasn't it inserts a default image.
if ( get_post_meta( get_the_ID(), 'team_page_custom_image', true ) ) {
echo wp_get_attachment_image($post_meta_data['team_page_custom_image'][0], 'medium');
}
else {
echo '<img src="' . get_bloginfo( 'stylesheet_directory' ) . '/img/team-logo.png" />';
}
It seems works fine except when an image is chosen and then deleted from the media library it leaves a blank spot as there is still a meta value in the database for the post-meta.
I know I can just delete them from the database but is there a function somewhere to take care of orphans from media library deletions? | Maybe it can be solved at run-time. `wp_get_attachment_image` says:
> Returns an HTML image element representing an attachment file, if there is any, otherwise an empty string.
So, if the post meta is set, but an empty string is given, we should delete the post meta.
$default = '<img src="' . get_stylesheet_directory_uri() . '/img/team-logo.png" />';
if ( get_post_meta( get_the_ID(), 'team_page_custom_image', true ) )
{
$get_img = wp_get_attachment_image( $post_meta_data['team_page_custom_image'][0], 'medium' );
if( !emtpy( $get_img ) )
{
echo $get_img;
}
else
{
delete_post_meta( get_the_ID(), 'team_page_custom_image' );
echo $default;
}
}
else
{
echo $default;
}
Or you can create a routine with `get_posts()` (in some hook or Settings API) to iterate through all posts and check/delete orphans. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post meta, media library"
} |
How to debug a blank page?
I'm not being able to load this page, although I can easily load all other posts that load the same custom post type template (please look for "// From now on, WP is throwing a blank page" on that template to pin point where exactly this situation occurs). When turning debugging on, I only get:
`Notice: wpdb::escape is deprecated since version 3.6! Use wpdb::prepare() or esc_sql() instead. in /nfs/c01/h04/mnt/38315/domains/joao.pt/html/wp-includes/functions.php on line 2905`
What else can I do to understand what's going on here? It doesn't even timeout, it just serves a blank page—tested in all major browsers. Because of the fact that pretty much all other posts with the same template load correctly, I really have no idea how to debug this weird blank page. | > Notice: wpdb::escape is deprecated since version 3.6! Use wpdb::prepare() or esc_sql() instead. in /nfs/c01/h04/mnt/38315/domains/joao.pt/html/wp-includes/functions.php on line 2905
WordPress often is not really accurate with giving your information. You can change that: Set `error_reporting( -1 );` and `define( 'WP_DEBUG', true );`. More info in that Gist. This will avoid the _white screen of death_.
If you got XDebug installed, every error normally comes with a backtrace of what happened. If you even got an IDE like PHPStorm, you'll be able to remote debug your pages and see your errors very accurate and fast.
If you ain't got any of that, your best bet is deactivating all plugins, switching back to the default theme and then activate one after the other step by step to see when the error occurs. If you found the plugin or theme responsible, do a cross file search for `escape`. Then change it according to the error message. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom post types, query, debug"
} |
Taxonomy Parameters in WP Query to get posts from two different taxonomies
For example I have custom post type Cars and two custom taxonomies Brand (with terms BMW, Honda, etc.) and Color (Red, Green, etc.).
Car must has Brand but may not have Color.
So it may be like: Car -> Brand : BMW -> Color : Red,
and aslo it may be like this:
Car -> Brand : BMW(without color).
I need to get Cars from 1 brand which has colors: Car -> Brand : BMW -> Colors (any color). I have tryed to create query but it does not work.
$args = array(
'post_type' => 'cars',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'brand',
'field' => 'slug',
'terms' => 'bmw'
),
array(
'taxonomy' => 'color'
)
)
);
$query = get_posts( $args );
var_dump($query);
die(); | _terms_ parameter of tax query is required. Just pass to it all the terms for taxonomy
$args = array(
'post_type' => 'cars',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'brand',
'field' => 'slug',
'terms' => 'bmw'
),
array(
'taxonomy' => 'color',
'field' => 'id',
'terms' => get_terms('color', array('fields'=>'ids') )
)
)
);
Note this query will also returns 'cars' that have no brand attached, but have a color. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, wp query"
} |
API for Post Stats for Self-Hosted Wordpress using JetPack
**EDITED** for Clarification
WordPress.com as well as JetPack provides stats (like no of views, referrer, etc) for various posts and blog as described here :Wordpress Stats
Is there an API so that I can access the stats data and use it as per my needs ? | There is indeed a Stats API that will allow you to access stats from a WordPress.com or a Jetpack site.
You can read more about it here:
* <
* <
* <
Jetpack uses this API to populate the Top Posts widget:
* < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "api, plugin jetpack, wordpress.com hosting"
} |
How to store media files in subdomain
In order to parallelize downloads, i created already a subdomain for images. images.mydomain.com
Now, i don't know how to move my media files, without breaking attachments, and after that, in the future, how to automatically store media file in subdomain.
Eventually, what i was thinking of doing was something like , redirect images.mydomain.com to mydomain.com/wp/content/uploads and after that replace all strings '< using the wordpress plugin "search and replace".
Does someone believes to know how to get around this?
thanks in advance | You can move the uploads folder to the sub domain by doing this
Open up your wp-config.php file, located at the root of your WordPress installation, and add the following code:
define('UPLOADS', '
The codex specifies that it should be added before the line that says require_once(ABSPATH.’wp-settings.php’);.
Make sure the uploads folder is writable. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "images, redirect, media, subdomains"
} |
Show Post from parent category (custom taxonomy) ONLY!
I want to display all post under a parent category (custom taxonomy) ONLY!.
Here's what I've done so far:'
<?php
$args = array(
'posts_per_page' => 100,
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'ait-dir-item-category',
'field' => 'id',
'terms' => 75
)
),
'post_type' => 'ait-dir-item' );
$the_posts = new WP_Query($args);
This displays all the posts including the sub categories, which I don't want to.
Thanks!! | Any `tax_query` can take an `include_children` argument (see Codex) that defaults to `true`. So just add that to your code and it should work:
<?php
$args = array(
'posts_per_page' => 100,
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'ait-dir-item-category',
'field' => 'id',
'terms' => 75,
'include_children' => false
)
),
'post_type' => 'ait-dir-item' );
$the_posts = new WP_Query($args);
_Note: I'm unsure of the behavior of`include_children` when a post is assigned to both a child and parent, but I would guess that the post would show up._
* * *
EDIT: Posted the wrong link earlier. from The Codex:
> **include_children** _(boolean)_ \- Whether or not to include children for hierarchical taxonomies. Defaults to true. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "categories, custom taxonomy"
} |
WordPress and Localization
I know that WordPress supports multiple languages - You can read more details here <
My question is, what is the difference in a localized version over the standard english versoin? Does it only contain extra language files? What should I look for?
Thanks. | The localized version is the English version translated. It contains the original and translated strings. You should look for missing translations or badly translated strings.
Use a desktop tool like PoEdit or a plugin like Codestyling Localization to manage your WordPress, Themes and Plugins translations (the localized `.po` and `.mo` files). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "multi language, localization"
} |
how to request a script more than once in wordpress
Can I ask how I can request a script more than once in wordpress. For example:
for($i = 0; $i < 2 ; $i++){
wp_enqueue_script('alerthello.js', 'example.com/example.js');
}
I expect the code to display two hello, but it display one only instead. | When you're using `wp_register/enqueue_script()`, you're basically pushing an element to an array named `global $wp_scripts`. Therefore you can't echo something twice as WordPress successfully prevents scripts being registered or added multiple times.
The reason is easy: Else, every plugin that registers or enqueues jQuery (or uses it as dependency) would add another instance. Which would be an undesirable result.
If you need to echo something twice, simply handle that inside your script file. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, javascript"
} |
What is a "protected" post status?
I noticed in the `register_post_status` function in core that there is an arg for 'protected'.
The following post statuses: 'future', 'draft', and 'pending' all have this set to **true**.
I'm not talking about a protected 'post' but the 'protected' argument used when registering a custom `post_status`.
What does this 'protected' status do? And why would I make a custom post status protected? | `register_post_status` is used for creating a custom post status. The protected argument, if true, specifies that a user must be logged in and have edit permissions on the post to view (preview) it.
For example, you said that the "draft" post status has `protected` set to true. This means that you can only view (preview) the draft post if you have permission to edit the post. Once the post is published, the `protected` parameter is turned off and anyone can view it.
If you are creating your own custom status, you might want it to be protected. For example, you could have a post status called "on_hold", and when you set a post to that status, it would no longer be visible to the public, but still visible to the administrators of your site. | stackexchange-wordpress | {
"answer_score": 14,
"question_score": 7,
"tags": "post status, core"
} |
Switching to child theme breaks menu names
When I switch to the child theme I am working on, the main menu uses the page names instead of the names that I gave it in the Appearance > Menu options. Happened to anyone else? | The custom menus assigned to Menu Locations (in the Appearance, Menus, Manage Locations tab) are saved per theme. So when you switched to your new theme, you lost that assignment. Go to the Manage Locations tab and select your custom menus again. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, child theme"
} |
Multisite get_home_url(); - Getting URL for current site
What would be the replacement for get_home_url() when using a multisite? For example, if I have one theme installed across several sites, and within the theme there are links that need to be specific to the current site.
On my single install, using get_home_url(); would give me < which was great, and if I moved the theme to a different domain, nothing would be affected. But when I'm using the same theme on a multisite, get_home_url(); gives me < no matter which site I am currently on. What I would need for each one is domain.com/sitename/. Is there a different tag to use in this case?
Thanks!
EDIT
Can't answer my own question yet, but `<?php echo get_bloginfo( 'url' )?>` was exactly was I was looking for. | `<?php echo get_bloginfo( 'url' )?>` was exactly was I was looking for. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "php, multisite, template tags"
} |
Cannot Get User id after login success in file wp_login.php
I have a problem when I want to get user id WordPress after login in file `wp_login.php`, I tried to insert some code in this file, after line `wp_safe_redirect($redirect_to);` in login case.
I must get user id after login to update my custom WordPress table.
session_start();
require( dirname(__FILE__) . '/wp-load.php' );
global $wpdb;
$session_id = session_id();
$current_user = wp_get_current_user();
$id_user = $current_user->ID;
$wpdb->query(
$wpdb->prepare("UPDATE wp_shortlist SET id_user='$id_user' WHERE id_session='$session_id' ")
);
any idea to get user id after login in file `wp_login.php`? | As said above modifying the core files is a bad idea, by doing so you are opening up security holes and on top of all this you loose the changes made on up-gradation.
To do the above you can try the wp_login hook, put the codes in your active theme's functions.php
function after_login() {
$current_user = wp_get_current_user();
$id_user = $current_user->ID;
// The query you were trying would go here.
}
add_action( 'wp_login', 'after_login' );
Hope it helps ! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "login, wp login form"
} |
Plugin Not Working After Being Uploaded To Wordpress Plugin Repository
Why my wordpress plugin is not working after I uploaded it to wordpress plugin repository. Is there any requirement of what tool I should use to write it or may be something else?
Here is my plugin repository < | You **have** to develop with WP_DEBUG enabled. And use Firebug or Chrome Console to check for Network/JavaScript errors.
) : ?>
<p><?php echo $field; ?></p>
<?php endif; ?>
But how can I check if the current viewer has the permission to view the field (from the visibility setting who the user can set)? | I found the answer to this question with support from the members from the BuddyPress forum. The function that I needed was xprofile_get_field_data().
Here my code:
<?php $hidden_fields = bp_xprofile_get_hidden_fields_for_user(); ?>
<?php if(xprofile_get_field_data('field_name') && !in_array(xprofile_get_field_id_from_name('field_name'), $hidden_fields)) : ?>
<p><?php echo xprofile_get_field_data ('field_name'); ?></p>
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "buddypress"
} |
Limit Contact Form 7 hook to specific form
I'm using a Contact Form 7 filter to take action after the email is sent. How can I limit this action to only one form? There are multiple forms on different pages, and I don't want this action to run after every form, only one specific form.
I tried limiting the action to the page where the form is using an if clause, but then the "action" doesn't complete. Once I remove the if clause, then the action works.
function foo() {
if(is_page('bar') {
// some action
}
}
add_action( 'wpcf7_mail_sent', 'foo', 1 ); | You know the id of the form from the shortcode, you can do stuff just for that particular form. Here's some sample code for that, just replace `$myform_id` with your form id:
add_action( 'wpcf7_mail_sent', 'wp190913_wpcf7' );
/**
* Do stuff for my contact form form. This function shouldn't return aything
*
* @param WPCF7_ContactForm $contact_form wpcf7 object, passed by refference
*/
function wp190913_wpcf7( $contact_form ) {
// Not my desired form? bail
if ( $contact_form->id !== $myform_id )
return;
// Do stuff for my contact form
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "conditional tags, plugin contact form 7"
} |
Why do folders have Empty Index.php Pages?
1. /wp-content/
2. /plugins/
3. /themes/
All have empty index.php files in it. Are they safe to delete? What is their purpose, why even be in the default install if they're empty? What is their purpose? | As a security measure, WordPress includes these index.php files to account for hosts that by default enable directory browsing.
Including them makes sure that no one can see the list of files in that directory, which could let them know what plugins or versions you are running and thus give them some things to try to hack your site.
As long as you don't have directory listings enabled, they are safe to delete (although there's probably no reason to delete them). | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "customization"
} |
Custom Post Type Works but Still Shows "Page Not Found"
I have a weird problem when creating custom post types. Everything works, the archive page shows the posts and the posts show their content, but for both the title of the site says, "Page not found."
You can see an example at `
I've flushed the permalinks, which is why the pages load their content, but there is still some disconnect. Any thoughts? | Hopefully this will provide some answers to anyone who runs into a similar problem.
I had copied/created a (poor) function in my functions.php file that was looking for specific templates and if they were not found it would set `$wp_query->is_404 = TRUE` and that was the cause of the problem.
Of course, the higher-level answer is let WordPress work for you. If you structure your template files correctly, you don't need to look for them yourself. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "custom post types, 404 error, custom post type archives"
} |
To merge customized codes upon wordpress update
When using `update` feature (in `wp-admin/update-core.php` page), it seems to me that wp just replaces all the resources, and the changes that have been made in the working resources just get erased instead of getting merged.
At least I've been experiencing with `wp-login.php` that gets replaced per every update and thus I have to reflect back the change from scratch (it's not easy often because the code in the file changes upon update).
Am I right? If so, are there ways to merge the changes already made with the update? | Yes, WordPress replaces all the resources.
No, there is no way to get the updater to merge changes. Even in theory, I doubt you could do that. Even the big version control systems-- SVN, GIT-- ultimately depend on user judgment. That suggests the only reasonable answer I can think of.
**You should not be hacking core files at all** , but if you must you will need to use a version control system on your end to try to manage your changes and merge them with each release. Of course, the automated updater will not be involved. You will need to update manually over FTP or run GIT (or other) on the production server. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, updates, automatic updates, merging"
} |
Does WordPress require that your submitted theme supports multiple menu levels?
As the title says I'm wondering if WordPress requires that your submitted theme supports multiple menu levels. I can't seem to find any info on this.
However the Theme Unit Test does include hierarchical pages. There's no information in the Theme Unit Test if this is required or not. | This is not required, but if your theme doesn't support multiple menu levels then you should note this in your theme documentation (readme file) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development"
} |
Programmatically disable W3 Total Cache in development environment
I've got two environments in my project: dev & production. I just want to be able to deactivate or disable W3TC in my dev environment but the plugin has no native support for this . I also can't find a deactivate hook that works with the plugin and setting `define('WP_CACHE', false);` based on `HTTP_HOST` seems to be bypassed in `wp-config.php`.
So surely this has come up before for people - what is the solution? | Caching plugins are very challenging to disable because on top of normal plugin functionality they tend to:
* created extra drop-in files
* set caching constants
* bypass PHP completely with `.htaccess`
While it's not impossible to mangle specific plugin into submission, it's flaky. More reliable to explicitly disable it in dev and keep. Note that implicitly stopping plugin from loading might not even be enough thanks to leftover extras that are cleaned up only via proper deactivation routine. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugin w3 total cache, deactivated plugin"
} |
How to make changes to style.php
I am working from a Wordpress theme called Dynamix.
The site is located here...
If you scroll down to the post with a comment, you'll see a comment bubble, with a solid black background. If you hover over it, you'll notice it turns red.
**In Chrome's debugger, I found this line of code...** (It's long, but it starts with this)
`#content ul li.socialinit, #content` **and it ends with this background tag...**
`background-color: #252525;` (in the debugger).
In style.php, which is **here** , I found the code, but I have no idea how to change it.
Looks like this: `background-color:#<?php echo $linkcol; ?>;`
I don't want the black background. I want it to say `background: none;`, which should fix my issues.
**I'm lost on what to do here...** | To remove the style without modifying the original code you can try add this to your style.css
.comment.yes {
background: none !important;
}
This will add a new style for that class. The `!important` part tells the browser not to let another style over-ride that line. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, css"
} |
Loading scripts to the Post Edit page only
I have added a few meta boxes for the posts and pages, so I want to load a js script only on the Create/Edit post and page. How can I do that? Currently I'm using following but that loads the scripts in all pages in the admin.
function my_meta_boxes() {
add_meta_box("post_meta", "Meta", "post_meta", "post", "normal", "high");
add_meta_box("post_meta", "Meta", "post_meta", "page", "normal", "high");
}
add_action( 'add_meta_boxes', 'my_meta_boxes' );
function register_custom_scripts() {
wp_enqueue_script( 'custom_js', get_template_directory_uri() . '/inc/meta/custom.js', array( 'jquery' ));
wp_enqueue_style( 'custom_css', get_template_directory_uri() . '/inc/meta/custom.css');
}
add_action( 'admin_init', 'register_custom_scripts' ); | We can improve a little bit with :
function specific_enqueue($hook_suffix) {
if( 'post.php' == $hook_suffix || 'post-new.php' == $hook_suffix ) {
wp_enqueue_script( 'custom_js', get_template_directory_uri() . '/inc/meta/custom.js', array( 'jquery' ));
wp_enqueue_style( 'custom_css', get_template_directory_uri() . '/inc/meta/custom.css')
}
}
add_action( 'admin_enqueue_scripts', 'specific_enqueue' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "custom field, theme development, metabox, wp enqueue script"
} |
WordPress Image Scaling Quality
How can I make sure that WordPress doesn't lose too much quality on uploaded images that are scaled down?
Here are some samples. You can clearly see that an image resized in Photoshop comes out with better quality than the same image resized within WordPress.
* **Original screenshot** at 700px width !Original screenshot at 700px width
* **Photoshop resized** at 600px !Photoshop resized at 600px
* **WordPress resized** at 600px !WordPress resized at 600px | WordPress does do some compression on images when it resizes them. You can disable this very simply using the following code (or using a plugin like this one):
function wpse_114909_image_quality() {
return 100;
}
add_filter( 'jpeg_quality', 'wpse_114909_image_quality' );
I'm sure that GD & Imagemagick are not as good at resampling images as Photoshop is, so this may be a battle you'll never win. All the same, this will certainly help. For any images where the quality matters _that much_ to you, you should manage the images manually instead of letting WordPress resize them. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "images"
} |
rewrite script to use wp_remote_get instead of file_get_contents_curl
I have a script that pulls the facebook likes via facebook graph and writes them in my DB. However it uses file_get_contents_curl for the request and this is causing problems, so I'd like to use the wp_remote_get() command. I've tried to change it but somehow I can't do it (I don't really have PHP knowledge).
Here's the part of the script:
foreach($posts as $post)
{
$fb = json_decode(file_get_contents_curl('
if( !isset( $fb->likes) && isset($fb->shares) )
{
$fb->likes = $fb->shares;
}
//$fb->likes = isset($fb->likes) ? $fb->likes : 0;
$myfblikes = sprintf("%04s", (int)$fb->likes);
update_post_meta($post->ID, 'fb_likes', $myfblikes);
} | You can try this:
foreach( $posts as $post )
{
$url = sprintf( ' get_permalink( $post->ID ) );
$response = wp_remote_get( $url, array( 'timeout' => 15 ) );
if( ! is_wp_error( $response )
&& isset( $response['response']['code'] )
&& 200 === $response['response']['code'] )
{
$body = wp_remote_retrieve_body( $response );
$fb = json_decode( $body );
if( ! isset( $fb->likes ) && isset( $fb->shares ) )
{
$fb->likes = $fb->shares;
}
if( isset( $fb->likes ) )
{
$myfblikes = sprintf( '%04s', (int) $fb->likes );
update_post_meta( $post->ID, 'fb_likes', $myfblikes );
}
}
}
where we can use `wp_remote_retrieve_body()` to get the response body of `wp_remote_get()`. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "wp remote get"
} |
how to register a second page-template
i'm using blogolife < and like to add another page-tamplate which is identical to the standart page-template but has a different sidebar. also i'd like to add a business- and a contact-template. the theme-folder structure how ever is kind of confusing to me, if someone would be so nice to load the theme and check the structure, and maybe even explain to me, i would be very pleased.
also i can only select one template, even if it seems there are several sub-templates in this theme. what am i doing wrong? | After a quick look at the structure, I got to say it appears pretty standard.
Simply follow the codex article on _creating a page template_ and drop the new file in the theme's root directory. Done.
Any custom template for multiple pages should start like this:
<?php
/*
Template Name: WPSE Template Example
*/ | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, themes, templates, user registration"
} |
enqueue_style is not working
I try to load the main stylesheet with enqueue_style - but it isn't working. Here is my code from functions.php:
function my_scripts() {
wp_enqueue_style( 'main-style', get_template_directory_uri() . '/style.css', false, '1.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
Loading the stylesheet in the header.php by using a link-tag works fine. I can't find the error - it seems that code is ignored - but function.php is loading.
I also tried to use `get_template_directory_uri()` instead of `get_template_directory_uri()`.
Because it is the recommended way to link to styles and scripts I want to get this work. I also want to use enqueue_scripts for some js and jQuery scripts.
Thanks for any hint or advice
The solution: I forgot to call wp_head() in the header.php - added and everything works :-) | The solution: I forgot to call wp_head() in the header.php - added and everything works :-) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "theme development, css, wp enqueue style"
} |
How to create single page site in WordPress
I have total 5 pages on my website, I want to display all pages as single page.
It is possible?
Example: < | Create a child theme for your current theme. Read how to here.
After that create a file in your child theme named `front-page.php`. This is the first file WordPress will look for when you visit the home page of your site.
To understand why, read here.
In that file use:
<?php
get_header();
$all_pages = get_pages();
global $post;
echo '<div class="pages-container">';
foreach ( $all_pages as $post ) {
setup_postdata($post);
// improve the content, this is an example
echo '<h2>' . the_title() . '</h2>';
echo '<div class="page">' . the_content() . '</div>';
}
echo '</div>';
wp_reset_postdata();
get_footer();
The docs for function I've used are here:
* get_pages
* setup_postdata
* wp_reset_postdata
* also get_header and get_footer | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, pages, frontpage"
} |
Can't create new Pods pages
this is strange.
Suddenly I can't create any more Pods pages! In the edit page screen instead of publish the main button shows submit for review and when I push it WP says: You are not allowed to edit this post.
Well, I'm the admin so I shouldn't have any problems, and indeed I created other pages before. The roles and capabilities seems ok to me...
What's going on?
EDIT: Looks like is a problem in a last upgrade in my functions.php code. But I can't get what! | I found the problem.
There was a line of code that was deleting all posts as soon they were created.
It may seems slly but it was wanted, I'm building a really custom app based on wordpress...
Simply I forgot that this would cancel many other things that pods saves as post, like pods pages or pods fields.
It's strange hwr that in the page editing screen, the main button was showing "submit for review" instead of "publish", lije wordpress knew about that error in the code. Maybe it decide what to show seeing if it was able to save a draft of the page. Since the drafts were getting deleted all the same, probably it thought I was allowed to publish.
Pretty intricate system! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "capabilities, pods framework"
} |
Use the_post_thumbnail as background image in LESS CSS
I'm trying to use `the_post_thumbnail` featured image as the background image to a div container within a page template file.
I'm using LESS CSS and wondered if it was possible to pass in a Wordpress tag to the LESS file or use PHP in anyway?
If not, I guess my only option would be inline style? | There's nothing wrong with an inline style in this case - just set all your other rules in your LESS (like background position, repeat, size), and then in your template:
<div class="something"<?php
if ( $id = get_post_thumbnail_id() ) {
if ( $src = wp_get_attachment_url( $id ) )
printf( ' style="background-image: url(%s);"', $src );
}
?>> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post thumbnails"
} |
Get all posts without tags
I'm working with a tag plugin. Is there a WordPress way to get_posts or query all posts that have no tags?
**EDIT**
I had already queried the WP Codex, search Stackexchange and Google for a related question at the time of the question.
I found several results for helping finding tags, but not the `NOT IN` operator in a `tax_query`. I didn't have any code to share yet as I didn't have the information I needed to build the query `$args`. | A `WP_Query` where `'tax_query'` has all tag terms and operator 'NOT IN':
$tags = get_terms('post_tag', array('fields'=>'ids') );
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'id',
'terms' => $tags,
'operator' => 'NOT IN'
)
)
);
$untagged = new WP_Query( $args ); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 0,
"tags": "wp query, tags, get posts"
} |
Compile errors during translation compile
I am trying to translate a theme using Poedit, every thing is alright except two strings which give me errors like this:
Error: 'msgstr' is not a valid PHP format string, unlike 'msgid'. Reason: The character that terminates the directive number 1 is not a valid conversation specifier.
The string itself is this:
% comments
Both errors are in strings having `% comment` (not sth like `% s`). Now I have two problems: 1\. How can I resolve these errors? Do I need to change theme code? 2\. After getting these compile errors, I used .mo and .po files anyway but some phrases had been translated and some not! What is the reason to this?
EDIT: The PHP code translation associated to is:
comments_number( __('There are no comments so far', 'hbthemes'), __('There is <strong>1 comment</strong> so far', 'hbthemes'), __('There are <strong>% comments</strong> so far', 'hbthemes') ); | The problem was with `POEdit` program. I used another app and it's gone. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "translation"
} |
Listing pages which uses specific template
I have created a template named `product.php` with the following header:
<?php
/*
Template Name: Product Page
*/
How can I list, in a sidebar, every page that uses the "Product Page" template?
I have tried reading the `wp_list_pages()` function documentation, but it only seemed possible to list filtering by `post_type`, not by template used. | You can do this with a `WP_Query` `meta_query`. The page template filename is stored in post meta under the key `_wp_page_template`:
$args = array(
'post_type' => 'page',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_wp_page_template',
'value' => 'product.php'
)
)
);
$the_pages = new WP_Query( $args );
if( $the_pages->have_posts() ){
while( $the_pages->have_posts() ){
$the_pages->the_post();
the_title();
}
}
wp_reset_postdata(); | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 9,
"tags": "pages, templates, list"
} |
twentythirteen h1 and h2 not resizing responsively
I'm using the twentythirteen theme which is supposed to be responsive, here on my site.
On this static homepage, the text-headers are generated as follows, using the heading tags:
<h2>Hello!</h2>
If you narrow the width of the page, you will see the page title "Home" shrink in size, but the text-headers don't. How can I fix this? | You would need to access your style sheet (style.css). Your site uses media queries to target specific screen sizes and apply different rules when the stylesheet interacts with them.
In section 4.1, it defines the site title as:
.site-title {
font-size: 60px;
}
In Section 8.0, just beneath `@media (max-width: 643px)` it defines the site title as:
.site-title {
font-size: 30px;
}
In other words, when the screen size is less than or equal to 643px wide, the site title adjusts to 30px.
In your case, you'd want your Section 8 include a rule for h2 (exchanging the # for the desired number of pixels:
.site-title {
font-size: 30px;
}
h2 {
font-size: #px;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "responsive"
} |
Is it possible to handle two or more shortcodes in a single page?
I have a shortcode **[API-Module version="1"]** and another shortcode like **[API-Module version="2"]**
If i handle any one at a time in a single page it works perfectly. Yet my requirement needs both had to be visible in front end(UI) when handling two shortcodes. Is there any possibilities to do so ?
Constructor to add short-code:
function __construct() {
add_shortcode('API-Module', array(&$this, 'handle_shortcode'));
}
This part is used in handling short-code:
function handle_shortcode($atts) {
$version_type = $atts['version'];
ob_start();
require_once "/front_end/view/api-list.php";
$output_string=ob_get_contents();
ob_end_clean();
return $output_string;
} | From the PHP Manual on `require_once`:
> The **require_once** statement is identical to require except PHP will check if the file has already been included, and _if so, not include (require) it again_.
The second time your shortcode handler is run, the view/template will not be executed.
Hence no output.
Change
`require_once "/front_end/view/api-list.php";`
to
`require "/front_end/view/api-list.php";`
and you ought to be fine. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode"
} |
Filtering WP_Query
I'm developing a site that uses a Artist custom post type and I need to query all posts of this type in a page template. I need to set the **is_post_type_archive** property to true too to filter this query using the **posts_orderby** filter. I'm using the following code, but it seems WordPress is ignoring the third line:
$args = array('post_type' => 'artist');
$wp_query = new WP_Query( array_merge( $args, array('nopaging' => true) ) );
$wp_query->is_post_type_archive = true;
This is the filter:
function artist_posts_orderby( $orderby )
{
if (is_post_type_archive('artist')) {
$orderby = "RIGHT(post_title, LOCATE(' ', REVERSE(post_title)) - 1) ASC";
}
return $orderby;
}
add_filter('posts_orderby', 'artist_posts_orderby' );
Any ideas?
Thanks in advance | I rewrote the code and now it works
The loop:
$args = array('post_type' => 'artist');
$wp_query = new WP_Query( array_merge( $args, array('nopaging' => true) ) );
The filter:
function theme_posts_orderby( $orderby, $query )
{
if ($query->query_vars['post_type'] == 'artist') {
// order artists by last name
$orderby = "RIGHT(post_title, LOCATE(' ', REVERSE(post_title)) - 1) ASC";
}
return $orderby;
}
add_filter('posts_orderby', 'theme_posts_orderby', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, wp query, filters, archives"
} |
Overwrite CSS with without deleting it
I have some css in the theme that I am using, I want to keep the stock style.css without deleting any of it. I want to use my child-theme style.css to remove or hide some values of a class. I would like to do this so I do not have to update my css with each new theme update.
This is what is in the stock theme
.et_pt_portfolio_entry {
border: 1px solid #dadada;
border-bottom: 1px solid #b7b7b7;
background: #fff;
padding: 5px;
-moz-box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.1);
-webkit-box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.1);
box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.1);
margin-bottom: 7px;
}
This is what I want to use in its place
.et_pt_portfolio_entry {
margin-bottom: 7px;
padding: 5px;
}
Normally I use display:none but I want to keep that class displaying, I just want to remove the other values without deleting the stock file.
Thoughts? | Assuming you have your child theme set up correctly, placing the following CSS in it which simply resets some of the preset values should get you all the way there.
.et_pt_portfolio_entry {
border: none;
border-bottom: none;
background: transparent;
-moz-box-shadow: none;
-webkit-box-shadow: none;
box-shadow: none;
padding: 5px;
margin-bottom: 7px;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "child theme, css"
} |
How do I print a notice only on certain admin pages?
I'm writing a plugin which would print a notice, but only on the media page. I found the `admin_notices` and `all_admin_notices` actions, but these are fired on all admin pages. Is there any way to find which admin page is the hook being called on from within the callback? | There is a global variable called $pagenow for the use within WP Admin:
global $pagenow;
if ( $pagenow == 'upload.php' ) :
function custom_admin_notice() {
echo '<div class="updated"><p>Updated!</p></div>';
}
add_action( 'admin_notices', 'custom_admin_notice' );
endif;
UPDATE: Simply include the snippet in your themes or plugins `functions.php` | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "plugin development, actions"
} |
Is it possible to match site root with a WP rewrite rule?
I need to add a custom query var to the site root.
For example say I have a query var, lets say 'colour'. I have a CPT called banana and I use the filter 'banana_rewrite_rules' to add '?colour=yellow'.
That works fine. If I visit `www.example.com/bananas/` or `www.example.com/banana/cavindish/` or `/banana/wild/` I get the colour=yellow as a query var.
Now, I also have vars being returned for posts and pages. That works fine as well.
Thing is, I need to return a colour on the site root as well. If someone visits www.example.com I need, for example, ?colour=white returned and accessible as a query var.
So going on what I've done before, if I could match the site root itself to add the query var my filter remains unchanged. (root_rewrite_rules filter doesn't work as it matches things like robots.txt, not the actual root).
Something like '^$' which works in Django? Or '/?$' | Turns out I was being dumb. The rule is '$' | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "url rewriting"
} |
Stop parsing shortcodes
I'd like to stop parsing shortcodes in `the_content` but I'm struggling to find what the correct filter would be. This didn't work:
remove_filter( 'the_content', 'do_shortcode', 40 );
remove_filter( 'the_content', 'run_shortcode', 40 );
remove_filter( 'the_content', 'wpautop', 40 );
remove_filter( 'the_content', 'autoembed', 40 );
remove_filter( 'the_content', 'prepend_attachment', 40 );
This worked (but also disabled all other useful filters):
remove_all_filters( 'the_content', 40 );
So, I'd like to disable `autoembed` and `do_shortcode` and let WordPress display them as plain text. Would it be possible? I'm using `wp` hook in main plugin's PHP file. | The correct way is calling `remove_filter` with the _same priority_ as the hook was added:
remove_filter( 'the_content', 'do_shortcode', 11 );
Some plugins change this filter’s priority, so you could clear the global list of registered shortcodes temporary:
add_filter( 'the_content', 'toggle_shortcodes', -1 );
add_filter( 'the_content', 'toggle_shortcodes', PHP_INT_MAX );
function toggle_shortcodes( $content )
{
static $original_shortcodes = array();
if ( empty ( $original_shortcodes ) )
{
$original_shortcodes = $GLOBALS['shortcode_tags'];
$GLOBALS['shortcode_tags'] = array();
}
else
{
$GLOBALS['shortcode_tags'] = $original_shortcodes;
}
return $content;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "shortcode"
} |
Why are some of my custom posts not showing up on my page?
I have 6 posts with a custom post type in my Wordpress theme. I want to show them all on a page but I can only get a maximum of 3 to show up, regardless of how many there are.
I have this code in the page:
<?php $count_posts = wp_count_posts( 'cases' )->publish;
echo $count_posts; ?>
<?php query_posts('post_type=cases'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="post" style="display:inline;">case</div>
<?php endwhile; else: ?>
<p>Sorry, no posts matched your criteria.</p>
<?php endif; ?>
...and it outputs this:
6
case case case
Why are my other 3 custom posts not showing up?
Thanks in advance | If you don't set a value for `posts_per_page`, it will use whatever the setting is for `Blog pages show at most` under `Settings > Reading`.
Also, don't use `query_posts`, use WP_Query instead:
$args = array(
'post_type' => 'cases',
'posts_per_page' => -1 // get all cases
);
$cases = new WP_Query( $args );
if ( $cases->have_posts() ) :
while ( $cases->have_posts() ) :
$cases->the_post();
// output case
endwhile;
else:
// nothing found
endif; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, pages, query posts"
} |
Is there an easy way to download all plugins from the repo?
I want to do some Scans and Stats and would like to download every plugin in the WP Plugin Directory.
Is there an easier way to do this, other then clicking the download button 27k times?
What would be my best option for doing this? | Use subversion to access the plugin .svn library, then get the complete repository.
See: < for more information | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins"
} |
After updating site to use SSL all images in posts point to http://
I recently upgrade my site to use SSL through a reverse proxy. I have changed the WordPress address and site address in the Settings menu and the main page loads just fine: <
If you click through to one of my posts however you get mixed content warnings on the SSL certificate: <
I see the images on the page are still pointing to the http:// URL they were added with but I would have thought that my redirect would force them to be served over this doesn't seem to be the case. Either way I'm happy to rewrite them to protocol relative URLs, I'm just not sure on the best way. How is it best to go about changing the URLs for the images in posts? | Installing the WordPress HTTPS plugin should take care of it. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "ssl, https"
} |
How do I insert a new meta key / value pair, but only if another meta key is present?
I need to add a new meta key and value part only on posts where another key is present (regardless of its value).
I tried to use a query to automate it, but my SQL is quite limited
Here's what I tried:
INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT
(SELECT meta.post_id
FROM `wp_postmeta` meta
INNER JOIN wp_posts posts ON meta.post_id = posts.id
WHERE meta.meta_key = 'existingkey'),
('newkey'),
('newvalue')
It returns the `#1242 - Subquery returns more than 1 row` error. | There's no need to do this via raw SQL.
Make use of the WordPress core functions `get_post_meta` and `update_post_meta`.
Use them like so:
$existing = get_post_meta( $post_id, 'existingkey', true );
if ( ! empty( $existing ) ) {
update_post_meta( $post_id, 'newkey', 'newvalue' );
}
Done. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "post meta, sql"
} |
Debug mode shows Strict Standards
When I set `WP_DEBUG` to `true` in `wp-config.php`, I get to see all the strict standards and deprecated messages.
I've set the `error_reporting` in my `php.ini`, `ini_set()` and `error_reporting()` to `E_ERROR | E_WARNING | E_PARSE`. But I still get to see the strict standards messages.
I know the messages can be useful, but they appear in some of the plugins I am using and I am not interested in seeing them. How do I disable them? | Just don’t set `WP_DEBUG` to `TRUE`. The error level is set in `wp_debug_mode()`, which is called in `wp-settings.php` before any plugins are loaded. If you leave the default values WordPress will set it to:
error_reporting(
E_CORE_ERROR |
E_CORE_WARNING |
E_COMPILE_ERROR |
E_ERROR |
E_WARNING |
E_PARSE |
E_USER_ERROR |
E_USER_WARNING |
E_RECOVERABLE_ERROR
);
But you _should_ keep strict standard messages on, because in some cases they advance to real errors in later PHP versions, so it is better to fix them early. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "errors"
} |
Only show content if current page is NOT one of 2 page templates
I've been using this `if` conditional statement to only show content if the current page is NOT using a certain page template;
if (! is_page_template('template-custom.php')) {
<!-- show some content -->
}
which has been working fine. Only now I need to amend the statement to show content if the current page is NOT using one of 2 templates (So if the current page uses `template-custom.php` or `template-custom2.php` do NOT show the content).
I tried this;
if (! is_page_template('template-custom.php') || is_page_template('template-custom2.php')) {
<!-- show some content -->
}
and this;
if (! is_page_template('template-custom.php') || ! is_page_template('template-custom2.php')) {
<!-- show some content -->
}
but to no avil.
Any suggestions? | If you want don't want to show content if the current template is `template-custom.php` or `template-custom2.php` you can use:
if (!is_page_template('template-custom.php') && !is_page_template('template-custom2.php')) {
<!-- show some content when you AREN NOT in template-custom.php NOR template-custom2.php -->
}
or
if (is_page_template('template-custom.php') || is_page_template('template-custom2.php')) {
<!-- show some content when you ARE in template-custom.php OR template-custom2.php -->
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "page template, conditional tags"
} |
File exceeds upload_max_filesize, despite max filesize being large enough
I am trying to upload a 762KB picture using the multi-file uploader at /wp-admin/media-new.php. This page reports that my maximum upload filesize is 2GB.
However, once the upload progress bar gets to 100%, the upload fails with
> The uploaded file exceeds the upload_max_filesize directive in php.ini.
I am aware of how to set my upload_max_filesize and associated variables in php.ini, but that appears to be correct. What else could be causing this?
Other potentially useful information:
* post_max_size is 3G
* max_execution_time is 600
* memory_limit is 256M
* The site is hosted on Dreamhost (shared hosting, unlimited storage).
My .phprc:
upload_max_filesize = 2GB
post_max_size = 3G
max_execution_time = 600
memory_limit = 512M
max_input_time = 500 | It was a simple typo in my phprc.
`upload_max_filesize` should be `2G`, not `2GB`.
It's interesting that WordPress and PHP/phpinfo() still picked it up and claimed the limit should be 2GB, though it makes perfect sense as to why uploads weren't working correctly. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp admin, uploads"
} |
Enqueueing Scripts and Styles
I'm trying to enqueue my custom script and style with the block of codes, the scripts works but not the style. I don't know what I'm doing wrong.
function my_scripts_method() {
wp_deregister_script( 'jquery' );
wp_deregister_script( 'style' );
wp_register_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' );
wp_register_style( 'style', '//siteripe.com/style.css' );
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
add_action('wp_enqueue_style', 'my_style_method'); | I think you are using the wp_enqueue_style the wrong way as it is not an action hook. wp_enqueue_scripts action hook is being used for enqueuing both scripts and styles. try this:
function my_scripts_method() {
wp_deregister_script( 'jquery' );
wp_deregister_script( 'style' );
wp_register_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' );
wp_register_style('style', '//siteripe.com/style.css' );
wp_enqueue_style('style');
}
add_action('wp_enqueue_scripts', 'my_scripts_method'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp enqueue script, wp enqueue style"
} |
Query Posts by Tag and exclude
Is it possible to only include posts with a specific tag in this query?
<?php $query = new WP_Query
(array('showposts' => 5, 'orderby' => 'date', 'order' => 'DESC'));
while ($query->have_posts()) : $query->the_post();?>
Also is there also a way to exclude posts with a certain tag as well?
Thanks! | It seems you're looking for the `tag` parameters:
$args = array(
'posts_per_page' => 5,
'tag' => 'YOUR-TAG-SLUG',
'orderby' => 'date',
'order' => 'DESC',
);
$query = new WP_Query($args);
while ($query->have_posts()) :
$query->the_post();
...
endwhile;
// don't forget to reset/restore the query
wp_reset_postdata(); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query, tags"
} |
How to set two different themes on one WordPress? (Desktop vs. Mobile)
I created two WordPress themes.
First for the Desktop and second for tablet/mobile. I want to set on one URL. When the website opens, the theme should change automatically based on resolution. | To employ two entirely separate themes is a suboptimal architectural approach.
Themes are activated site-wide/globally and not on a per-user basis. You don't want to change the current theme constantly.
While I personally really dislike this option, WordPress ships with a function that sniffs the UA-String, `wp_is_mobile`.
This function can be employed to either output alternative markup and/or load an alternative stylesheet (from within the same theme).
Or - and this is my personal choice - familiarize yourself with CSS3 mediaqueries. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "themes, css"
} |
Woocommerce get cart total price in a number format
Is it possible to get the cart total price without any markup. So without the € symbol? Right now I'm getting the amount with:
$totalamount = $woocommerce->cart->get_cart_total();
this will give €16.50
I tried this also:
$totalamount = number_format($woocommerce->cart->get_cart_total(), 2, '.', '');
But this always gives 0.00
Is there a woocommerce get function that will give a number format of the total cart price? Thanks! | ## Update 2020
**Answer**
See flytech's answer for a solution using the native WooCommerce API.
**Note / Caveat**
If you're going to do proper arithmetic with monetary values, **_always_ use signed integers (!) representing the smallest denomination of a given currency** (Cent, Penny, Paisa, Dirham, e.g.).
Only convert back to decimal fractions in the presentation layer of your application _after_ all calculations are done.
This holds true regardless of language or framework.
## Original answer
I don't know woocommerce at all and hence there might be a native way as well, but anyhow, this
$amount = floatval( preg_replace( '#[^\d.]#', '', $woocommerce->cart->get_cart_total() ) );
should do.
The `preg_replace` eliminates everything but decimal characters and colons.
Should you care to do math with it, the `floatval` converts the value from a string to a numeric one. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 8,
"tags": "plugins, terms, markdown"
} |
find pods item where relationship to other pod is not set
I need to fix the effect of an error that left empty a relationship field that should have been autofilled.
To fix this I need to find all pods item that has the relationship not set, but I don't know how to do it.
I tried with `'where' => 'source.id = ""'` in a `find()` but with no luck.
Any idea? | What you want is:
`source.id IS NULL`
This will match items that have no source set at all. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "sql, pods framework"
} |
Internal error (500) on local & Fatal error on live when trying to access post type edit screen
I'm building a CMS for a company that has 60,000+ static pages which have been converted into posts. 30,000 of these are a particular post type. When I try to access the edit screen in the admin area (<
On my local server I get an internal 500 error.
On my live site, (database migrated with wp-migrate-db-pro) i get:
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes) in /home/omol/public_html/wp-includes/post.php on line 1876
seems like 256m should be enough memory? I wasn't having this error before and was able to see the 30,000 articles on the edit screen just yesterday.
I've reverted to twenty-twelve theme & checked the htaccess, to no avail. | This sounds like you have a hierarchical post type. You will have trouble with hierarchical post types with large numbers of posts because query results have to be sorted/resorted. Register you post type with hierarchical set to false, if you can. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql"
} |
get post count for related author
I'm trying to use the code below to obtain the number of custom posts the author of a post has published.
function count_user_posts_by_type( $userid, $post_type = 'artistblog' ) {
global $wpdb;
$where = get_posts_by_author_sql( $post_type, true, $userid );
$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
return apply_filters( 'get_usernumposts', $count, $userid );
For example I'm outputting a loop of custom post types. Next to each post title I'm displaying the author of the post using a similar get_related_author function. I also want to display the number of posts this author has published. I assume I just need to replace $userid with the_author_meta() somehow but haven't managed to get it working.
Am I even approaching this in the right way?
Thanks D | You need to read query_posts link to do this. Here you can see 'author' - Order by author.
Simply you can do: `SELECT count(ID) FROM wp_posts groupby author;` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, author"
} |
How to remove featured images from posts
Somehow my theme doesn't recomend featured images. That being said, how can i remove featured images from posts? | 1. Use Developer tools in Google Chrome and see what section is responsible for displaying the featured image on post page.
2. Open page.php or single.php (relevant file responsible for generating single page) and delete that code.
Keep a backup of the file before making any changes :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post thumbnails"
} |
Specify Table Column Width on a Page
I currently have the following html on my Wordpress page
<table border="5">
<col width="50">
<col width="100">
<tbody>
<tr>
<td>
<h4>NLP</h4>
</td>
</tr>
<tr>
<td>Overview</td>
<td>A natural language processing challenge.</td>
</tr>
</tbody>
</table>
However the `<col width="50">` seems to be getting ignored. Is this getting overridden by something in the CSS and if so how do I fix it? | You could do it like this?
<table border="5">
<tbody>
<tr>
<td width="150" colspan="2">
<h4>NLP</h4>
</td>
</tr>
<tr>
<td width="50">Overview</td>
<td width="100">A natural language processing challenge.</td>
</tr>
</tbody> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "columns, table"
} |
How can I check if on specific plugin generated page or child
I am writing a function to force a redirect when accessing a certain page.
I have done similar things using code like
if ( is_main_query() &&
( is_singular($restricted_post_types)||is_single() )
&& ! is_user_logged_in() ) {
wp_redirect(...)
}
But now I want to target a certain class of pages (profile related pages in the bbpress plugin bc Genesis is destroying them). I don't know what I can use to identify this from an action in the template_redirect hook.
I think anything with the pattern `'<baseurl>/forums/user'` would catch what I need | If you're trying to catch the pattern '/forums/user', you could use PHP's stringpos function. Something like this should capture what you're looking for:
$url_pattern = "/forums/user";
$requested_uri = $_SERVER["REQUEST_URI"];
if(strpos($requested_uri, $url_pattern) == 0){
//Your code goes here
}
Make sure if you have "enforce trailing slashes" set that you use "/forums/user/" as your matching pattern instead. This code isn't tested but should work. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, redirect, bbpress"
} |
How to access data in wordpress database externally using php
I want to share data in specific wordpress database tables with an iOS app. The client wants data entry via wordpress form plugins which create their own tables in the wp database. The plugins I've looked at don't have APIs themselves and examples of wordpress REST APIs all use AJAX which I'm not familiar with and/or can only access info in wordpress posts or user data. Is there a way to do this via php that doesn't involve accessing the database directly? I fear changes in database structure with updates could break the app. | Unless you want to use PHP to run queries directly on your database, you'll have to use a REST API and Javascript to gather the data. One point worth noting is these REST API's also use direct database queries in order to gather info to return to you when you make a request. This means that any updates to Wordpress database structure that would break your app if you wrote PHP to access the DB would also break the API plugin you use. The only difference is most plugin devs are pretty quick as far as updates go when their code becomes deprecated, and may be able to fix any issues faster than you could.
Here's one JSON API plugin I found in the Wordpress repo: <
I'm sure there are others. Just look around. Let me know if this helps clarify things a bit. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, php, database, api"
} |
How to store category and tags separatly on wordpress?
I am trying to insert data manually on all tables on the back end. I am facing a problem while inserting data to `wp_terms`. I can successfully insert category into `wp_terms` and define relationships in `wp_term_relationships` and `wp_term_taxonomy`. How does WordPress differentiate between category and tags ? | take a look at **wp_term_taxonomy** table you will see a column called taxonomy, categories has "category" taxonomy in the field for each category and tags has "post_tag" taxonomy, custom defined taxonomies are also working this way. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, database, tags, terms"
} |
Can WordPress handle following functionalities?
Now i am planning a development of a new web site and searching for a CMS. I know WP not bad, but never tried to build a complex community information site using this engine.
Among basic requirements there are following, i would call them "community":
\- user-panel (user profile with settings, history of activity etc)
\- users possibility to rate topics/comment/post
\- posts output according to those ratings
\- site log in/register via Facebook/Twitter account etc
Are there any popular, stabe extensions that could handle those "community" needs without deep rebuilding of engine?
_I know that all of those features can more or less be made using CMS with some extension such as Joomla, Drupal and LiveStreet, but in this project i want to exclude them._ | Most of the times when someone uses the words "Wordpress" and "community" together the answer is Buddypress.
Regarding your requirements I would say:
* social media login,
* user panel
can be handled well by plugins, but
* content rating,
* output content based on ratings
sounds like something that has to be custom-coded.
But this also depends on what content should be voted on and how the voting should be handled. I know there are buddypress plugins available for rating forum posts and pictures.
I would advise you to just install wordpress + buddypress and some plugins and see if this provides you with 95% or 50% of your requirements. After all it's not only about if there are plugins available for something but also how they work. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, comments, cms, rating, customization"
} |
$wpdb->insert Giving duplicates
I'm getting duplicate entries with this, how can I fix it please?
<?php
echo "Month". $_POST["Month"];
global $wpdb;
$wpdb->show_errors();
$wpdb->print_error();
$wpdb->insert(
'church',
array(
'Firstname' => $_POST["Firstname"],
'Surname' => $_POST["Surname"],
'Month' => $_POST["Month"],
'Day' => $_POST["Day"],
'Email Address' => $_POST["Email"],
'Mobile Number' => $_POST["Number"]
)
);
?> | There is nothing that prevent duplicates here.
When you create the table `'church'` is a good idea set a `UNIQUE` sql index for field email, in this way you can rely on email address to preventing duplicate entries.
As a generic PHP good practice, you should check the existence of a a variable before using it, using `isset` function:
/* If $_POST['email'] is setted and it is a valid email address */
if ( isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
global $wpdb;
$exists = $wpdb->get_var( $wpdb->prepare(
"SELECT COUNT(*) FROM 'church' WHERE email = %s", $_POST['email']
) );
if ( ! $exists ) {
/* Your insert code here */
}
}
P.S. Is also a good idea prepend the WordPress table prefix in front of custom table names. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "database, wpdb, duplicates"
} |
How to hook into action/filter call
I'm about to create a very simple logging plugin.
Every time an action or filter is fired I need to log it to the file. The idea is that we will be able to see exactly which actions and filters are executed (and functions they run) for every page load. This includes the order that they run in. | The callbacks hooked onto 'all' are called prior to the callbacks for _any hook_ (action and filters) being called. (See source)
add_action( 'all', 'wpse115617_all_hooks' );
function wpse115617_all_hooks(){
//This is called for every filter & action
//You can get the current hook to which it belongs with:
$hook = current_filter();
}
See < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, filters, hooks, actions, logging"
} |
Remove category link
I want to use categories but I also want to remove the category pages.
Assumed that this category exists this URL should return a 301 and redirect to
I've tried to add a `category.php` to my theme but this won't work for me.
I don't want to hide posts with a specific category or remove the category base or something like that. I'm using WordPress 3.6.1. | Hook `'template_redirect'` action hook and redirect if in category using `wp_redirect`
add_action('template_redirect', 'no_cat_archives');
function no_cat_archives() {
if ( is_category() ) { wp_redirect( home_url(), 301 ); exit(); }
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories"
} |
How to get the wpnonce value?
On using inspect element to check the 'href' attribute of 'Deactivate' links for the plugins listed on plugins.php page, I found that the url contains a wpnonce field with a certain value. I need to get this value. For eg,
<a href="plugins.php?action=deactivate&plugin=my-custom-css%2Fmy-custom-css.php&plugin_status=all&paged=1&s&_wpnonce=08a2b0d940" title="Deactivate this plugin">Deactivate</a>
How do I get this value '08a2b0d940' as in the above link ? | That value is a random-ish string generated for one-time use with a lifespan of, if I remember correctly, 12 hours. I am not sure what you mean by "get" the value. Assuming you mean "generate the nonce" then...
You want `wp_nonce_url` or one of the related functions.
wp_nonce_url( $actionurl, $action, $name );
For example:
wp_nonce_url( '
You can't regenerate the value if that is what you want but you could regex it out of the URL with PHP, circumstances permitting, or use Javascript to search the generated markup. Since I don't know _why_ you are trying to do this, a solid answer is difficult. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "plugins, nonce"
} |
What action to use for when a post is saved / published, with a caveat
I'm trying to do some stuff when a post has been saved, I'm currently using the `save_post` action, of which generally works.
However, the problem I'm having is when a post is scheduled it fires the `save_post` action, of which changes some data I don't want it to.
Is there an action of which fires **only** when the user clicks publish / save in the post edit screen, and **not** when a post changes schedule status. | Check `if ( defined( 'DOING_CRON' ) && DOING_CRON )`, which will be true if the post save is triggered during a scheduled cron job. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "save post, scheduled posts"
} |
How can I make new .css file in child theme override styles in child theme's style.css
I want to make a separate responsive.css file in my child theme but having trouble making the media queries override the styles in the child theme's default style.css.
I've tried putting `<link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri(); ?>/responsive.css" type="text/css" media="screen"/>` after the `<?php wp_head(); ?>` code, which works, but I've read that this is not good practice.
I do not really want to add the media queries to the end of style.css as it's already large and getting quite confusing! | You can enqueue your own stylesheet by adding this to your child theme's `functions.php` file:
function wpa_custom_css(){
wp_enqueue_style(
'wpa_custom',
get_stylesheet_directory_uri() . '/responsive.css'
);
}
add_action( 'wp_enqueue_scripts', 'wpa_custom_css', 999 );
This will load the file `responsive.css` located in your child theme directory. The priority is set very low (999) so it is more likely to appear after other styles which may be enqueued on the same action. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "child theme, css, wp head, responsive"
} |
How can I stop Jetpack mobile theme from using full size featured images?
The site I'm managing is using Jetpack's mobile theme for mobile devices. This works relatively well, except for the fact that for featured images the mobile site loads the full sized image instead of the resized thumbnails used by the desktop theme.
With some of the images going up to 3000px wide in their original resolutions, this means that most pages on the site is actually larger on the mobile theme than on desktop. The worst offender is the archive pages, where a large number of featured images is shown. As can be seen here, some pages are 5x as large on mobile.
 uses the main theme's default `post_thumbnail_size`, which is set using `set_post_thumbnail_size`. Adding this line to my main theme's `functions.php` inside a function called through the `after_theme_setup` action helped solve the problem:
set_post_thumbnail_size( 600, 400, true ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "mobile, plugin jetpack"
} |
Embed YouTube, login to buy & payment methods
As you can probably tell, I'm new to WooCommerce and WordPress in general.
Before I start building a site and buying plugins and extension I would like to know:
* Can you easily embed YouTube videos onto product pages with WooCommerce?
* Does the customer have to log in or create an account to buy an item through WooCommerce?
* Can a customer pay via credit or debit card through PayPal and not have a paypal account when using WooCommerce? | From Woocommerce docs:
> WooCommerce includes options to allow guest checkout, meaning customers do not need an account to make a purchase;
Paypal standard merchant functionality permits people to use credit or debit card instead of a paypal account.
WooCommerce is based on custom post types, and uses the standard editor field, so embedding a youtube video in your product would be just as easy as adding a video to a blog post. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Wordpress Customizer: custom redirection after closing
Someone knows if is there a way to customize the redirection after a user click "close" in the Wordpress Customizer" live editor?
It would be very useful. Thank you very much. | You might try to use _jQuery_ to change the url behind the _Close_ link.
Another idea would be to use `wp_get_referer()` to intercept the page loading when you go from `customize.php` to `themes.php` by hooking into the `load-themes.php` action:
add_action( 'load-themes.php', 'my_customize_redirect' );
function my_customize_redirect() {
if ( strstr( wp_get_referer(), '/wp-admin/customize.php' ) )
{
$url = get_admin_url(); // EDIT this to your needs
wp_safe_redirect( $url );
exit();
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "redirect"
} |
Unfortunately removed myself as plugin committer
Unfortunately I removed myself as plugin committer. I was only committer of my plugin. So that, I couldn't find any options to add me back again.
What can I do now?
Please Help. | Write an email to `plugins [at] wordpress.org`, and explain your problem. There is nothing you can do without their help. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, author"
} |
A question of etiquette when forking a plugin?
I am updating (forking) a WP plugin over on Github - with some functionality on the plugins roadmap - so I know this feature is desired by the developer and will probably be included in their next update through WP plugins.
When updating the plugin with my additions, do I also update the readme.txt file etc and add my username as a contributor (I guess this should be the case)? Or should I contact them and ask to be put on?
It is my expectation that if I had contributed then I would be credited here but not sure on the right approach!
Thanks for any advice ;) | IMHO Yes put your name as a contributor, you've contributed to that fork. However personally I'd let the lead developer know just so you and they don't duplicate work (unless they decide they don't want your code, but you won't know that till you've tried). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development"
} |
how to debug shipping module / class
I'm working on an own shipping module and want to print some arrays. But, the module is operating in the background, so I can not print the arrays. Is there a way? | Yes, add this function to your module
function my_print_r( $msg, $name = '' )
{
$error_dir = '/path/to/wordpress/wp-content/debug.log';
$msg = print_r( $msg, true );
$log = $name . " | " . $msg . "\n";
error_log( $log, 3, $error_dir );
}
And call `my_print_r( $variable_to_inspect, 'description' );`. The file `debug.log` is originally used by `WP_DEBUG_LOG`, and if you don't have it enabled only your debug info will be there. This plugin of mine shows the content of that file in the dashboard. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
I'm not able to get access to $wpdb
I'm developing some additional functionality with a jQuery autocomplete form, some custom database tables, and PHP to query the tables.
I have it working outside of the WordPress framework using mysqli for the database part.
I've added the form to a WordPress page (and added the jQuery references to the header). When I run the Firefox Web Developer Web Console, I can see that the jQuery is doing its job up to the point of calling the PHP script.
My PHP script is in the root directory of my Genesis child theme.
The PHP script is where it hangs, and it appears that I'm not getting access to the information in `$wpdb`. I executed this script in the same directory as a test:
<?php
echo "got here";
global $wpdb;
print_r($wpdb);
?>
I see "got here" but nothing else.
Is there something else I have to do to get access to `$wpdb`? Apparently me declaring it `global` isn't enough. | If you're not using WP's built in Ajax handlers, which includes things for you, you will need to include the WP core yourself. Try adding
define('WP_USE_THEMES', false);
global $wpdb;
require(BASE_PATH . 'wp-load.php');
to the top of your file. I should point out that the path to `wp-load.php` may not be the same and hard coding the path will make your code un-portable. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "database, wpdb, user access"
} |
Add filter to comments loop?
I'm making a plugin which stores referrer data for comments. I already have my database table created, and the data is being stored correctly when a comment is made.
Now I would like to attach a custom div to the comment block for each comment. How would I add a filter to the comment loop? I want to say "if this comment ID has a referrer logged in my table, then print out the referrer in my special div". I can write the function myself, I just need help on where to inject my function. | It is hard to say what you need to hook into without knowing all the details but I think you may be able to use `comment_text`\-- more or less the `the_content` of comments.
add_filter(
'comment_text',
function ($comment) {
return $comment.'<div>This is your special division</div>';
}
);
If that isn't quite right, take a look at the filters listed in the Codex for comments. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments"
} |
Rearranging Dashboard meta boxes with use of plugin/functions.php
I know how to remove meta boxes from dashboard, also how to add new ones, but is there a method that allows to rearrange them, for example move from `side` position to `normal` with use of functions.php or a plugin?
I know that it would require to fire only once somehow, to allow user to rearrange elements in the future, but in that case, it might just do it every time it loads - elements on dashboard are limited and functionality to rearrange them can be disabled completely. | `add_meta_box` has a the following _placement_ parameters:
$context
'normal', 'advanced', 'side'
$priority
'high', 'core', 'default' 'low'
For `$context` the difference between _normal_ and _advanced_ is that _normal_ will be placed on the page before _advanced_.
The `$priority` determines the hierarchy but is overridden when dragged by the user. You can disable the drag and drop functionality.
Furthermore `do_meta_boxes` can be used to place (output) the registered meta box, for example if you want to place the meta box above the WYSIWYG editor you can use it in a function which fires `edit_form_after_title`.
If you only want to run an action once you can some trickery with `did_action`, for example:
function action_trickery_115819(){
if(did_action('admin_init') === 1) {
//some action to run once
}
}
add_action( 'admin_init', 'action_trickery_115819' );
< < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "plugin development, metabox, dashboard"
} |
Create service similar to wordpress.com
I am looking to build a service for users where they can signup (using an online form such as Gravity or Ninja forms) for a website either as a sub domain or sub directory of the main website similar to wordpress.com. I am using wordpress multisite, but I cannot find anything online on how to accomplish this. Is there a special plugin or script/scripts that I can run? | You don't need a separate form to create a register page.
Go to the network Dashboard » Network setting » Enable both sites and users can register, and you are ready to go.
Visitors now to your site can register a new site at this URL:
yoursitename.com/wp-signup.php
And for reference you can go through this source to get a bit more handy on WordPress Multisite:
* WordPress Multisite Guide - WPMU.ORG
Let me know if helps to solve your problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "multisite, forms, wordpress.com hosting, signup"
} |
Plugin or shortcode for ISBN number?
I have a Woocommerce site with a catalogue of books. Each book has an ISBN (or EAN) number entered in a custom field.
I need to do two things with the ISBN, and I don't want to have to manually enter code for each product:
1. I need to link to the Google books preview (at the moment I do this manually by adding another custom field with this script (only the ISBN changes from product to product)
`<script type="text/javascript" src=" </script> <script type="text/javascript"> GBS_insertPreviewButtonPopup('ISBN:978-1-920590-37-6'); </script>`
2. I need to link to the products for sale via a number of other online shops, with my affiliate ID followed by the ISBN number, for example
`
Can anyone tell me whether I need to create a plugin or use shortcode to achieve this? | I've had some help from a developer, and would like to share the solution:
function get_google_tag( $isbn_metadata ) {
return (
/* '<span class="post-meta-key">Preview: </span>' . */
'<script type="text/javascript" src=" .
'<script type="text/javascript">' .
'GBS_insertPreviewButtonPopup(\'ISBN:' . $isbn_metadata . '\');' .
'</script>'
);
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, shortcode, plugins"
} |
How to add image on top of header logo in child theme?
How do i add an image (icon that will link to photographer's page) on top of my logo
that is already part of my theme, into the child theme functions code, so that it will be saved if i ever upgrade the theme?
I don't know how to use widgets to achieve this nor have I found a suitable plugin.
I currently have it hacked into the parent theme's header file. | You have done the most of it, just that you haven't realized it yet. If you are using a child theme then you can copy and paste the header.php from the main theme into the child theme folder and make the exact same changes you have made now to keep the icon above the logo.
Now the header.php in child theme will load instead of the main theme's.
In doing so the changes remain preserved even if the main theme is upgraded/updated.
**Files inside the child theme remain preserved on parent theme update**
Another way is to find suitable hooks from the header.php file and code it in the child theme's functions.php file.
Hope it helps! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "header image, logo"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.