INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Is it possible to rewrite a page url Without setting the permalinks to Post Name?
Is it possible to rewrite the page url if your page link is for example `localhost/wordpress/?p=123` ? Instead of `post_name.php?...`. (So the first option of permalinks and not `post_name`. | The reason this was not working is due to `Localhost` you apparently can't do this without having a online wordpress site. Locally this is not possible. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, url rewriting, urls, rewrite rules"
} |
WordPress is adding rel="nofollow" and target="_blank" to internal links in posts and pages
For some reason WordPress started to add rel="nofollow" and target="_blank" to some of my links in my posts and pages. Not to all my links but randomly.
I really dont know why because when I'm editing my post it is just a normal link without rel="nofollow" and target="_blank". Adding target="_self" or rel="dofollow" doesnt change anything.
Why is this hapening and how can I solve this problem? Anyone got the same problem and knows a solution?
Thanks in advance:)
This is an example page and I'm taling about the link "control panels" | When you place a link into a WordPress post or page the link window, where you specify where the link is to lead, has a check box for specifying that you want to open the link in a new window.
There is a similar box in the advanced settings tab of any graphical element you place in a post or page.
If one of those boxes is not checked on the "target= _blank" links then I would suspect a setting in one of your plugins, probably an SEO plugin.
The troubling part is the inconsistency. A plugin setting should be a consistent result. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "links, nofollow"
} |
Basic do shortcodes question
I used WordPress codex page to code. As you can see I have 2 PHP codes in my line. The page is able to get the code's value but it doesn't obey the CSS rules, which I believe, because I inserted my PHP codes in the wrong way.
Can you take a look at the following code and suggest to what the problem might be?
<?php echo do_shortcode('[groups_non_member group="VPS"]' ."<p class='vod-time-price'>" . the_field('run_t') . "MIN | $". the_field('price_per_r') ."</p>". '[/groups_non_member]'); ?> | `the_field()` is an ACF function and will `echo` content. It follows the WordPress (somewhat) pattern whereby functions with `the_` at the front will `echo` content and functions beginning with `get_` return content.
> Displays the value of the specified field. (this is the same as “echo get_field($field_name)”)
>
> <
Using the wrong function, as you have, will cause data to output in the wrong location. Use `get_the_field()` instead. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "shortcode, advanced custom fields"
} |
How to merge two Wordpress themes?
I have a project in which I want to merge two wp themes, I have two themes in which one has a great interface i want to use this interface and second theme has a good functionality so I want to use that fuctionality with first theme, but I have no idea about this, can it be possible??? if yes how can I achieve this provide some refrence. | Milo is correct, it is a very broad question. That said, what you want to do is totally doable, BUT, it is going to take effort.
There is no easy way in mergin two themes into one. You will have to set up a completely new theme, and then you have to start to extract every little piece of code from these two themes, add it into your new theme and integrate them them to work in harmony.
There is unfortunatly no other quicker way of doing it that I know off or came across. Make yourself ready for a bumpy ride and enjoy the ride | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "themes"
} |
Unsual behaviour of navigation Menus
I deleted all the previous menus which where there in my site. Then I created a new menu called Home and added few pages to it
So my menu looks like this!enter image description here
**Problem :** When I click on About us and other links, then that links are not working. Why is this so??
Is it because I deleted all my previous menu? If so then how I can get my deleted menus?
Update:
Error in firebug!enter image description here | Problem was the theme that we purchase didn't upload the plugins and other Java Script files properly
So it was giving an error. Going through theme installation document helped me. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "menus, links"
} |
Incorrect filenames in load-scripts.php parameters
I'm attempting to load the media upload js file in a widget. The code works on my development machine and on the staging site but not on the live server. The error I get is that wp.media is undefined.
I enqueue the scripts & styles I need with:
public function enqueue_admin_scripts($hook) {
if( $hook != 'widgets.php' )
return;
wp_enqueue_style('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_script('shw', get_template_directory_uri().'/js/custom-media.js');
}
However when viewing the link that is created, I see the following: `
As you can see `media-upload` has been displayed as `media-uplo&load` so the media functions are never included.
Has anybody come across anything like this before or can give me some advice on where to start debugging? | Do you have the "all-in-one-wp-security-and-firewall" plugin?
More info: <
Short answer, if so, disable the "Deny Bad Query Strings" option. If not, check for any other "security" plugins you have that might be doing dumb things. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "uploads, wp enqueue script"
} |
Add Wordpress to Meteor js site
I have a Meteor app that I want to add Wordpress blogging platform to.
There doesn't need to be any integration, just:
<
Anything behind `blog/` belongs to WP.
How would I go about doing this? Thanks in advance. | This question is probably beyond the scope of WPSE. But my solution would be to install PHP-FPM and run Node and PHP-FPM on different ports behind Nginx.
Sample Nginx Config (will require tweaking)
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass // Assuming Node is running on port 3000
proxy_redirect off;
}
location /blog {
rewrite /blog/?(.*) /$1 break;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass // Assuming PHP-FPM is running on port 9000
proxy_redirect off;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "php"
} |
Displaying a custom field
I'm trying to display a custom field called 'my_custom_field' inside the loop:
$custom_array = get_post_custom( get_the_ID() );
echo $custom_array['my_custom_field'];
This code display "array". Should it not display the value of the custom field instead? | `get_post_custom()` will return an array of arrays. You need:
echo $custom_array['my_custom_field'][0];
Alternatively, you can use `get_post_meta()` with the `$single` flag as `true`:
echo get_post_meta( get_the_ID(), 'my_custom_field', true ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom field"
} |
Is author.php a core file?
I want to change the author.php with more information. Can i edit author.php without it remove my code, after a Wordpress update? Or is there some hook for this. | If you are talking about `author.php` in your theme directory, usually at `wp-content/themes/<YOURTHEMENAME>` this isn't a core file but part of your theme.
Themes don't get changed when WordPress is updated, so concerning WordPress updates themes are safe.
**But** if your theme isn't custom made by you (which I assume here) this file would be changed if you update your theme. So to be safe you should create a child theme as child themes make it possible to update the parent theme while keeping your child theme changes. Details about how to create a child theme can be found at the WordPress Codex | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "author, profiles, author template"
} |
How to tell a theme to use different .mo and .po files?
I have a theme which loads .po and .mo files to display strings in English. I want to have only one language (Polish), but those two files are en_US. I tried replacing content in the en_US.po file but nothing changed on the website, I do not know why. Where does it store strings if changing .po files changes nothing? | There are already an `en_US.po` file in the theme you are using. You can simply make a copy of that file and rename it as `pl_PL.po`. You can now open the `pl_PL.po` template with poedit, do all your translations in there, and just save it. Poedit will automatically create a `pl_PL.mo` template.
No need to go through all the pt. Just remember, as previously stated, change the language in the `wp-config.php` to `pl_PL` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "themes, multi language, translation"
} |
Force wp_enqueue_scripts to the HEADER?
A plugin I'm working on requires jquery to be loaded before the content is processed. Some stock themes, like 2010, 2011 and 2012 (I believe) put the JS in the footer.
How can I force the scripts to be loaded in the header (I will notify users of the plugin that the plugin requires this)? | The normal behavior of `wp_enqueue_script` is to put the script output into the head section, the parameter `$in_footer` is optional and defaults to `false`. So, you can load jQuery with your plugin into the head and, assumed your dealing with well programmed themes/plugins, it won't load again, because `wp_enqueue_script` prevents this by default - additional information about that here. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "jquery, headers"
} |
Define locale WordPress uses with gettext functions?
I'm trying to localize my plugin. I have two `.mo` files:
/lang/myplugin-es_ES.mo
/lang/myplugin-en_US.mo
The translation works but I don't understand how to change the language to use the `en_US` file instead of the `es_ES`. This is what I'm trying:
function define_locale($locale) {
$subdomain = array_shift(explode(".",$_SERVER['HTTP_HOST']));
if($subdomain == "en")
return 'en_US';
else
return $locale;
}
// Define Locale
add_filter('locale','define_locale',10);
While `get_locale()` shows the locale is `en_US` my plugin still uses the `es_ES` file. What am I doing wrong? | Have you tried to add/change language flag in `wp-config.php` file
define ('WPLANG', 'en_GB');
REF: Installing WordPress in Your Language | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "localization"
} |
$wpdb->wp_users returning empty value for
I have a code Example:
function custom_func(){
global $wpdb;
$wpdb->flush(); //tried with and without this line
$getTest = 'SELECT * FROM $wpdb->wp_users LIMIT 1';
$arrayReturned = $wpdb->get_results($wpdb->prepare($getTest));
}
From what I've read I thought that $wpdb->wp_users is meant to have returned the database name and table name like so dbName.tableName; but it just returns an empty value.
I've tried:
$getTest = 'SELECT * FROM $wpdb->wp_users LIMIT 1';
which shows as the following to wordpress:
SELECT * FROM $wpdb->wp_users LIMIT 1
and
$getTest = 'SELECT * FROM '.$wpdb->wp_users.' LIMIT 1';
which shows as the following to wordpress:
SELECT * FROM LIMIT 1
I can't fathom why this isn't working since this is all based on literature from the wordpress codex, any thoughts? | First of all why you would need custom query for this basic functionality to get users, when WordPress has inbuilt function **get_users()**.
Anyway for custom query, table name is defined as
function custom_func(){
global $wpdb;
$getTest = "SELECT * FROM $wpdb->users LIMIT 1";
$arrayReturned = $wpdb->get_results($wpdb->prepare($getTest));
}
It's **$wpdb->users** or **$wpdb->post** and not **$wpdb->wp_users** , what you use for a table name, in custom queries.
Also I've used the double quotes **" "** for query and not single quotes **' '** , you can read here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, functions, mysql"
} |
SQL to update custom post taxonomies
I have a custom post "review". It uses the same categories and tags from default posts, so they share "category" and "tag" taxonomies.
But later I changed the "review" register to have their own taxonomies, "review-category", and "review-tag". Of course all tags and categories previously assigned on reviews was unbind from them.
So the question: how can I (if possible) convert all tags and categories only in reviews to the new taxonomies? If I wasn't clear enough:
UPDATE wp_term_taxonomy SET taxonomy='post-tag', parent=0 WHERE taxonomy='tag';
This can convert all "category" to "post-tag", but I need to do it only for reviews. Something like (it doesn't work):
SELECT FROM wp_posts WHERE post_type='review'(
UPDATE wp_term_taxonomy SET taxonomy='post-tag', parent=0 WHERE taxonomy='tag';
) | You will need to join four tables to get categories of custom post type "review"
1. wp_term_relationships
2. wp_posts
3. wp_term_taxonomy
4. wp_terms
by using following query you can get list of categories applied to your custom post type:
SELECT *
FROM wp_term_relationships AS tr
LEFT JOIN wp_posts AS p ON tr.object_id = p.ID
LEFT JOIN wp_term_taxonomy AS tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
LEFT JOIN wp_terms AS t ON t.term_id = tt.term_id
WHERE p.post_type = 'review' AND tt.taxonomy = 'category';
and then update the type of these categories to your new custom category (i.e. "review-category")
UPDATE wp_term_taxonomy SET taxonomy = 'review-category' WHERE term_taxonomy_id IN (1, 71, 72);
change where clause according to your category ids.
For more information visit following WordPress documentation links:
Database_Description
WordPress_Taxonomy | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy, query, sql"
} |
Get All In One SEO Pack to use custom field instead of Content
I'm having an issue with a custom theme whereby All in One SEO pack isn't auto-generating descriptions because I am using a custom field to enter the main body of the page/post. Is there way to specify that All in One SEO uses a specific field to read from for the purpose of generating the SEO content automatically? | You can not specify which field, but you can use the filter *aioseop_description* to do whatever you want with the description before presenting. So technically, you can use your custom field as follows (untested) :
add_filter('aioseop_description','my_custom_description');
global $post;
function my_custom_description($text) {
$mycustomseo = get_post_meta($post->ID, 'my_custom_field', true);
return $mycustomseo;
}
Replace *my_custom_field* with your custom field.
Source Ref : < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, seo, advanced custom fields"
} |
$count_posts->draft & published
Currently our portfolio is stacking up a lot and want to show a few projects less instead of showing all. Still, I'd like to show an indication how many projects we did in total. Currently I have the following code and need to count the drafts & published posts.
$count_projects = wp_count_posts( 'apps' );
$published_projects = $count_projects->publish;
$total = $published_projects + 11;
How can I count all drafts & published posts together? | In this line you are getting only the count of published items ( **obviously!!!!** ):
$published_projects = $count_projects->publish;
You should do something like this:
$count_projects = wp_count_posts( 'apps' );
$published_projects = $count_projects->publish;
$draft_projects = $count_projects->draft;
$total = $published_projects + $draft_projects;
More details and examples in `wp_count_posts()` reference. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "count"
} |
How to hook in after user's registration email has been sent?
I want to redirect to a page **after the user's registration email has been sent**. What is the correct hook?
`user_register` is too early, that is the user is entered into the database but the email isn't send.
Thank you! | I would use the `registration_redirect` filter. This allows you to set _where_ the user is sent to, but leaves WordPress to perform the redirect (after everything has successfully processed).
function wpse_139267_registration_redirect( $url ) {
return site_url( 'thank-you' );
}
add_filter( 'registration_redirect', 'wpse_139267_registration_redirect' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "hooks, user registration"
} |
Password recovery URL has error - but not found in code or db
On a multisite/network install, all of a sudden my password recovery URL has a problem:
http//my.domain.com/wp-login.php?action=lostpassword
Note the lack of a colon following the 'http'.
A grep of the database and codebase does not reveal any culprits (although it must be in there somewhere). Any idea what might cause the problem? The site domain settings all seem correct.
Here's the multisite config:
/* Multisite */
define('WP_ALLOW_MULTISITE', true);
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', true);
define('DOMAIN_CURRENT_SITE', '
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
define( 'SUNRISE', 'on' ); | The solution was in the multisite settings in the `wp_site` table.
The `domain` field entry was set (probably manually during a change of domain names) to `" It should not have included the protocol, but just be a bare domain.
Wordpress adds another `" to the start of the domain, and then runs it through a text filter, which strips out the second `":"`. What I ended up with was `"
As a result I could not use grep to find the 'typo' in the code of database as it was generated on the fly.
A simple fix, but a tough one to track down. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "login, password"
} |
HTML to WORDPRESS
I am very very new at this but would like to expand my creativity.
I would like to design/build my own wordpress. Because this is a huge task I have read that first designing the page with just html and css THEN bringing it into wordpress is a better a solution. Would you say this to be true? | Designing in plain 'ol HTML and CSS _could_ make easier. However, there are many features of the WordPress framework that you'll miss out on. Read some of the WP documentation in the Codex to begin with:
<
I will also draw your attention to the body class attribute, which I find extremely useful when designing my WordPress CSS.
<
Good Luck, and have fun! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "theme development, css, html, design"
} |
What is the simplest way to disable multisite leaving one of the sites only?
I developed different versions of a wordpress site using multisite. Now I need to use only the second version out of three, that is blog_id=2 which is also pointed to a mydomain.com/dir2.
What is the easiest way to disable multisite while leaving blog_id=2 pointing directly to mydomain.com | Use the default export plugin and use a new install, Single mode. Import the XML file and done. All other options have more todos and risk. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "multisite"
} |
What's an efficient way to change the post status of many posts at once?
I'm looking for an efficient way to change the post status on many posts at once. I have a custom post type that I'm using as a means to store content that must be approved by a moderator before being published. I'm trying to give the moderator the ability to "approve all" or "reject all" on a fairly large number of posts (100-200 would be common).
The best solution I've come up with is to make an ajax call that sends a list of post id's to the server, which loops through them calling the below function:
wp_update_post(array('ID'=> $post_id, 'post_status' => 'publish' ))
This results in a query to the DB for each post, however, and it's much slower than I'd like. Ideally, I'd be able to make a query that changes the post status to 'publish' on all of the post ID's in the list at once, but I can't find any means to do this. | What you are doing is the safe way, and the way I'd recommend. To my knowledge, there is no Core function to bulk update only single values in the `$wpdb->posts` table, so to do that you'd need to write your own SQL...
$ids = array(); // your IDs; I am assuming these to be validated and sanitized
$wpdb->query("UPDATE {$wpdb->posts} SET post_status = 'publish' WHERE ID IN (".implode(',',$ids)).")");
You might be able to do the same with `$wpdb->update` but I rarely use that method, so I am not sure. (A comment below indicates that it is not possible.) Check the Codex and play with it if you want.
**I would recommend not doing either** , though, and continuing to use `wp_update_post`. If you skip around the Core functions you also skip around numerous actions and filters, and may cause yourself unintended consequences or other frustrations later on. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, posts, plugin development"
} |
Change default upload images size for contributors
When a contributor uploads an image to a post, the default image size option is set to Medium. How can I change it to Large or Full? | The default image size for inserting images is stored in the options table in `image_default_size`. You can change the default image size by updating the option:
update_option( 'image_default_size', 'large' );
## Role-dependent default image size
To change the default image size for contributors only, you could hook into `pre_option_[option]` filter (which is fired directly after sanitizing the option name passed to `get_option`, giving you the possibility to change the value returned by `get_option`) and return another image size for contributors only:
function myplugin_contributor_image_default_size( $value ) {
if ( current_user_can( 'contributor' ) ) {
return 'large';
}
return $value;
}
add_filter( 'pre_option_image_default_size', 'myplugin_contributor_image_default_size' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions"
} |
Can't access login page after password reset
After completing the WordPress reset password procedure I try to login with the new password but I get an error saying:
'Authorization Required. This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.'
The password has been changed but I have to use a different browser in order to view the login page and be able to login. Once this happens I can't view the login page even after deleting all the cookies. If I repeat the same procedure on a different browser the same thing happens.
Does anybody know what may be the cause of this ?
Thank you | This could be down to a number of reasons:
a) The browser you're having problems with is saving the old password and refusing access. This is why the other browser works when logging in with the new password. Try and reset the saved password to see if this solves the issue.
b) Your hosting provider has implemented an extra layer of security to avoid WordPress websites being hacked. Contact your host for more information.
You may also want to consider reading the following article: <
I would have suggested this in the comments, but I don't have a high enough reputation.
Hope this helps :) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "login"
} |
tax_input argument for wp_insert_post()
I'm trying to insert custom taxonomies using `wp_insert_post()` and the `tax_input` argument, but it doesn't work. I want to set a post to a custom taxonomy ('types') and a category ('cars')
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'tax_input' => array('types' => array('cars')),
'post_status' => 'pending',
'post_type' => 'vehicles'
); | I find the answer. After building my arguments for wp_insert_post() function and passed it to a variable $pid i set the following line after that and everything works slightly.
wp_set_object_terms($pid, 'cars', 'types', true); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "wp insert post"
} |
The excerpt suffix won't go away
I want to show the post content until the more tag, or if there's no more tag than just first n words. Something really basic, right? Obviously I need to use `get_the_excerpt` function. But the problem is that this function is behaving strangely. It adds a suffix to the end, that nobody wants. And you can't remove it!
You could in the pas do this
But this no longer works, because Wordpress decided to give us even more bad time with this by changing `[...]` to something like `[…]`
Now you can't even `str_replace` or `rtrim` that `[…]`. Trust me I tried.
The solution from here works, but this only cuts text after n words. It ignores the more tag.
Another way would be to use `get_the_content`, but that just shows the full post content even if I select Summary in the Settings -> Reading.
So please, what am I missing here? | The excerpt has a maximum lenght of 55 words, so even if you try to cut your text at say 70 words, `the_excerpt()` will ignore that and only show 55 words.
To remove`[...]` from the read more tag, simply find `the_content()` and replace it with `the_content('',FALSE,'');`. You can also use `the_content('Read more...');` to display a text after the read more tag, in this case `Read more...`.
If you need to remove `[...]` from the excerpt, you can do this in your functions.php
function new_excerpt_more($more) {
global $post;
return '';
}
add_filter('excerpt_more', 'new_excerpt_more');
You can also add a custom text or link inside the `''` if you need something else to dispay | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "excerpt"
} |
Get attached media only
I am using wp_query to get uploaded medias. Everything is working fine, but wp_query will return the medias with no post attached. This is not what I wanted. How can I exclude the unattached media from the wp_query?
This is my query arguments look like:
$args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => -1,
);
$attachemnt = new WP_Query($args);
Is there any argument that can use for exclude the unattached media in wp_query class?
Thanks | All media (somewhat incorrectly) in the `$wpdb->posts` table will be "attachments" whether actually attached or not. "Attachments" that are actually attached will have a `post_parent` other than 0, so what you need are all of the attachments that have a 0 in the `post_parent` column, if I understand you.
$args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => -1,
'post_parent__not_in' = array(0)
);
$attachment = new WP_Query($args);
var_dump($attachment->posts); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "wp query, attachments, exclude"
} |
Producing a list of media library items categorized under a certain taxonomy item
I created a custom taxonomy called "Reference Type" which is used to categorize media library items. In the taxonomy.php page, I want to produce a list of all media library items that are categorized under "Reference Type". How would I go about doing this? | You can use a tax query for all "Reference Type" terms, which will retrieve all attachments that have at least one "Reference Type" term.
$rt_media = new WP_Query(
array(
'posts_per_page' => -1,
'post_type' => 'attachment',
'tax_query' => array(
array(
'taxonomy' => 'reference_type',
'terms' => get_terms(
'reference_type',
array(
'hide_empty' => false,
'fields' => 'ids',
)
)
)
)
)
);
while ( $rt_media->have_posts() ) : $rt_media->the_post(); ?>
<div class="item">
Use any template tags you want to output the list!
</div>
<?php endwhile ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, media library"
} |
Link posts to pages for breadcrumbs
Is there a way of linking custom post types to pages.
I am looking to create breadcrumbs for the posts.
The posts are summarised on individual pages e.g. golf, tennis, football etc..
So the Breadcrumb Structure inside the post will be:
Home / Tennis / "Post Title"
When clicking on Tennis - it should lead to the Tennis page I have created which summarises all tennis events. | You need to go and have a look at template hierarchy for custom post types. I believe your custom post type is tennis. So you would make a copy of your theme's `archive.php` template and call it `archive-tennis.php` You can now style that template to your liking.
Just remember, you don't need to add or change any specific code inside your new template to specify your CPT. Wordpress will exactly know it should use `archive-tennis.php` when the custom post type tennis is clicked | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, breadcrumb"
} |
Is it possible to add short code and html tag in Category Description?
I want to add a shortcode (like slider) and html tag like `<h2>-------- text -----</h2>`. Is that possible?
I have already tried but is not really working. Only normal text is showing, no short code or html tag even. Any idea how or not possible?
i want to use this for own theme. i have one product page. but many category (like 7) and each category will have different slideshow banner. and under there product picture and details. i don't want make each category page separately, i can show shortcode from category description then i can it will be work for me. my shortcode will be `[rev_slider slider]`
category page code
<?php if ( category_description() ) : ?>
<div class="catdes"><?php echo wpautop( term_description() ); ?></div>
<?php endif; ?>
function page
remove_filter( 'pre_term_description', 'wp_filter_kses' ); | For displaying shortcodes you can use `do_shortcode`
<?php echo do_shortcode( term_description() ); ?>
For HTML the filter should be enough (what you posted worked on my install).
remove_filter( 'pre_term_description', 'wp_filter_kses' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "categories"
} |
Fetching posts from wordpress function in ajax
I'm trying to fetch posts in ajax. Everything is working but It is showing only one post. Please check my code and tell me if something is wrong
function ag_get_posts() {
global $post;
$args = array(
'post_type' => 'post',
'posts_per_page' => 12,
'post_status' => 'publish',
);
query_posts( $args );
while ( have_posts() ) : the_post();
locate_template( 'post.php', TRUE, TRUE );
endwhile;
wp_reset_query();
exit;
}
add_action('wp_ajax_ag_get_posts', 'ag_get_posts');
**jQuery:**
var data = {
action: 'ag_get_posts',
};
jQuery.post(AjaxPath.ajaxurl, data, function(response) {
var result = $(response)
Content.html(result);
}); | If you read the documentation for `locate_template` you'll see the problem.
locate_template( $template_names, $load, $require_once );
> $require_once (boolean) (optional) If true, the template file will be loaded with the php require_once function. If false, the template file will be loaded with the php require function. This parameter has no effect if $load is false. Default: true
PHP won't load your template more than once because you've set `$require_once` to true.
A simpler API function for this purpose is `get_template_part`:
get_template_part( 'post' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop, jquery, ajax"
} |
Make page tab link to pdf
I'm sure this is ridiculously simple, and I'm just missing something very basic. I have a CV as a pdf. I'd like to have the tab that says CV open up that CV as a pdf. I do not want to embed it as a Google Doc or anything.
**EDIT:** Including link to my site. < I'd like the "CV" tab to bring up the pdf. | If you are talking about menus and your theme uses the Menu API, then upload the PDF to a publicly accessible server-- doesn't have to to be the one your site uses-- then
1. go to Appearance -> Menus,
2. Navigate to a menu, or create one
3. find the "Links" dialogue,
4. input the URL and the link text
5. Save | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "links, pdf"
} |
Adding a photo to each WP user
I found several plugins (like this one and this one) to get the ability to attach a picture to a WP user. But these plugins are not maintained any more.
Since there's apparently no plugin that does it today, is there an easy way to do it manually? | I use a plugin called Avatar Manager for that function. The author has also done a tutorial on how to write your own avatar manager plugin, but unfortunately it is also a bit outdated and doesn't work anymore. Although the plugin states it is compatible up to 3.6.1, it is still working in 3.8.1. I know at this stage the plugin is maintained as I just recently submitted the Afrikaans translations to the author, and that was included in the last version released.
Images are uploaded via the users profile page if "Anyone can upload" feature is enabled by admin. Images are stored the exact same way as any image uploaded via the media uploader, and images are shown in the the Media section in the back end. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "users, thumbnails"
} |
Custom Template for more than 1 Tag
Wordpress let me create custom tag templates, i have lots of tags, and i want to display the post tagged with some tags with a template, and the post tagged with other tags with another template. !enter image description here
As this image shows the template hierarchy let me create the tag template easily, giving to the page the name or the id of the tag. But i want to create 1 template tag for a great number of tags (instead of making 1 template for every different tag), and another template tag for the remaining one. | Here's an example that "abuses" the tag description field to store a template name for the tag. We use the `tag_template` filter to get the tag description if it exists and include a template file with the description as part of the name. You could extend this to whitelist specific template names so typos don't result in trying to load a file that doesn't exist:
function wpd_tag_template( $templates = '' ){
$tag = get_queried_object();
if( !empty( $tag->description ) ){
$templates = locate_template( 'custom-tag-' . $tag->description . '.php', false );
}
return $templates;
}
add_filter( 'tag_template', 'wpd_tag_template' );
So for example the description contains `template-1`, WordPress will load the file `custom-tag-template-1.php` for this tag. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development"
} |
Change Wordpress Shortcode added in to post
Problem: I am using a plugin that turns the wordpress gallery into a cool slide show.
How ever, every time I make a gallery - Wordpress add this code to the post .
[gallery ids="334,332"]
I need it to be this -
[wp-slideshow include="334,332"]
* * *
Might be helpful: I think this is the file controlling the output?
< | ` remove_shortcode( 'gallery' ); add_shortcode( 'gallery', function( $atts ) { $atts = shortcode_atts( array( 'ids' => '' ), $atts ); return do_shortcode( "[wp-slideshow include=\"$atts[ids]\"]" ); } ); `
This may be better than replacing the gallery shortcode as if you decide to change plugin you will have the standard gallery shortcode which many plugins will work with directly. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "shortcode, gallery"
} |
Apply code for all else first block
I have this code for sidebar in Wordpress :-
register_sidebar(array(
'name' => 'Main sidebar',
'description' => 'main sidebar.',
'before_widget' => '<div id="blocks" class="siderbar box_outer %2$s" style="visibility: hidden;"><div class="widget">',
'after_widget' => '</div></div>',
'before_title' => '<h3 class="widget_title">',
'after_title' => '</h3><div class="wid_border"></div>'
));
In this cod will add every widget attribute `style="visibility: hidden;"`, but i need to add this attribute for all widget else first widget.
How can do that by php or JQuery. | I believe that what you want to do would better be done with CSS rules in your stylesheet rather than with an embedded `style` tag that you dynamically manipulate with PHP.
Remove `style="visibility: hidden;"` from your `register_sidebar` argument and use something like the following instead (Proof of Concept):
<html>
<head>
<style>
.aclass { visibility:hidden }
.aclass:first-child { visibility:visible }
</style>
</head>
<body><?php
for ($i = 1; $i < 5; $i++) {
echo '<div class="aclass">'.$i.'</div>';
} ?>
<body>
</html>
That is purely to make the two necessary rules apparent. You can run that code to get a feel for things if you'd like. You will need to swap `aclass` for the class you need to target-- either `siderbar` or `box_outer` I presume. And you probably want to write the rules into your main stylesheet. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "widgets"
} |
Fontawesome icon vanishes in editor while switching text and visual mode
While switching between text editor mode or updating post fontawesome icon vanishes.Please do not refer to use any plugin.I think i tag is stripped by editor,how can I overcome this? My code in editor text mode
<span><i class="fa fa-user"></i></span>
or
<i class="fa fa-user"></i>
As long as I am in text mode everything is well but when I switch to visual mode all of my code gets vanish. | I think you should first enable i tags.Then you should enable class id or span whatever you like.To do so add this code.
function add_mce_markup( $initArray ) {
$ext = 'i[id|name|class|style]';
if ( isset( $initArray['extended_valid_elements'] ) ) {
$initArray['extended_valid_elements'] .= ',' . $ext;
} else {
$initArray['extended_valid_elements'] = $ext;
}
return $initArray;
}
add_filter( 'tiny_mce_before_init', 'add_mce_markup' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "tinymce"
} |
Category Page Template - Can't get category ID
I am creating a category template that uses WP_query to get posts from my custom post type...
<?php
$query = new WP_Query( array( 'post_type' => array( 'mycpt' ), 'posts_per_page' => 5 ) );
?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php the_title(); ?>
<?php endwhile; ?>
How do i get the category id for the current category type? I can get the category title with...
<?php single_cat_title( '', true ); ?>
But how do I get the ID? | On a category archive, the "queried object" will have what you need.
$cat = get_queried_object();
var_dump($cat->cat_ID);
You can access it by means of `get_query_var()`:
$cat = get_query_var('cat');
var_dump($cat);
You can also pull is straight from the `$wp_query` global:
var_dump($wp_query->query_vars['cat']);
All of these assume that you are actually on a proper category archive page and that nothing has clobbered or otherwise corrupted the main query. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories"
} |
Plugin not showing in dashboard
I've seen many other related questions, but all of them are resolved with just adding the name format at the top of the plugin main PHP file, and/or manually downloading and extracting the plugin, but none of those answers worked for me.
I'm talking about the Wordpress Users Plugin. After downloading and extracting it in `wp-content/plugins/` directory, I can't find it in the dashboard list.
I've checked that the main file (`wp-users.php`) is placed at the main path, and it starts with the plugin name:
<?php
/*
Plugin Name: WordPress Users
Plugin URI:
...
I'm confused about what can be happening. Any idea? | If the plugin headers are correct, then the only option that comes to my mind is that the owner and permissions of the plugin file or its directory (if it is in one) are incorrect and WordPress cannot read the plugin file. Other than simply being logically important, if you check the source you can see that the Core specifically checks whether the plugin files are readable.
See the following for the appropriate settings: <
< < | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 5,
"tags": "plugins"
} |
White text on white background in TinyMCE when wp_editor is called in WP 3.9
One of the features of my plugin is to add a TinyMCE editor instance inside a meta box on the Edit Post screen. This has worked great up until 3.9 and I'm not clear as to what's going wrong.
Here are the relevant files containing the code for the meta box editor (links to files inside Github commit):
* admin/author-customization-admin.php
* admin/assets/js/edit-post.js
What am I missing? This is what I'm given when I load the Edit Post screen:
![
The contents are there though, which you can see when you highlight inside the textarea:
![
On WordPress 3.8.1 the code works just fine:
![
I'm not sure whether it's an issue with the PHP code or the JavaScript. Any help is appreciated. | The text goes white when the `id` attribute (`$editor_id`) contains `[]`. They are not allowed here.
Make sure the second argument for `wp_editor` does not contain `[]`, and the text becomes visible again. I have reported that regression with a test case on ticket #26778.
To use brackets in the `name` attribute, use `textarea_name` in the `settings` parameter.
### Example
$editor_id = 'my_editor_1';
$editor_name = 'my_editor[1]';
$settings = array (
'tabindex' => FALSE,
'editor_height' => 150,
'resize' => TRUE,
'textarea_name' => $editor_name
);
wp_editor( $post->post_content, $editor_id, $settings ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "plugins, php, javascript, tinymce"
} |
Login problem after installing my written plugin
I have create a simple widget plugin, it's so simple and it make no changes in cookie setting, also it work great in my local site , but in the host i have a problem after activate this plugin and try to login the WordPress again, it says:
> ERROR: Cookies are blocked or not supported by your browser.
or a whitepage show after logging in, and dashboard do not appear.
after deactivating the plugin every thing will work correctly!
what is the problem? is there any thing that i must add to my plugin for setting an special cookie? | finally I have found the answer, the answer is in this link:
How To Fix The WordPress White Screen of Death (Theme/Plugin Error)
the answer is too odd! that was happened because new line character(enter) between close and open tag of php...like this: !in the line 11 you can see an example
in the line 11 you can see an example, when it have been delete every thing have been right! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, login, dashboard"
} |
Hide specific parent categories from post edit
I have many custom post types and they all take advantage of wordpress categories. I therefore have several parent categories for each custom post type. Is there a way to hide the other parent categories when editing a certain custom post type?
In this screenshot for example I'd only like "Download Categories" to show while I'm in my custom post type "downloads".
!enter image description here | Probably you're making a wrong use of taxonomies. Instead of using only the _Categories_ taxonomy, you should create several **Custom Taxonomies**.
I mean _Blog Categories_ , _Download Categories_ , _Team Departments_ , etc... should be different taxonomies, and you should assing each of these taxonomies to the custom post type(s) they're related to...
Check the function **register_taxonomy()** for further information.
This is a very simple example:
function register_download_category() {
register_taxonomy(
'downloadcategory',
'downloads',
array(
'label' => 'Download Categories',
'rewrite' => array( 'slug' => 'downloadcategory' ),
)
);
}
add_action( 'init', 'register_download_category' );
In order to make queries by custom taxonomies you have to use the **WP_Query Taxonomy Parameters**. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, taxonomy"
} |
How to know if user choose to show full post or excerpt?
I've seen there is a setting to choose whether to see full posts or excerpts on feed. However I'm using a theme that doesn't seem to support this functionality (it always show the full post). For this reason I created a child theme and would like to know what function to use to check what the user chose from preferences. e.g:
<?php if ( did_the_user_choose_excerpts() ) : ?>
<div class="entry-summary">
<?php the_excerpt(); ?>
</div><!-- .entry-summary -->
<?php else : ?>
// Full post
How do I check if the user chose to see excerpts? | !Show summary or full textx for feeds
That option refers to show excerpt on rss/atom feeds, not to normal frontend archives.
You can get that value using
get_option( 'rss_use_excerpt' );
That is **1** if user choose "Summary", **0** if user choose "Full text". | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "themes, content"
} |
https and wordpress breaks posts
I have a wordpress http site which still works just fine. I added https and the first page works but none of the post pages do.
server: Ubuntu 10.04.4 LTS (lucid) running Apache 2.2.14 SSL through RapidSSL
** EDIT **
Here's the 404 I see instead of a post (make note, on the exact url but with `https` I'm able to see my content)
* * *
**Not Found**
The requested URL /shortcuts/ was not found on this server.
_Apache/2.2.14 (Ubuntu) Server at www.mydomain.com Port 443_
* * * | My best educated guess is to perform a checklist on the following:
* Take a look at the virtual host configuration files for your domains, if you have access to them. Ensure that they agree with the corresponding WordPress installations on your machine(s).
* If your Virtual Host configurations are written correctly and as intended, then the next step is to check if your websites work with "Pretty Links" disabled. If they do, then we know for a fact that WordPress is probably configured incorrectly for using SSL, and that the URL Rewriting settings need to be changed for WordPress. The easiest way to do that is through the use of this plugin:
* WordPress HTTPS
Potential Resources:
* Apache 2.2 Manual - Virtual Host Example Configurations
* Administration Over SSL
* Blog Tutorial - How to Secure WordPress with SSL using a Plugin
* WordPress HTTPS - A Simple Tutorial | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, apache, ssl, https, linux"
} |
Remote database -> massive response time increase?
I have nginx web server running newest WordPress and DB server running MySQL 5.6 There is around 90-100ms latency(round-trip delay) between those 2 servers.
The problem is that It takes about 5000 ms to get response from my web-server if I access DB remotely.(The connection is encrypted by SSL)
In comparison it takes about 200 ms if I access MySQL locally(web-server & MySQL installed on one single machine).
1\. Why is that ? Is it because WP has multiple MySQL queries per page and waits for each and every one to complete ? Therefore it adds up : 100+100+100+100..=5000ms ?
2\. Can WP be modified to request from MySQL asynchronously, in order to reduce waiting time for request to be successful?
Thank you. :) | Yes
90-100ms round trip + time to prepare SQL statement + time to execute statement + time to send results back multiplied by the number of times you need to query the database.
Sure the connection may stay open but it's an inherently expensive thing to do.
Considering that some setups can respond in full in less than 100ms never mind the database connection, you should look into co-locating your database and your server, if not on to the same machine but somewhere very very close.
WordPress specific things that may help include:
* Object caches
* Database query caching
* fewer SQL queries
* Use of transients to store the results of expensive operations
You can see what SQL queries are made and slow queries using tools such as the query monitor plugin | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database, mysql, remote"
} |
meta_compare not comparing whole integer
I have submitted an integer data via a form to my custom search page. I can get values properly if the input is single char (e.g. 1 ) but if the input is multi char (e.g. 100) it still compares against "1".
IF the user input is **1** I get all the posts with custom field value **More than 1**. but If the input is **100** the result is same.
_Why is this happening??_
Here is my code::
$i_rate = $_GET["interest_rate"];
$bc_args = array(
'post_type' => 'data',
'data-category'=>'insurance-rate',
'order' => 'DESC',
'meta_key' => 'interest_rate',
'meta_value' =>$i_rate,
'meta_compare' => '>=',
'orderby' => 'meta_value_num',
);
$sortedPosts = new WP_Query($bc_args); | You could try this instead:
$bc_args = array(
'post_type' => 'data',
'data-category' =>'insurance-rate',
'order' => 'DESC',
'orderby' => 'meta_value_num',
'meta_query' => array(
array(
'key' => 'interest_rate',
'value' => (int) $i_rate,
'type' => 'numeric',
'compare' => '>='
),
)
);
$sortedPosts = new WP_Query( $bc_args );
where we use the _numeric_ `type`.
You should also consider using `filter_input` instead of `$_GET`:
$i_rate = filter_input( INPUT_GET, 'i_rate', FILTER_SANITIZE_NUMBER_INT );
or the native `add_query_var / get_query_var` way.
_Ps:_ `data-category` is not a native parameter in the `WP_Query()` class. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 0,
"tags": "wp query, custom field, meta query"
} |
Hide comments and posts posted by other user
I've created a user with role Contributor, when i logged in as Contributor all the posts and comments are listed in the dashboard. How to disable this? I just want to see the post made by me/specific_user. How to do this? | You can use a filter to pre_get_posts so that only your posts are listed. Something like this:
function my_posts_only( $query ) {
global $pagenow;
if ( 'edit.php' != $pagenow || ! $query->is_admin )
return $query;
if ( ! current_user_can( 'manage_options' ) ) {
global $user_ID;
$query->set( 'author', $user_ID );
}
return $query;
}
add_filter( 'pre_get_posts', 'my_posts_only' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, comments, users, user roles"
} |
how to display a page before the home page
I want to build a wordpress theme in which there is a landing page made by an image and a logo; when the logo is clicked the theme have to go to another page in which there is the navigation bar and other stuff.
Thus, the sequence is this:
1. Landing page (image and logo);
2. Home page (navigation bar, etc..)
My initial idea is to use the `front-page.php` and the `home.php`; is it right?
Thanks! | After some research I came to conclusion that this splash screen will destroy the website SEO and the usability, so I have decided not to add this kind of page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, customization"
} |
WordPress object for comments frame
For two days I have tried to make this code work. I want to add a comment frame in `single.php`. I got this code to put it in the single page's template:
<script type="text/javascript" charset="utf-8">
initFrame({ app_id: 'xxx' ,
object_id: 'ARTICLE_ID' ,
object_title: 'ARTICLE_TITLE' ,
object_content: 'ARTICLE_CONTENT' ,
object_url: 'ARTICLE_URL' ,
arguments_container: 'comment' ,
width: '610' })
</script>
and they said: Replace strings with some logic:
* ARTICLE_ID: id of the article in your website.
* ARTICLE_TITLE: title of the article
* ARTICLE_CONTENT: body content of the article
* ARTICLE_URL: the url to the article
* DIV_ID: the div id where Naqeshny arguments box appears
The question is: what should I write in ARTICLE_ID, ARTICLE_TITLE, etc. to change in every topic I write on my website? | So long as you're in the loop, you can just use the standard template tags:
<script type="text/javascript" charset="utf8">
initFrame({
app_id: "",
object_id: <?php the_ID() ?>,
object_title: "<?php the_title_attribute() ?>",
object_content: '<?php echo wp_trim_words( strip_shortcodes( striptags( get_the_content() ) ), 45 ) ?>',
object_url: "<?php the_permalink() ?>",
arguments_container: "comment-naqeshny",
width: 610
});
</script> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "single, terms"
} |
show previous/next post orderer by title in custom post types
What's a working method to show link to next and previous same custom post type article, ordered by title and not id? (generally applying a filter to the order) | If you use a filter like the following to adjust the order of a post type archive, then the next & previous links will work perfectly without need for modification:
function wpse_139866_set_order_by( $wp_query ) {
if ( ! is_admin() && $wp_query->is_post_type_archive( 'my_post_type' ) && $wp_query->is_main_query() ) {
$wp_query->set( 'orderby', 'title' );
}
}
add_action( 'pre_get_posts', 'wpse_139866_set_order_by' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, order, next post link, previous post link"
} |
How to display the featured image of a parent on child pages?
I was searching how I can get the featured images of the parent also on the child pages, without uploading it also for the childs.
How can this solve? | You can use `get_the_post_thumbnail()` and pass the ID of the parent instead:
if ( $post->post_parent )
$post_id = $post->post_parent;
else
$post_id = $post->ID;
if ( $thumbnail = get_the_post_thumbnail( $post_id, 'post-thumbnail' ) ) {
echo $thumbnail;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "featured post"
} |
Post Fetching Ignoring Sort_Column?
I am using the code below subpages for my portfolio. For some reason, it seems to be ignoring the ordering I have set on my pages. Any help?
<?php
$args = array(
'post_type' => 'page',
'sort_column' => 'menu_order',
'post_status' => 'publish',
'posts_per_page' => -1,
'post_parent' => $post->ID,
);
$query = new WP_Query($args);
while ($query->have_posts()) {
$query->the_post(); ?> | I'm not sure why you use the `sort_column` parameter, it's not supported by the `WP_Query()` class. According to the Codex, the correct way to sort, is to use the `order` and `orderby` parameters.
Please try this:
$args = array(
'post_type' => 'page',
'orderby' => 'menu_order',
'order' => 'ASC', // DESC is the default order
'post_status' => 'publish',
'posts_per_page' => -1,
'post_parent' => $post->ID,
);
$query = new WP_Query( $args ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "pages, wp list pages"
} |
Multi-image upload doesn't work
I just installed Gravity Forms 1.8 and made a form with a multi-upload field.
The field shows up alright, but the field just, doesn't works. Clicking the Select Files does nothing, and dragging files in the zone only opens the file in my browser.
There is no errors in the console of Chrome and Firefox
What could prevent the field from working? | The most common cause of the multi-file upload field failing to function is the scripts being included down in the footer when they should be up in the header. This usually happens when using the function call to embed the form, there is a second function call you also need to use to ensure the scripts are included correctly: <
Gravity Forms 1.5 introduced the gravity_form_enqueue_scripts() function which allows you to easily enqueue the necessary Gravity Forms' scripts and styles when manually embedding a form. This is also useful if you are using a GF widget and do not wish for the styles and scripts to be loaded inline. < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin gravity forms"
} |
Why doesn't this code add a table to my database?
To get to the point, I'm trying to add a database table upon installation of my plugin. Here's my code:
global $scimp_db_version;
$scimp_db_version = "1.0";
function scimp_install () {
global $wpdb;
$table_name = $wpdb->prefix . "scimp";
$sql = "CREATE TABLE $table_name (
id int NOT NULL AUTO_INCREMENT,
feedurl text NOT NULL,
category text NOT NULL,
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
add_option("scimp_db_version", $scimp_db_version);
}
register_activation_hook( __FILE__, 'scimp_install' )
Needless to say, this isn't working. The table isn't being created. I'm hoping that there's just something simple that I'm missing after looking at it too long. Can anyone see anything wrong here? | A key must be defined for a table by using a single column, or multiple. So on your code, you need to a line to the sql `KEY id (id)` -
$sql = "CREATE TABLE $table_name (
id int NOT NULL AUTO_INCREMENT,
feedurl text NOT NULL,
category text NOT NULL,
KEY id (id)
);"; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "mysql"
} |
Make A WordPress Page Accessible To Admins Only, Redirect Other User Roles
I need to redirect **logged-in** and **non-admin** users, from page with id 172, to the home of the website. Note that users that are not logged in can actually see the page.
add_action('admin_init', 'xyz');
function xyz() {
if( is_page( 172 ) ) {
if( is_user_logged_in() && ! current_user_can('update_core') ) {
wp_redirect( home_url() );
exit;
}
}
}
Problem: This code is not working. | `admin_init` runs on admin pages, not the front end. The equivalent front end action, `init`, is too early to check `is_page`. A safe action for redirection is `template_redirect`:
function xyz() {
if( is_page( 172 )
&& ! current_user_can('update_core') ) {
wp_redirect( home_url() );
exit;
}
}
add_action( 'template_redirect', 'xyz' ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "admin, redirect, user roles, user access"
} |
Is there an admin hook that will let me read GET variable before it's too late to set the header Location
I need to redirect the page based on the query vars in my plugin admin menu. I don't know where I can hook in to read the query vars or the GET vars order to decide if the page needs to be redirected. | You can check the `$current_screen` on the `current_screen` action, and redirect after checking some GET conditions:
function wpd_current_screen( $current_screen ) {
if ( 'toplevel_page_your_menu_item_id' == $current_screen->base ) {
// check some condition and
wp_redirect( admin_url() );
exit;
}
}
add_action( 'current_screen', 'wpd_current_screen' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, hooks"
} |
Directly using pure JWPlayer JS (but NOT WP Plugin)
First of all, I'm not using WP JWPlayer Plugin. (And i don't want it. And thats the another story)
* * *
Well in the Template file:
wp_register_script('myJW', get_bloginfo('template_url') . '/jwplayer.js');
wp_enqueue_script('myJW');
?>
<div id='myJWPlayer'></div>
<script>
jQuery(document).ready(function(){
jwplayer("myJWPlayer").setup({
playlist: "
listbar: {
position: 'right',
size: 250
},
width: 700,
height: 400
});
});
</script>
It is not working, since **even** the `jwplayer("myJWPlayer")` call is **not** being triggered.
* * *
**Note: This codes are perfectly working in pure HTML sites.**
Any idea please? | You need to properly enqueue your script. You should hook your script to the
function enqueue_custom_script() {
wp_register_script('myJW', get_bloginfo('template_url') . '/jwplayer.js');
wp_enqueue_script('myJW');
}
add_action( 'wp_enqueue_scripts', 'enqueue_custom_script' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "templates, javascript, jwplayer"
} |
Unable to get to the admin panel
I am using WordPress on one of the sites. I admit that I have been blitheringly idiotic not testing on a dev server, but I updated all the plugins today. They were akismet, custom login and wp security.
Now the problem is that I am unable to get to the wordpress login panel. I had changed the login url using one of the plugins custom login or wp security or both, I am sure I don't remember. The login page url sends me to the not found page.
I have already tried disabling all the plugins from the database by applying `a:0:{}` in active_plugins in the options table on the wordpress database. | I have found the solution.
After searching the whole of the WordPress database, I got the "divine" inspiration to check out the .htaccess file. The custom-login script had modified the file. I just removed the line `RewriteRule ^.*wp-admin/?|^.*wp-login\.php /not_found [R,L]` and everything started working again. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "admin, login"
} |
Remove the word 'Categories' from wp_list_categories
I've got the following code: `wp_list_categories();`
It outputs all my categories, however, it makes them the child of a list element, called `CATEGORIES`.
So, I get an unordered list, like so:
CATEGORIES
* FASHION
* DAILY FASHION CANDY
* TRENDS
* BEAUTY
* ACCESSORIES
* CELEBRITIES
* LIFESTYLE
However, I only need:
* FASHION
* DAILY FASHION CANDY
* TRENDS
* BEAUTY
* ACCESSORIES
* CELEBRITIES
* LIFESTYLE
I'm sure I could remove/hide the word `CATEGORIES` with JS or CSS, but is there a way to prevent it being there in the first place? | Take a look at the parameters in the documentation of **wp_list_categories()** function.
You need to use this parameter:
> ### title_li
>
>
> _(string)_ Set the title and style of the outer list item. Defaults to "Categories". If present but empty, the outer list item will not be displayed. See below for **examples**.
I think it's clear, you just need to pass this parameter as an empty string:
wp_list_categories('title_li='); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 6,
"tags": "theme development"
} |
Exclude Current and Sticky Post
On a single Post page I have a side bar displaying up to three other, related posts. How can I exclude both Sticky Posts and the Current post?
I know how to exclude the Current post and how to exclude Sticky Posts by using post_not_in in a WP_Query, see code example below. But I guess you can not use post_not_in twice in the same query. Any suggestions?
$current_post_ID = get_the_ID();
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'order' => 'DESC',
'orderby' => 'date',
'posts_per_page' => 3,
'post__not_in' => get_option( 'sticky_posts' )
'post__not_in' => array($current_post_ID)
); | Whenever an array of arguments is a function parameter in a WP core function it is parsed via `wp_parse_args` and almost always extracted into single variables.
I.e. _no, you cannot use the same argument twice_.
What you want to do is something like this:
$exclude = get_option( 'sticky_posts' );
$exclude[] = get_the_ID();
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'order' => 'DESC',
'orderby' => 'date',
'posts_per_page' => 3,
'post__not_in' => $exclude
);
As an aside, you were also missing a comma. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "sticky post"
} |
When using wp_enqueue_script(); in a theme why don't we use add_action?
When using `wp_enqueue_script` in a plugin, I have always been told to use an `add_action` :
function add_my_css_and_my_js_files(){
wp_enqueue_script('jquery-validate-min', plugins_url('jquery_validate_min.js', __FILE__ )
}
add_action('wp_enqueue_scripts', "add_my_css_and_my_js_files");
How come this is **not** required if you put wp_enqueue_script in the theme:
wp_enqueue_script('jquery-validate-min', plugins_url('jquery_validate_min.js', | It is required, actually.
There's no real difference between themes and plugins as such. Neither of them should take actions on merely being loaded, they should use action hooks on functions to have things happen in the correct ordering. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, theme development, wp enqueue script"
} |
Transition Post status not working
I have a plugin which uses the `transition_post_status` hook, to fire a custom function on post update. But I don't know why its not working. Here is the code
add_action('transition_post_status', 'pmc_update_notification',10,3);
function pmc_update_notification($new_status, $old_status, $post) {
echo 'function checkpoint 1';
$options = get_option('pmc_setting');
if($options['snpi'] != false && is_single()){
if ( $old_status == 'publish' && $new_status == 'publish' ) {
echo 'function checkpoint 2';
$post_title = get_the_title($post);
$post_url = get_permalink($post);
$message = __('Post updated','pmc').":\n";
$message .= $post_title . ": " . $post_url;
// Send notification
pmc_send($message);
}
}
} | Found the problem!
It was the `is_single()` line. It's not working because its outside the loop. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, hooks"
} |
Custom content before post content
I am using this code to insert custom content after title and before content. How can i limit it to only "post" not pages and custom post types.
function theme_slug_filter_the_content( $content ) {
$custom_content = 'YOUR CONTENT GOES HERE';
$custom_content .= $content;
return $custom_content;} add_filter( 'the_content', 'theme_slug_filter_the_content' ); | You can check the post type of the current post via `get_post_type`:
function theme_slug_filter_the_content( $content ) {
if( 'post' == get_post_type() ){
$custom_content = 'YOUR CONTENT GOES HERE';
return $custom_content . $content;
}
return $content;
}
add_filter( 'the_content', 'theme_slug_filter_the_content' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop, content restriction, post content"
} |
Hook only specific post type
with this function I change the title of my posts in the posts type 'alternatives'. My problem is that Wordpress changes all my titles now. Does anyone know how I can set this for the specific custom post type only?
// Change alternatives title
function alternatives_title( $title, $post_id ) {
if( get_post_type( $post_id ) == 'alternatives' ) {
$title = $title . ' alternative';
}
return $title;
}
add_filter( 'the_title', 'alternatives_title' );
add_filter( 'get_the_title', 'alternatives_title' ); | You need to set the number of arguments your filter accepts:
add_filter( 'the_title', 'alternatives_title', 10 /* Priority */, 2 /* Arguments */ );
And you only need to use `the_title` (there is no `get_the_title` filter). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, posts, filters, hooks"
} |
Can't update WP Editor after Ajax
I want to update the WP Editor textarea after Ajax, but it does not work.
I have the following in my Ajax success function:
$('input#pn').val(response.name);
$('select').val( response.category_name );
$('textarea#pd').val(response.description);
$('textarea#ld').val(response.long_description);
`ld` is the id of the `wp_editor` textarea.
The first three work but the fourth one is `wp_editor`. | Replace:
$('textarea#ld').val(response.long_description);
With:
tinyMCE.get('ld').setContent(response.long_description); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "ajax, wp editor"
} |
Category based on post id
I have the following:
$custom_loop = new WP_Query( array('category_name'=>$category, 'meta_key'=>'name', 'orderby' => 'meta_value', 'order' => 'ASC', 'posts_per_page'=>'-1'));
How can I tell it that if `$post->ID == 1` then `$category == 'first'` and if `$post->ID == 2` then `$category == 'second'`
I suppose it should be an array of some sort, but I just can't figure out what? | `WP_Query` itself can't do that logic internally but you can easily create the query dynamically.
$args = array(
'meta_key' => 'name',
'orderby' => 'meta_value',
'order' => 'ASC',
'posts_per_page' => '-1'
);
if ($post->ID == 1) {
$args['category_name'] = 'first';
} elseif ($post->ID == 2) {
$args['category_name'] = 'second';
}
$custom_loop = new WP_Query($args); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, array"
} |
How to give the same error message when the wrong password or wrong username is used?
For security reasons, my WordPress instance should give the same error message when an incorrect password or wrong username is used. How can it be done? | You can use `login_errors` filter for changing the custom error message
Please have a look at
Change login error messages | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "security"
} |
What is the correct way to write this conditional statement?
I'd like to remove auto formatting 'wpautop' from specific pages. Here is what I've got, but it doesn't appear to work:
if ( is_page ( 'services' ) ) {
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
};
I am quite new to php, I have done some research to see how to write this statement, but I have had trouble finding an example that addresses my need. What would be the correct way to write this conditional statement? | You need to add your function in the `template_redirect` hook. You need to first wait for wordpress to finish loading pages before you can add your hook to remove `wpautop`, otherwise your hook will simply get run over. So your funtion will look like this
function pietergoosen_remove_wpautop() {
if ( is_page ( 'services' ) ) {
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
}
}
add_action( 'template_redirect', 'pietergoosen_remove_wpautop' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, conditional content"
} |
How do I change the text: Click on Event Name for description/registration
I am running Event Registration for the first time on a WP site and would like to be able to edit the phrase that shows up at the beginning of the Event Registration page:
> Click on Event Name for description/registration
I have searched all the templates but I can't find where that is located. Any assistance in finding that would be appreciated.
Thanks. | You didn't provide a link to the plugin but I guess you mean this one.
I wonder if you mean:
* line #20 in the file `/public/evr_public-show_event_list.php`:
echo '<caption>'.__('Click on Event Name for description/registration','evr_language').'</caption>';
* line #338 in the file `evr_content.php`:
<b>Click on Event Name for description/registration</b>
You could use the `gettext` filter to change the former, but you should report the latter one to the plugin author and ask for a proper localization of that text. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
Get first post from wp_query
How can I get the first post from a WP_Query result?
$connected = new WP_Query( array(
// Arguments
));
// This doesn't work..
echo $connected[0]->post_name; | If you poke through `WP_Query` the set of queried posts is saved into `posts` property and current post gets assigned to `post` one (each time loop iterates).
So you could do `$connected->posts[0]` if you need to just fetch that, but it might be more convenient to do `$connected->the_post();` then `$connected->post` if you need to skip first one and process the rest in normal loop. | stackexchange-wordpress | {
"answer_score": 19,
"question_score": 7,
"tags": "posts, wp query, loop"
} |
I want to select the from values from database in WordPress?
Here is my code:
$sql = 'SELECT * FROM ' . $wpdb->base_prefix . 'item WHERE uname = "'. $_POST['login_name'] . '" ';
$result = $wpdb->get_results($sql) or die(mysql_error());
foreach($result as $results) {
$results->salt;
$results->password;
}
echo $sal->$results[0];
echo $pwd->$results[1]; | Read the `wpdb` docs and don't forget to protect your query:
global $wpdb;
$table_name = $wpdb->prefix . "item";
$login_name = sanitize_user( $_POST['login_name'] ); //assuming you're dealing with username
$prepare = $wpdb->prepare( "SELECT * FROM $table_name WHERE uname = %s", $login_name );
$myrows = $wpdb->get_results( $prepare );
//output results
echo '<pre>' . print_r( $myrows, true ) . '</pre>'; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, mysql, wpdb"
} |
How to achieve certain page (url) accessible to certain users
I have created a download page I want it should be accessible to certain users who are logged in to my blog. No one else should have direct access to page. Is there some plugin for that?
I have searched a lot but not found any meeting this requirement. Moreover if this possible to create a custom log in page other than wp-admin?
I have tried the password protect option in WordPress visibility but that is not much useful. | You could create a simple page template with just five lines of code:
/* Template Name: Protected Page */
if ( ! is_user_logged_in() )
auth_redirect();
else
require_once './page.php';
Then select that template for the page you want to protect.
`auth_redirect()` will send the user to the login page and back to the original URL after they are logged in. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, user roles"
} |
XML Sitemap : broken XML file
I use WP SEO by Yoast to generate sitemaps and the sitemap generated for custom types has a short hexa string at the beginning that invalidate the whole XML file :
148e2
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="//cabouge.tv5monde.com/main-sitemap.xsl"?>
<urlset xmlns:xsi=" xmlns:image=" xsi:schemaLocation=" xmlns="
~~You can see the live file here~~ (problem solved on the live file).
The characters at the beginning of the files seams to be linked to the content, because they are different for another custom type.
I use WPSEO v1.5.2.5, but the bug was present with version 1.4.6. It seams to be linked to my server configuration, because I cannot reproduce it on a testing server with the same Wordpress code installed on it. The production server runs PHP 5.3.8.
I tried to disable all other plugins, but the issue is still present.
Any idea about where I could find the issue ? | This seams to be an issue with the `header('HTTP/1.1 200 OK')` function call in Yoast's Wordpress SEO plugin that is not compatible with my server configuration (Nginx with some security config in front, then apache for php processing).
In some way I do not fully understand, this php function call was forcing the server to send an HTTP/1.1 header with a HTTP/1.0 encoded body, so the end of the response header was interpreted as the beginning of the body.
Checkout the issue I have created on wordpress-seo github repo for more information. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "plugin wp seo yoast"
} |
Query custom post type only if it contains another custom post type
I currently have a custom post type named "blog". On registration, every user gets automatically a post "blog" linked with their user ID.
This custom post type queries another post type named "articles". Those articles are written by the user and then showed in their "blog" custom post type.
Now, I would like to show a list of X most recent "blog" custom post type but only if they have at least one "article" in it but I can not find any way to do it...
Thank you in advance for your help and have a good day. | I finally found a workaround for this, here it goes :
I used "get_user" with a "has_custom_post_type" function to query every user with at least one article written and then added the link to their blog CPT by adding "/blog/display_name" in the href.
Here goes the code
<?php
$blog_url = get_bloginfo('home');
$users_number = 0;
$blogusers = get_users('orderby=registered&order=DESC');
foreach ($blogusers as $user) {
$cpt_count = has_custom_post_type( $user->ID, 'article' );
if (!empty($cpt_count) ) {
$users_number ++;
if ($users_number <= 5) {
echo '<li><a href="' . $blog_url . '/blog/' . $user->user_nicename . '">Le blog de ' . $user->display_name . '</a></li>';
}
}
}
?>
Thanks to everyone for your help. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, query"
} |
Read More link scrolling page
I'm creating a theme, and I want to prevent the page from being scrolled when a user clicks 'Read More' and the code given in the Wordpress Codex is not helping me at all.
My `functions.php` is exactly the same as the snippet in the Codex and the relevant line of my `index.php` is:
`<div class="content"><p><?php the_content(__('Read More')); ?></p></div>`
Edit: I have a new, weird bug: the content of the Codex snippet is being shown as raw HTML in my blog and admin pages. | There is an explanation in the WordPress Codex which I copy here for reference.
**Don't forget`<?php` and `?>`**
<?php
function remove_more_link_scroll( $link ) {
$link = preg_replace( '|#more-[0-9]+|', '', $link );
return $link;
}
add_filter( 'the_content_more_link', 'remove_more_link_scroll' );
?>
Prevent Page Scroll When Clicking the More Link | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "read more"
} |
Custom Field Search
I'm trying to create a custom search form that searches a custom post type that I have created.
The form would need to search two custom taxonomies (similar to tags and categories) and the body text of the post.
There would be a search input that would search the body text and tags and a dropdown that would filter by category (Any, Category 1, Category 2, Category 3).
What kind of templates would I need to make and what kind of code would this require?
Thanks a ton! | Use pre_get_posts to filter search results:
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', 'custom_post_type_name');
$query->set('cat', intval($_POST['cat']); // assuming you have a select with categories with name "cat"
}
}
}
add_action('pre_get_posts','search_filter'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "custom post types, custom taxonomy, search"
} |
Copy a user from one WordPress site to another
Is it possible to copy a user from one WordPress site to another?
I copied the record from the `user` table and all the related records from the `usermeta` table (12 records by default) but I think something else is needed. I get this message upon login: `You do not have sufficient permissions to access this page.`
The reason I need this is I have 4 users I'd like to grant access to on a new site but use their credentials from the current site. | You need to make sure the new ID of the user in the user table matches the foreign key in the usermeta.
Also a word of caution regarding your comment on Active Directory integration. For public facing websites be extremely careful, you could inadvertantly expose you domain controller information to the web. You might want to consider additional security precautions around the login and admin pages, for example limiting access to certain IP addresses or dual authentication. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "users, user registration, user access"
} |
Check is_single() outside loop
How can I check if an Id `is_single()` outside the loop in a plugin?
When I try it I always get a fatal error The code
add_action('transition_post_status', 'pmc_update_notification',10,3);
function pmc_update_notification($new_status, $old_status, $post) {
if ( $old_status == 'publish' && $new_status == 'publish' ) {
$post_id = get_the_ID($post);
if (is_single($post_id)){
$post_title = get_the_title($post);
$post_url = get_permalink($post);
$message = __('Post updated','pmc').":\n";
$message .= $post_title . ": " . $post_url;
// Send notification
pmc_send($message);
}
}
} | In your example, you can't.
Per the Codex,
> [`is_single()`] checks if a single post of any post type except attachment and page post types is being displayed.
You're trying to use it on the `transition_post_status` hook, which is not related to page display, and so `is_single()` has no meaning.
### The Solution
Instead of using `is_single()`, use `get_post_type()`:
if( 'post' == get_post_type( $post ) ) {
// code goes here
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "posts"
} |
Is jQuery included in WordPress by default?
When I downloaded the latest version 3.8.1, inside `wp-include/js` there is a jQuery folder.
Can I assume that WordPress will always include it, meaning I don't have to make my own call? E.g.
wp_register_script('jquery', ' array(), null, false);
wp_enqueue_script('jquery'); | Yes, jQuery is part of WordPress core. But--it can become outdated, because jQuery updates can happen in between WP releases. The recent release of WordPress does use a very recent version of jQuery.
By default,
wp_enqueue_script('jquery')
grabs jQuery from the core at /wp-includes/js/jquery/jquery.js.
The "correct" way to add jQuery to your WP site is:
function theme_scripts() {
wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'theme_scripts');
Another catch--if you _do_ use the latest jQuery, be careful that it doesn't break plugins. | stackexchange-wordpress | {
"answer_score": 31,
"question_score": 14,
"tags": "jquery"
} |
Am I allowed to resell Wordpress Premium Plugins under GPL?
I have seen a few websites around that resell premium plugins and extensions such as the Woocommerce Extensions, is this allowed? Not too sure where to ask this question either. | Read < and <
> Except for one special situation, the GNU General Public License (GNU GPL) has no requirements about how much you can charge for distributing a copy of free software. You can charge nothing, a penny, a dollar, or a billion dollars....
>
> The one exception is in the case where binaries are distributed without the corresponding complete source code. Those who do this are required by the GNU GPL to provide source code on subsequent request. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "plugins, woocommerce offtopic, premium"
} |
Rewrite Page with a slug before page name
I am using $wp_rewrite->non_wp_rules
I have the following code that works:
'name/(.*)' => 'index.php?post_type=post';
Im able to use a url like <
using $wp_rewrite->non_wp_rules, how can I make pages work the same way.
This is just an example:
'anothername/(.*)' => 'index.php?post_type=page'; //for all pages
'anothername/(.*)' => 'page/pagename' //for one specific page
Is there a way I can have a page look like this:
The two examples above just redirects me to:
//without the slug | I've not tried external rules, but you can achieve that with an internal rewrite and `pagename`:
function wpd_page_rewrite(){
add_rewrite_rule(
'^anothername/([^/]*)/?',
'index.php?pagename=$matches[1]',
'top'
);
}
add_action( 'init', 'wpd_page_rewrite' );
For parent/child pages you have to set `pagename` to the parent/child path, `page/pagename`, or you can also use `page_id` and use the page's ID.
EDIT - note that you have to flush rewrite rules after adding new ones. a quick way to do this during testing is to visit the permalinks settings page. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "permalinks, url rewriting"
} |
Can't save WordPress post with "/etc/" in it
In my self-hosted WordPress site, if I create a post with "/etc/" (without quotes) in it anywhere, I get a 404 Not Found when I save the post.
Wrap it in `<pre>` tags, or even escaping the characters (`/etc/`) doesn't work.
I've tried disabling all my plugins, but that doesn't make a difference.
Any pointers will be greatly appreciated. | Ther is probably `mod_security` or a similar add-on installed on your web server. Find it, take the word `etc` out of the list of stop words.
WordPress doesn’t do that. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, content"
} |
How to completely disable a taxonomy archive on the frontend?
I have registered three custom taxonomies. All three of these custom taxonomies are attached to my custom post type.
There is only one taxonomy out of the three registered, that I would like not accessible what so ever on the frontend of the website.
What is the best solution for this?
I have been playing around with specifying different arguments while registering the taxonomy, but nothing seems to work.
$args['show_in_nav_menus'] = false;
$args['query_var'] = false;
$args['public'] = false;
Should I just hook into `template_redirect` and do a `is_tax()` check? If it's the taxonomy I want disabled, just redirect to the custom post type archive? | s_ha_dum's answer didn't work for me, but this did:
/**
* Completely disable term archives for this taxonomy.
* @param string $taxonomy WordPress taxnomy name
*/
function kill_taxonomy_archive($taxonomy){
add_action('pre_get_posts', function($qry) {
if (is_admin()) return;
if (is_tax($taxonomy)){
$qry->set_404();
}
}
);
} | stackexchange-wordpress | {
"answer_score": 18,
"question_score": 7,
"tags": "custom post types, plugin development, custom taxonomy, themes, taxonomy"
} |
Wrapping images in tags based on size
I am making a site for a client where all the thumbnails on a page need to be styled differently than regular sized images. Right now I have a snippet of code I found that allows me to wrap every image inserted into a post in a div, but I would like to only wrap the thumbnails.
Code:
function filter_images($content){
return preg_replace('/<img (.*) \/>\s*/iU', '<div class="post-thumb"><img \1 /></div>', $content);
}
add_filter('the_content', 'filter_images');
Is there a way I can do this? | You can wrap specific sizes in arbitrary html when they're inserted into post content via the `image_send_to_editor` filter.
Here we check if `$size` is `thumbnail` and wrap it in a div, otherwise we just return the unaltered `$html`:
function wpd_wrap_thumbnails( $html, $id, $caption, $title, $align, $url, $size, $alt ){
if( 'thumbnail' == $size ){
return '<div class="circle">' . $html . '</div>';
}
return $html;
}
add_filter( 'image_send_to_editor', 'wpd_wrap_thumbnails', 10, 8 );
You can also add an editor stylesheet with your CSS, so the client sees them styled properly within the editor. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "pages, images"
} |
How to understand a specific bit of Wordpress syntax
I am changing a theme in Wordpress, and in an earlier theme, there was something like this that added a an email signup widget to the page:
[green_tick_1_list width="100%"]
But in the new theme that I installed, this just shows up as text. Is there any way to make it show up as the email signup form like it used to?
And what is that syntax? Is that something I can create in WordPress per each theme I use? | That's a Shortcode.
It may be possible to find the function that renders that shortcode and copy/paste it into your own plugin, making it theme-independent, however, how easy that will be to do depends on how the shortcode works- if it depends on additional php functions, JavaScript, and CSS embedded within the theme. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "themes, theme options"
} |
Access Wordpress database outside of Wordpress
MAIN QUESTION:
I am writing a wp plugin. Within it, I have a page located here:
How do I access WP database from this page? Is there any official, proper way that won't break with updates? Or any reliable way at all?
* * *
As a second possibility (not preferred) - I was thinking maybe my plugin could create a wordpress page, which then would be somewhere like:
Is this possible? And how would it react to user's changes of permalinks settings? | In a nutshell there is no generic reliable way to load WordPress core from arbitrary file. Since core and extensions directories are independent from each other (they are co-located by default, not by necessity) only core configuration "knows" where extensions are, but not other way around.
In private code things like this just get hardcoded. In public code this is pretty much undoable properly.
If it's not critical for you to modify core load process then custom URL is definitely way to go. Implemented via Rewrite API from scratch or as endpoint it will be reasonably reliable. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, database, wpdb"
} |
How do I display the posts from a custom post type on a category.php page?
I have set up a `category.php` according to this wordpress hierarchy diagram.
When I am on the page < I want to display all posts that are under `my-category` using the loop:
<?php if (have_posts()): while (have_posts()): the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php endwhile; endif; ?>
Wordpress is not showing the posts. I will also add that this is a custom post type, but that shouldn't matter or should it?
I can use `get_posts()` but then what is the point of having a `category.php`?
How do I show the posts in the current category using `the_loop`? | > I will also add that this is a custom post type, but that shouldn't matter.
In fact, this _is_ your problem.
By default, the Category Archive Index will only query posts from the `post` post-type. You need to tell WordPress to do otherwise, by adding your custom post type to the query via `pre_get_posts`:
function wpse140419_add_cpt_to_category_archive( $query ) {
// Only modify the main query
// on the category archive index page
if ( $query->is_category() && $query->is_main_query() ) {
// Add CPT to the query
$query->set( 'post_type', array( 'post', 'your-cpt-slug' ) );
}
}
add_action( 'pre_get_posts', 'wpse140419_add_cpt_to_category_archive' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "categories, loop"
} |
wp_get_attachment_image_src() and custom sizes
As said in this page, `wp_get_attachment_image_src()`only accepts built-in sizes such as thumbnail, medium, large or full.
How do you get the same return value with custom sizes you add with `add_image_sizes()` ? | You are misreading the Codex. `wp_get_attachment_image_src()` works just fine with custom image sizes.
Proof of concept:
// copied from the Codex
//
if ( function_exists( 'add_image_size' ) ) {
add_image_size( 'category-thumb', 300, 9999 ); //300 pixels wide (and unlimited height)
add_image_size( 'homepage-thumb', 220, 180, true ); //(cropped)
}
Add an image to the Library, then...
$image_attributes = wp_get_attachment_image_src( 28, 'category-thumb' );
var_dump($image_attributes);
You will notice that the image returned is (an appromixation of) 300x9999-- that is 300 wide by whatever height scales correctly. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 5,
"tags": "post thumbnails"
} |
Edit the excerpt before it is shown
I'm looking for a way the edit the excerpt before it get's show on the page.
The issue is this: We import data (jobs) for a third party provider and the content is divided in sections with each a header (e.g. the first one is "Introduction"). The issue now is that in the overview with the post, each excerpt looks like "Introduction. Lorem Ipsum". So I want to manipulate the data to remove "Introduction."
Are there any hooks in WordPress that I can utilize to either edit the data before shown, or is there a function that I can overwrite that display's `the_excerpt()`?
I'm using a child theme of a theme we bought and would prefer to not mess with the core files. | Well, I found it:
function get_the_excerpt_filter( $excerpt ) {
$wordToRemove = "Introduction";
$len = strlen($wordToRemove);
if(substr($excerpt, 0, $len) == $wordToRemove){
$excerpt = trim(substr($excerpt, $len));
}
return $excerpt;
}
add_filter( 'get_the_excerpt', 'get_the_excerpt_filter' );
Hope this helps someone else. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "excerpt"
} |
Memory needed to host 200 wordpress sites?
I'm planning to use Multisite to host 200 different wordpress blog with each having their own unique subdomain. I notice each time I create a virtual host for each subdomain it'll use roughly 50mb ram. So if 50mb * 200 sites = 10GB RAM correct me if wrong is 10GB of RAM needed to host 200 sites? if possible is there solutions to decrease ram usage? | The actual RAM you need depends on many factors:
* plugins
* theme
* installed extensions (server and PHP)
* the current operation (editing images needs the most)
* translation, some translation files are really heavy
In a multisite, some resources are shared, the server setup for example is not duplicated each time you create a new site.
You can save some resources if you enable the built-in Opcache, check your theme and the plugins with Xdebug. There is not much you can do with translations. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "multisite, performance, memory"
} |
Changing permalink name redirects to another template?
I'm creating a template with a few templates with names `page-contact.php`, `page-portfolio.php` and `page-blog.php`.
The problem is that when I select a **Defaul Template** for a page (I expect it to open `page.php`) and rename the page permalink to **sitename.com/contact** the page starts using the `page-contact.php`..
Why is that, why is the URL telling WordPress what template to use if a Default one i chosen? Is this intended behavior? | Yes, this is the intended behaviour:
> page-{slug}.php - If the page slug is recent-news, WordPress will look to use page-recent-news.php
So, simply use a different filename for your templates, like template-contact.php for example. You can find more info about this here:
< | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "permalinks, pages, templates, page template"
} |
How do I count columns on a custom WPDB query?
How would I count the columns of a custom `WPDB` query?
This does work although I need a different kind of output:
$sql_assoc = "SELECT * FROM test";
$num_cols = count((array) current($sql_assoc));
echo $num_cols;
OUTPUT:
47
But what I would want is every `column`+the total as output, like so:
`4712345678910111213141516171819202122232425262728293031323334353637383940414243444546`
Usually you'd accomplish this by doing the following but of course this won't work in wordpress or at least I have no idea how to use `field_count` in wordpress since outputting query results of a custom `WPDB` goes differently like so in PHP:
$sql = "SELECT * FROM test"
if($result = $mysqli->query($sql))
{
$numcol = $mysqli->field_count;
} | This is not possible.
I instead created functions to execute count queries. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wpdb, columns, count"
} |
Make different sites on multisite reference same script
I'm using multisite and want all my scripts to point to the same URL so they are optimized as well as they can be. Currently I have:
<
<
But they both reference the same file. I'd like them to be both something like:
<
That way it would save people having to download the same file again even though they already have it cached locally. This question is the same question but the solution isn't up to date. Does anyone have any ideas of code or any plugins that might help solve ?
Thanks | Hi this is what I did to solve it:
add_filter( 'script_loader_src', 'change_src' );
add_filter( 'style_loader_src', 'change_src' );
function change_src( $url )
{
if( is_admin() ) return $url; // Don't filter admin area
return str_replace( site_url(), 'www.mysite.com/mydefaultnetworksite', $url );
}
I'm using both those filters because I want it to apply to script and stylesheet urls. The function just looks for the site url, rips it out and replaces it with a hardcoded version of the url I want all the sites scripts / stylesheets to point to.
I opted for the first site in the multisite, but it could be any :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, optimization, scripts"
} |
apply_filters('the_content') - make it ignore shortcodes?
I am using `apply_filters('the_content)` so I can see properly formatted content inside my wp editor in the backend.
However, this also renders the shortcode that's in the content.
I want it to ignore the shortcode and apply filtering to the rest of the content, basically the same thing as when making posts. If you view post content in the backend, you will see the shortcode, but if you view it inside a page on your website, you will see the rendered shortcode (its result).
Is this possible? | The function that parses the shortcode, `do_shortcode` is added as a filter on `the_content` by default, at priority 11.
You can remove it using `remove_filter`:
remove_filter( 'the_content', 'do_shortcode', 11 );
Call this right before you're actually using `the_content`, and add it afterwards (in the unlikely case that it's needed after that):
remove_filter( 'the_content', 'do_shortcode', 11 );
the_content():
add_filter( 'the_content', 'do_shortcode', 11 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "filters, content, wp editor"
} |
Search page for custom post type
I am new to wordpress and a beginner coder, and i was searching around the net, found solutions but still does not work.
I have custom post type named `dlm_download`, and my custom search template not working
I added the following to my `functions.php` file - the code is from this answer by @Ronald.
function template_chooser($template)
{
global $wp_query;
$post_type = get_query_var('post_type');
if( $wp_query->is_search && $post_type == 'dlm_download' )
{
return locate_template('archive-download.php');
}
return $template;
}
add_filter('template_include', 'template_chooser');
Created the `archive-download.php`
and when i preform my custom search, i get the url like this `mysite.com/?dlm_download=699` nothing happens i just get redirected to my home page.
Could please someone tell what i am doing wrong? | You can simply include a custom search function into your search by using `pre_get_posts`
You can do something like this
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', 'your-custom-post-type' );
}
}
}
add_action('pre_get_posts','search_filter'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, posts, templates, search"
} |
Format numeric symbols in titles
When I add title post as: `this - is - post`
I view code source : `this – is – post`
How to format code source as: `this - is - post`
Error: I'm user jQuery UI autocomplete code source [`"this – is – post"`,`"this – is – post"`, ] and views html autocomplete input is `this – is – post`
How to fix in jQuery or change echo code source? | WordPress makes number of typographical replacements, related to dashes. You can read through the How WordPress Handles Dashes and Hyphens for full details, but in short your specific case is `[space][hyphen][space]` getting replaced with `[space][en-dash][space]`.
You will have to step through your code to make sense at which point it goes wrong and turns into visible unwanted entity rather than character.
Depending on how much of this you have the easy fix might be just to type actual en-dash character (`Alt`+`0150` on numpad on Windows) instead of "minus" hyphen. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "jquery, jquery ui"
} |
Permalink change made author archive vanished
I changed my WordPress blog URL from:
into first,
and then after many days,
But now seen that, they are taking the author archive link to a dead end (404). Where the default author archive link is: `/?author=1`, with any of these permalinks, the author archive's link becomes `/author/1`. But the URL is taking me to a 404. I've tested in my local dev environment too, can't get what's the exact URL which can give me the author archive.
The author archive link, that's in my theme is:
<a href="<?php echo get_author_posts_url( false, $authordata->ID, $authordata->user_nicename ); ?>">
<?php the_author(); ?>
</a>
Is that a bug of WordPress or I'm doing something wrong? | Your `get_author_posts_url()` seems wrong, it doesn't accept three parameters. Passing ID as first one should be sufficient to generate correct link, name argument is pretty redundant there. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "permalinks, 404 error"
} |
Why is tinymce visual editor showing the background from my theme
In my theme I have the body background style set to a particular image (in style.css file). When editing the content under visual editor I have this same background I set in the theme. Is it possible to turn this off? | Maybe your theme register a custom stylesheet for the editor, this is possible via the function add_editor_style(). Search for the function in your theme directory, maybe inside the `functions.php`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "visual editor"
} |
Wordpress crop image not working
I have the following CSS:
.crop {
height: 40px;
overflow: hidden;
margin-bottom: 20px;
}
to crop an image when the screen shrinks. It works in a normal HTML file, but in Wordpress, the result is a compressed image, not a cropped one. How can I fix this? | It's possible your theme is setting
width: auto;
on the image, possibly as part of some responsive tweaking. This would cause it to keep its normal proportion but with the specified height.
Can you provide a URL to look at? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, cropping"
} |
problem including page template
I am creating a one page wordpress site. The code I am using does work but for some reason it will not include page templates. It only gets the content from the page editor but will not get the custom html that is inside the page template so I am trying to include the file.
I am getting error messages that say include() : "Failed opening"
$template = get_post_meta( get_the_ID(), '_wp_page_template', TRUE );
$file = get_template_directory_uri() . '/' . $template;
include($file);
I am confused here because the path that it is giving me is the correct path for the file. I have 4 templates in my theme and from the code above, One template did get included but the other three have failed. | I think you meant to use:
get_template_directory()
> Codex: Absolute path to the directory of the current theme (without the trailing slash). (link)
instead of:
get_template_directory_uri()
> Codex: Retrieve template directory URI for the current theme. Checks for SSL. (link)
if you're using `include()` for PHP code.
But you should rather consider using:
get_page_template()
> Codex: Retrieve path of page template in current or parent template. (link)
The function `get_template_part()` is also handy when want to resuse template parts. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "template include"
} |
Different Ways to Query Custom Post Types?
I'm using this code to use custom post types like regular post:
add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
function add_my_post_types_to_query( $query ) {
if ( is_home() && $query->is_main_query() )
$query->set( 'post_type', array( 'post', 'miss_behave', 'emily_davies','gemma_patel','poppy_smythe' ) );
return $query;
}
But I also saw this code to display custom post types:
$query = new WP_Query( array(
'post_type' => array( 'post', 'page', 'movie', 'book' )
) );
I'm wondering what the differences are between the two methods.
Thanks. | The first way, using the pre_get_posts action will modify the main query before the page loads. The second way will create a new query. It is much better to alter the main query than to create a new query. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, wp query, query posts, query"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.