INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
trouble with my loop
I am trying to exclude categories from my blog page. I have the code all set up and according to the codex, this should work
$string = '-' . implode( ',-', explode( ' ', $data['exclude_categories'] ) );
The above line will print this to the screen upon testing
-homepage,-recent-news
Those are the two test categories that I am trying to remove from the blog page. Then I start my query like so
<?php query_posts($query_string . '&cat=' . $string);?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
my other code stuff here
when I test the blog page, all the posts show up. I can't figure out what is wrong. | `cat` accepts category IDs, not slugs or names. a better method here is to use the `pre_get_posts` action, the Codex page has an example that does exactly what you're trying to do. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "exclude"
} |
Don't post or draft if post already exists
I've got a problem. I don't want duplicate posts. Any way to check if a post already exists and if it does just set the new one to draft? I am using IFTTT to update my blog and sometimes it posts multiple times. | I have no idea what IFTTT is but you can use the `save_post` action hook to do a check for duplicate posts. This hook runs whenever a post is created or updated you would then be able to right your own code to check against existing posts.
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "posts, draft"
} |
Category page when using static front page
I'm using a "static" front page with the posts on a page called News. Is it possible to make the categories use that as the base? Like this:
/news/[category_name]/
And is it also possible to do the same with posts?
/news/2012/09/17/post-title | Yes update permalink to something like this
!enter image description here | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, categories"
} |
Purchased Theme to Custom Made Theme?
I bought a theme from Themeforest and now I would like to convert it to a custom made theme. I was creating the theme with the Underscores theme: < but how do I keep the same custom post types in the next theme?
Is this less time consuming than recoding the purchased theme? | Move the custom post types to a plugin. They should never be part of a theme for exactly the reason you asked here. :)
In your theme add just the needed template files, but not the code for post type registration. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "theme development, themes"
} |
Excluding a custom taxonomy term breaks wp_get_post_terms
I'm trying to exclude one custom taxonomy from an archive page, and then show the terms of the returned posts.
When I run WP_Query to exclude the custom term, it returns the posts correctly, but no longer fetches the terms array when using `wp_get_post_terms()`. I suspect that not querying in the positive prevents it from fetching the terms. Here's what my code looks like:
$query = new WP_Query(
array( 'tax_query' => array(
array(
'taxonomy' => 'documenttype',
'field' => 'slug',
'terms' => array('pressreleases'),
'operator' => 'NOT IN'
),
) )
);
//then later, in the loop ...
$terms = wp_get_post_terms($query->post->ID,'documenttype');
// var_dump($terms) shows an empty array | Thanks for your help everybody.
I was using a custom post type and forgot to include
'post_type'=>'my_custom_post_type'
I finally got to the problem by doing a `var_dump` on the `WP_Query` object and looking at the SQL. Running the query directly on the database and picking through it, I eventually found my error. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "custom taxonomy, wp query"
} |
Menu items id's - are they 100% unique?
With regards the menu item id's WP generates such as `menu-item-814`, are these 100% unique in nature?
I know they are unique at the time, but are they always unique? Meaning that if I was to delete something that had the id of 814, is it possible that some other menu item could now be assigned this ID? ...or if WordPress was updated do they still keep the same ID's?
I ask because I want to assign something to a certain menu button via JavaScript but on the off chance the button is removed I don't want to be applied to a new button that has now been assigned that ID. | Yes it is always unique. id 814 cant be applied again unless you update it manually on your DB. Its because of auto increment .. DB automatically increment id so everytime next id will be +1
814
815
816
and so on.. Even if you delete an id in between. It wont affect auto incrementation.
Read MY SQL AUTO_INCREMENT for detailed understanding. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "menus"
} |
Echo simple string in Plugin
I am getting started with plugin development. I wrote the following program to display text on screen but nothing happened. Please help. Thanks.
<?php
/*
Plugin Name: Fahad
Plugin URI:
Description: Declares a plugin that will be visible in the
WordPress admin interface
Version: 1.0
Author: Yannick Lefebvre
Author URI:
License: GPLv2
*/
?>
function fahad(){
echo "I am alive";
}
add_filter('wp-footer', fahad); | A subtle difference between your syntax `wp-footer`should be `wp_footer`, underscore `_` and not hypthen `-`
add_filter('wp-footer', fahad); // wrong...
add_filter('wp_footer', 'fahad'); // right..
Follow the naming convention of functions:
* (Codex) Plugin_API: Action_Reference » the `wp_footer` hook
* (Codex) Plugin_API: Action_Reference
* (Codex) Function_Reference | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "plugins, plugin development"
} |
Admins can't edit each other's posts
After I imported content from another wordpress site using the WXR export/import tools, my admins can't edit each other's posts. This is really aggravating because I can't figure out how to change this. And it doesn't just related to imported content. I can create two brand new admins, each one creates an entry, but neither one can edit the other's posts.
On the post listing page, it doesn't even show an Edit link on or below the title, and there's no checkbox for bulk editing, if the logged-in user isn't the author. I don't have this problem with pages, but it does effect any Custom Post Types set as 'capability_type' => 'post'
I have no idea how this happened or how to undo it. Please help before I pull all my hair out. | Ok, I got it figured out. For some reason, current_user_can was returning false when an admin went to edit other user's posts... I have no idea how admins lost the ability to do this, but putting this into functions.php is a workable bandaid that restores admin edit capabilities;
$administrator = get_role('administrator');
$administrator->add_cap('edit_others_posts'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "users, permissions"
} |
Multisite mu-plugins site-specific directory
Is it possible to have a must-use directory within the multisite system that is specific to each individual site? | Define the constants `WPMU_PLUGIN_DIR` and `WPMU_PLUGIN_URL` depending on the host or path in you `wp-config.php`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugins, multisite"
} |
Getting thumbnails of a custom posts featured images in a page-templates metabox
I guess I need to know how to call meta data into metaboxes for beginners.
I'm using
$posts = get_posts(array(
'post_type' => 'slidertype',
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids'
)
);
//loop over each post
foreach($posts as $p){
//get the meta you need form each post
$thumb = get_post_meta($p,"_thumbnail_id",true);
echo $thumb;
To try to get thumbnails of my custom post type 'slidertype' to show up in a page's metabox. Right now it's displaying a number which doesn't make sense to me. No advice is bad advice guys! Thanks. | You can get the image from your $thumb integer with the following additional code:
$thumb = get_post_meta($p,"_thumbnail_id",true);
$image = wp_get_attachment_image_src($thumb);
echo $image[0];
This will return the URL of the image, just put that in an img tag to display it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, post meta"
} |
How do i structure my theme folder to avoid one huge list of files
When working with a worpress site with lots of custom post types and lots of page templates, my theme folder is looking messy. What are the accepted best practices to organise code files in WordPress?
a couple of the limitations i'm coming up against are that templates are chosen by name, so i can't group files by prefixing them. Also custom post template files can not be in sub directories. Also header and footer can not be in subdirectories.
How can i organise my code better? | Not a full answer, but I can at least answer this question:
> Also custom post template files can not be in sub directories.
Everything, that you can load via `get_template_part()`, can reside in a subfolder:
get_template_part( 'subdir/part', 'suffix' );
It's as easy as that. Now you've your part inside
~/wp-content/themes/theme_folder/subdir/part-suffix.php
* * *
_Slightly off topic._
Then there're some nice tricks, like using the post format or post type as part name:
get_template_part(
'content'
,get_post_format()
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 4,
"tags": "themes, directory, code"
} |
Is it possible to put next and previous category links?
I'm not trying to navigate to the next post within a category, but to put previous category and next category under the category description on its archive page and navigate between archive pages.
I've searched, but I'm not sure this is even possible without hardcoding categories, and I don't want to do that. I'd like to dynamically link.
Not asking anyone to write any code for me, just asking does this sound like a good starting direction for what I need to look at doing:
Build a get_next_category function by using the wp_list_categories, then pulling the adjacent from that list and turning it into a link?
In short, I want a category archive page to show a category title, description (know how to do both of those), then next and previous category links before it shows the posts. I am not creating a list of categories, just navigation links.
Hope that clarifies what I'm trying to do. Still searching codex and exchange. | Not sure if this is what you want, gets all the categories and outputs a link to the next and previous in the order returned from `get_categories()`:
$this_category = get_queried_object();
$categories = get_categories();
foreach( $categories as $position => $cat ) :
if( $this_category->term_id == $cat->term_id ) :
$next_cat = $position + 1;
$prev_cat = $position - 1;
break;
endif;
endforeach;
$next_cat = $next_cat == count($categories) ? 0 : $next_cat;
$prev_cat = $prev_cat < 0 ? count($categories) - 1 : $prev_cat;
echo 'previous: ' . get_term_link( $categories[$prev_cat] );
echo 'next: ' . get_term_link( $categories[$next_cat] ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "categories, navigation"
} |
Using get_post_meta with new_to_publish
I'm trying to read the custom fields set by the user when publishing a new post:
function doSomething($post) {
$meta = get_post_meta($post->ID);
error_log("post meta: ".print_r($meta, true));
}
add_action("new_to_publish", "doSomething", 999);
add_action("draft_to_publish", "doSomething", 999);
add_action("pending_to_publish", "doSomething", 999);
The custom fields are there for draft_to_publish but not for new_to_publish.
If I use save_post it seems to work every time, but I need it to only run when the status is set to publish for the first time... | That's because the fields weren't set then. Note: The »Autosave« process/request also doesn't save them.
Use the values from `$_POST` instead for your `"new_to_publish"` action.
**EDIT:** Do **NOT** forget to escape and properly sanitize input data! Else you will open a security hole. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 7,
"tags": "custom field, post status, post meta"
} |
Populate meta select box with child pages
I'm trying to populate a drop down select meta box with a list of child pages of that page.
I am using the wp_list_pages function to retrieve the list of child pages, no problem there.
The problem is that the list is return as li items. What is the best way to get these into an `<option>` format suitable for a dropdown box? | Not sure what you mean by "drop down select meta box", so maybe I'm way off, but there is a wp_dropdown_pages function that does that. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "metabox, dropdown, wp list pages"
} |
How to change font in title of sidebar widget
I'm not sure if this question belongs in the CSS forum or the WordPress forum...
At this link to my wordpress site: < in the sidebar, there's a title for a widget "GET FREE CHAPTERS PLUS MORE HELPFUL COPYWRITING IDEAS" - I'd like to change the font of widget titles, so it's not all-caps. So it's small and bold.
How do I do that?
I'm a novice. Where would do i go to find the right file; what's the file name; what code do i need to find to change; and what code do i use as the change? | It definitely belongs to CSS forum, but any way:
Open: your style.css located in wp-content/themes/twentyeleven-child/
Go to: line 1736 where it says .widget-title
Remove: `text-transform: uppercase;` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "sidebar"
} |
using Ajax: call to undefined function get_option
I am using ajax on my template to load a file called counter.php. When I click a button, it is supposed to increase the counter. But when I click the button I get this error "Fatal error: Call to undefined function get_option()".
This is what I have on counter.php
$post_ID = $_POST['ID'];
$opn_name = 'fb_counter'.$post_ID;
$counter_value = get_option($opn_name);
if($counter_value==NULL){
$counter_value = 0;
}
update_option($opn_name, $counter_value+1);
echo get_option($opn_name);
I am not sure what is wrong. Do I have to include any wordpress files on this php file ? | Basically, if you're going to be making calls to WordPress functions, then you should be in the WordPress environment, which means that you should not be calling your own files to begin with, but should implement your AJAX call within a WordPress hook.
Read up on this: <
That article describes how to implement AJAX requests within WordPress plugins, but it works equally well in themes or in any other code that WP loads.
Essentially, you hook a function to wp_ajax_* or wp_ajax_nopriv_* and then make your request through the the admin-ajax.php file instead of directly to your own file.
Side note: Implementing a counter like you're trying to do won't work particularly well, because you have a race-condition there. More than one person can be visiting your site at the exact same time. Storing counter data in the DB like that isn't going to scale to a very large site with lots of requests, although it will work fine for smaller sites. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "ajax, options"
} |
Custom post type - order field
In a custom post type, is there a way to include the "order" field that is available for pages?
Is there any built-in logic that prevents duplicate values in the "order" field?
The idea is to be able to sort a custom post type by a user-specified order, then alphabetically by a string-based custom field. | When declaring your custom post type using the register_post_type function, you have to add 'page-attributes' to the support field, like in the following example:
register_post_type('myposttype', array(
'supports' => array('title', 'editor', 'page-attributes'),
'hierarchical' => false
));
You'll need to add any other supported meta boxes as well to the 'supports' field, see < for more information about the register_post_type fields.
Also as far as I know there isn't any built in way to prevent two of the same order, this is because you can create sub-ordering based on heirarchy (so one group of children pages can have a different ordering than another) | stackexchange-wordpress | {
"answer_score": 36,
"question_score": 20,
"tags": "custom post types, theme development, order"
} |
Content in footer file
I swear I've done this before, but I am drawing a blank on it now...
I'm trying to get it so that I can have editable content in my footer.php file. So that I (or the user) can update the content within the pages area.
But I can't remember how to go about it, or if I need to do a widget instead? | There are a couple of ways this can be achieved.
You can create a theme option for the area. I used this as a theme option starter when I built a theme recently: Sample theme options
Or
You can simply create a widget area for the footer < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "content, footer"
} |
Wrong user registration date in wordpress
I have this funny problem and I'm not able to locate where it happens.
The problem is when a user registers on my site his/her registration date is wrong (not just wrong but total rubbish, even if I add them manually from the admin panel).
I tried deactivating every plugin and theme installed on wordpress to no avail.
The problem persists no matter what. Here is a screen shot from phpmyadmin.
!enter image description here
Help me, please. | It seemed that the database was somehow malfunctioning. I tried repairing the table and it seems to have worked for now. Though I had to reset all the dates. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "user registration, date"
} |
What types of files can I upload with the Wordpress Uploader?
I have a domain with Wordpress 3.4.2 installed on it. (This is NOT a Wordpress.com site)
What kind of files can I upload? I know .jpeg, .gif, .png, .mp3, etc. are accepted, but where can I find a complete list of the accepted file types?
Basically, what can I upload via this screen: !enter image description here | From < :
**WordPress supports uploading the following file types:**
> Images
>
> .jpg .jpeg .png .gif
>
> Documents
>
> .pdf (Portable Document Format; Adobe Acrobat) .doc, .docx (Microsoft Word Document) .ppt, .pptx, .pps, .ppsx (Microsoft PowerPoint Presentation) .odt (OpenDocument Text Document) .xls, .xlsx (Microsoft Excel Document)
>
> Audio
>
> .mp3 .m4a .ogg .wav
>
> Video
>
> .mp4, .m4v (MPEG-4) .mov (QuickTime) .wmv (Windows Media Video) .avi .mpg .ogv (Ogg) .3gp (3GPP) .3g2 (3GPP2)
>
> Not all web hosts permit these files to be uploaded. Also, they may not permit large file uploads. If you are having issues, please check with your host first.
That bottom note means that you may be limited on the size of file uploads via your or your web host's php.ini file, and file type uploads may also be limited in php.ini or .htaccess, depending on what you have configured or what your web host has configured. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "uploads, file manager"
} |
What triggers these wordpress queries on my homepage?
I am trying to clean up my wordpress theme and I want to know what triggers the following questions on my blog homepage.
First - do I need this on my homepage?:
SELECT user_id, meta_key, meta_value FROM wp_usermeta WHERE user_id IN (1)
require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/baracuda/index.php'), setup_postdata, get_userdata, get_user_by, WP_User->init, WP_User->for_blog, WP_User->_init_caps, get_user_meta, get_metadata, update_meta_cache
Second:
SELECT * FROM wp_users WHERE ID = '1' | Are the queries themselves displayed or are the results displayed? If the results of those queries are being output onto your homepage it's a potential security vulnerability.
The query returns user data including username and password hash for user ID 1 of the wp_users table, which is the administrator user that Wordpress creates when first installing.
I recommend changing the administrator's password and removing the code from the homepage, and checking other template files for similar code.
Also its generally a bad practice to run SQL queries in theme files, as there are built-in functions in Wordpress for accessing user data. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query"
} |
How can I change get_the_post_thumbnail to make 100% width image?
I have a WP site whose center column is variable width.
I would like the featured image to appear front and center - 100% width. If I hard code the image path using a plain old image tag with width=100% it looks exactly as I want.
For obvious reasons I don't want it hard coded.
I'm currently using this but the image goes outside of the bounds of the column.
<?php echo get_the_post_thumbnail($id, 'full', array('class' => 'aligncenter')); ?>
So, my question is this.
How can I mimic the behavior of `<img src="myimage.png" width="100%" />` but with the `get_the_post_thumbnail` convention. | I ended up using the following to solve my problem.
<?php $image_id = get_post_thumbnail_id(); ?>
<?php $image_attributes = wp_get_attachment_image_src( $image_id, 'full'); ?>
<img src="<?php echo $image_attributes[0]; ?>" width="100%"> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "images"
} |
How do I display the index position of a post from a custom post type?
So I have a custom post type (ex. songs) and have a few posts that I created for this post type.
I want to display them on a webpage in order (ex. 1, 2, 3, ...). How do I get the index position and display it on my page?
Any insight or solutions would be greatly appreciated! | One solution is to add a custom field to the posts. Call it index_position or something similar. Create a nice meta_box if you want the client to be happy.
Then, when you query for posts in your template, ask for posts sorted by your custom field in a meta_query:
$song_query = new WP_Query(
array(
'post_type' => 'songs',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_key' => 'index_position',
)
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, posts, get posts"
} |
highlight parent page menu item when in custom post type
in a website that I am building I have a portfolio custom post types (called: "project") to show my portfolio items. The page that holds the loop of the custom post type is a custom page called " **Portfolio** " this page has only thumbnails and each thumbnail is linking to a custom post type: <
notice when inside the portfolio page above the upper menu is highlighting the current page like other pages in the site.
when entering a post type (clicking on one of the portfolio items) I would like the upper menu "portfolio" to stay highlighted as we are still in the portfolio section but it doesn't work: <
I understand why it doesn't work but I can't find a solution how to keep it highlighted when inside a custom post type.
would love to have a solution
Thanks Gil | You should be able to use a _body class_ to style your menu item :
.single-project .menu-item-45 a
In "Appearance > Menu", you could also add custom CSS classes to menu items. You could give your Portfolio menu item a class of "portfolio" and do this :
.single-project .menu .portfolio a
I do this mainly because I don't like .menu-item-[number], it's more readable with a plain text name, but the first solution should work anyway. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, menus, syntax highlighting"
} |
adding meta data using plugin to top of head
It seems if you use the wp_head hook as an action to put your custom metadata into the head tags of your page, it is dependent on where the theme you are using calls the wp_head. In my case, it is at the end of the head tags.
How can I force my meta data near the top of the head tags? I have a header.php file I'm calling in using a self-made plugin. I know how to write the function code to call the header.php. I just need to know how to hook it to the start of the head tags.
Thanks, Derek | Okay, here's the answer:
function CustomHead() {
include('headcontent.php');
}
add_action('wp_head','CustomHead',1,1);
The key is that first "1", which sets the priority of it to run at the highest (this is an optional element, defaulting to 10, putting it at the end of the head by default). More info here: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, headers, wp head, custom header"
} |
Put code into body tags near top, using a plugin
How do I use a plugin to put this inside the body of every page on my WP site, for facebook integration. (Yes, I know other plugins can do it, but I want to do it myself.) Facebook recommends as close to the top of the lead body tag as possible.
Thanks!
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=99999999999";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script> | Ultimately, further research found there is an effort to add wp_body as a hook, but it is not yet implemented. In the meantime, one can append or prepend it to the content of the loop. But in this case, adding the facebook stuff at hook wp_footer works. This is what I've done. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugins, hooks"
} |
WP Query Obj: Set value to be unequal | Hide media by admin
I would like to hide all media uploaded by the admin.
I've found an answer to this question to be pretty close. Except that the query returns all media uploaded by a specific (current) user, instead of excluding all by a specific user.
[...]
if( !current_user_can('delete_pages') )
$wp_query_obj->set('author', $current_user->id );
[...]
Q: Is it possible to modify the wp_query_obj to exclude all posts by a specific user? | The method is similar, just exclude the author by prefixing the id with a minus sign:
$wp_query_obj->set( 'author', '-1' );
See `WP_Query` for a full list of query arguments. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "wp query, uploads, media library, exclude"
} |
Modify wording of bulk options
I would like to modify the wording in the bulk actions on the posts screen or custom post types. I am trying to do so using the following code, but it's not working. Any idea why?
add_filter( 'bulk_actions-edit-post', 'my_custom_bulk_actions' );
function my_custom_bulk_actions( $actions ){
$actions['trash'] = 'Just testing';
unset( $actions[ 'edit' ] );
return $actions;
} | There's currently no possibility to modify those. Just renaming it (the label in the UI only) via JS is possible.
I'd recommend to not try to modify those strings, as they equal action names and therefore are part of the query strings. You might break things easily. Figuring out what causes things to brake a half year later will just be a pain. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "bulk"
} |
Is there a Wordpress core & plugins update action hook?
I would like to run several actions on a website once WP core or any of the plugins have been updated using the built-in update process. Is there a way to do it?
I would prefer if I could run commands on 3 different cases:
1. WP core update is finished
2. A single plugin update has been finished
3. A bulk update for plugins has been finished (so that I run the command only
after all of them have been finished) | ## Hooks
The hooks you're searching for are
'pre_set_site_transient_update_plugins'
and
'upgrader_post_install'
The later takes three arguments. Example:
function upgrader_post_install_cb( $true, $hook_extra, $result )
and should be used for: Move & activate the plugin, echo the update message.
## Moving plugins
Moving works like this:
$wp_filesystem->move(
$result['destination']
,'your_destination_path'
);
Then use `activate_plugin( 'path/file' );` after moving. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 6,
"tags": "hooks, updates"
} |
Wordpress Multisite - is it possible to put the main site in a subdirectory?
I am creating a site that has different language versions and the requirement from the client is that all language versions are:
1. A different site on a Multisite setup
2. They all have address like this: mysite.com/en
Since the main site is in english, it's address actually has to be mysite.com/en, not just mysite.com
If possible, I wouldn't want to make a redirect from the main site to just a subsite that has the address mysite.com/en, but would like to use the actual mainsite with the subdirectory address?
Reasons: admin interface & database are cleaner + consistency. | No, not without major refactoring and lots of custom rewrite rules. The thing just isn't geared to do that without some restructuring.
Is it possible? Sure.
Would it be clean and easy? Not even a little bit. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "multisite"
} |
How would I attach media/images to a post based on a ID stored in a each post's custom field
I have converted a site over to wordpress recently. I was able to import all the posts via a CSV importer, but not the images associated with each post. The post type is " **machinery** ". The custom field with the post's previous ID on the old system of each post is called " **machinery_legacy_idLocation** ". I have an additional table called " **legacy_images** ".
" **legacy_images** " has 2 columns " **ListingID** " and " **imageurl** ".
" **ListingID** " in the " **legacy_images** " table matches a post with the same " **machinery_legacy_idLocation** ".
Now the "imageurl" matches the title of a corresponding image that I have already added to the media library in Wordpress.
Basically I just need to figure out a way to reattach all these images to all these posts after the move. | `wp_insert_attachment` will insert an attachment post for a given parent post ID and filename. You can write a little script to query for all your posts with the legacy key, get their associated image paths, and call `wp_insert_attachment` for each. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, custom field, images, media"
} |
How to check if page has status published
How to check if page `id(SomeID)` is actually published? | You can use `'publish' === get_post_status( $id )`, where `$id` could be the current page ID retrieved via `get_the_ID()` or any other. | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 5,
"tags": "select, post status"
} |
get_posts not finding argument: post_name
I am digging up posts with a specific slug:
Where
$postSlug = 'abc'
$args = array(
'post_name' => $postSlug,
'post_type' => 'post',
'post_status' => 'publish'
);
$slugPosts = get_posts($args);
Output of $slugPosts[0]->post_name:
$slugPosts[0]->post_name = 'xyz'
What am I doing wrong here? How can I get a post from a slug? | Aha, despite there being a postmeta field of post_name->'slug', the correct syntax (which mirrors that of WP_Query, is
$args = array(
'name' => $postSlug,
'post_type' => 'post',
'post_status' => 'publish'
);
$slugPosts = get_posts($args);
Where 'name' is the key in the query (for posts, 'postname' for page).
Doesn't make much sense but might as well stick it as an answer. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "wp query, get posts"
} |
How do I remove the post format meta box?
Is it possible to remove the "Post Format" meta box from the edit/new post page? The blog in question has a lot of users that keep messing with that but it only uses the standard format post.
I'm kind of new to wordpress so excuse me if this is a really obvious one.
Thanks. | That gets added because your theme supports `post-formats`.
You can either use a plugin (or a child theme's `functions.php`) file to hook into `after_setup_theme` late and remove theme support:
<?php
add_action('after_setup_theme', 'wpse65653_remove_formats', 100);
function wpse65653_remove_formats()
{
remove_theme_support('post-formats');
}
Or look for the the line in your theme's `functions.php` file:
add_theme_support('post-formats');
and remove it.
The first option is a better bet. Stick it in a plugin and it will be there for the next theme you use as well. | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 5,
"tags": "post formats"
} |
How to tell if an option has been created vs an empty option?
What is the method to test for the existence of an option in the database?
Not the value of the option, just that the option exists. | Options that don't exist get the fact of their non-existence cached in memory when you attempt to get them. So you can check that cache to determine the difference.
$value = get_option('example');
$notoptions = wp_cache_get( 'notoptions', 'options' );
if ( isset( $notoptions['example'] ) ) {
// option does not exist
} else {
// option exists, $value is legit
} | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "plugin development"
} |
Apply html elements in php statement
I know this is probably going to sound like a beginner question ... to which it is in some sort.
I have this statement in my one plugin that i am working on:
add_post_meta($newpostid, 'name', $formdata['your-first-name'].$formdata['your-last-name']);
Which in turn will add FirstnameLastname in a custom field.
What i would like to do is add a space between the first and last name like this:
Firstname Lastname
I have tried using statements such as:
add_post_meta($newpostid, 'name', $formdata['your-first-name']. echo ' ' . $formdata['your-last-name']);
But obviously that is not going to parse correctly. Is there any Idea on how I can achieve this?
Any help would be welcome. :) | Do this instead:
add_post_meta($newpostid, 'name', $formdata['your-first-name'] . ' ' . $formdata['your-last-name']);
This uses PHP string concatenation to add a space; the `echo` isn't necessary in in this instance because WP will do it itself, later. You probably can't force a non-breaking space there, either, since WP will escape all its output. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, php"
} |
"After file loaded" action
I have a plug-in that allows for repeatable fields. There will be an image and the image description. The description allows for tinyMCE editing. There are obviously problems with this, but I think I have found a solution.
What I am trying to do is save the metadata after the user closes the thickbox and the image filed is populated. I'm wondering if there is an 'add_action' hook that I can use to accomplish this. Any ideas? | I used the `send_to_editor` method in JavaScript. The end result ended up looking like this:
window.send_to_editor = function(html) {
// logic to save via AJAX goes here.
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, custom post types, custom field, attachments, tinymce"
} |
Preview page/post revisions without overwriting current content
Is it possible to add or update a Post/Page without it overwriting the current content that it on there? I need to make some edits to a page, but I need to have someone review it before I can publish it and I don't want to overwrite the current content that is up there.
Any suggestions? | WordPress has built in Revision Management.
You can set the saved revisions to a custom number in the wp-config.php file in your installation.
define( 'WP_POST_REVISIONS', 30 );
**NOTE:** You should be aware of the »autosave« mechanism, which also sets post revisions. So leaving a tab open for 1 hour with a Post Revision interval of 6minutes and a Revision limit of 10 revisions, might destroy your whole history.
!enter image description here !enter image description here !enter image description here
**NOTE:** There's also the Role »Contributer«, which is _not_ allowed to publish posts. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, pages, content, draft, review"
} |
why the posts queried from sql is more than those showed on the page?
i am using WordPress multisite, the issue i face is that the posts queried from sql is more than those showed on the page, the details is as follows:
mysql> select count(*) from wp_137_posts where post_type='post';
+----------+
| count(*) |
+----------+
| 32 |
+----------+
1 row in set (0.46 sec)
here i find there is 32 posts to the blog whose id is 137
but in fact when i open that blog, i can find only 30 posts including both published and draft posts.
why there are not 32 posts when i open my blog? | Autosaves get stored with `post_type=inherit` and other objects such as menus are also stored in the posts table. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, multisite, database, count, hacks"
} |
Wordpress shows my picture in admin bar
I have installed wordpress on my dev but during installation, I did not upload any picture for my profile but on admin bar, it is showing my picture. How I can remove it? | That's a gravatar. Change your user email to another email that is not registered at gravatar, or change the image to a blank .jpg at < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "images, wp admin"
} |
Prevent reload confirmation after AJAX save
I am saving information in the admin panel via ajax. The problem I'm running in to is the "Are you sure you want to navigate away from this page" popup appear, even though everything has been saved. Is there any way to flag the page as saved? | You can try clearing window.onbeforeunload with the following Javascript after your AJAX save:
window.onbeforeunload = null; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 4,
"tags": "custom post types, custom field, admin, ajax"
} |
why there are so many posts whoes post_type is revision? will these records waste too much database space?
from the following data we may know there are only 30 records which are meaningful, and there are 92 records of revision post_type which can not be shown on the blog.
so will these records waste too much database space?
is it recommended to save such kind of revisions? (btw, i may edit my blog oftenly)
mysql> select count(*),post_type, post_status from wp_137_posts group by post_type, post_status;
+----------+-----------+-------------+
| count(*) | post_type | post_status |
+----------+-----------+-------------+
| 1 | page | publish |
| 2 | post | auto-draft | // also, should i delete this record?
| 30 | post | publish |
| 92 | revision | inherit |
+----------+-----------+-------------+
4 rows in set (0.24 sec) | Every time you edit a post/page, WordPress creates timely revisions of it. Check the Firebug console for the requests that are sent at regular intervals when you are on the edit page. They are useful if you lose the post content at some point and want to get back to an earlier version of the post. Once you publish the final version of the post then you can delete all the post revisions.
And yes, they do take up your database space!
**Solution:** There's an excellent answer over here. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "posts, database, post status, post type, revisions"
} |
Defining a custom 404 for non-WordPress parts of site
I have a site with WordPress located in a directory under the root. The root directory contains the main files for the non-WordPress part of the site. Wordpress is included in all of these pages by inclusion of wp-load.php and this is working fine.
My question is about how best to handle 404 errors generated in this external part of the site. I'd like to have a single 404 page and ideally to use the WP 404 page for this purpose.
Is this possible and does anyone know how it could be accomplished? | Set the WordPress `index.php` as error handler in your `.htaccess` (if you are using Apache):
ErrorDocument 404 /wp/index.php
Make sure the path matches the path to the WordPress directory. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "redirect, 404 error"
} |
Wrapping a function in html tag and return?
I am creating a shortcode. The shortcode will output a list of pages with the wp_list_pages() function. I am using the ('title_li') parameter and the list headline will be removed, because it is left empty and the "ul tag" will be removed as well, which is not desired.
<
Now I am trying to wrap it in ul tag again. This is what I am trying but it will return list of pages in "li" with out the "ul tag".
function sitemap_function() {
$return_string .= "<ul>";
$return_string .= wp_list_pages('sort_column=menu_order&title_li=');
$return_string .= "</ul>";
return $return_string;
}
function register_shortcodes() {
add_shortcode('sitemap', 'sitemap_function');
}
add_action('init', 'register_shortcodes');
Hope someone can help me out here. Thanks in Advance. | you need to sert the `'echo'` parameter of `wp_list_pages()` to `0` (zero):
$return_string .= wp_list_pages('sort_column=menu_order&title_li=&echo=0'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "shortcode, wp list pages"
} |
Implementing "Random" to custom-background
I have a client site that requires a random background image. I figured that `custom-background` would have something similar to `custom-header` for randomizing which image is selected, but alas it does not seem to be the case.
Does anyone have experience doing this, or know what direction would be best to extend `custom-background`? Or would the better approach be to ignore `custom-background` and create my own background theme support (I severely frown upon this method, but 'the easy route' is always there). | I created a theme like this sometime ago using backstretch script < very light and easy to set.
But note that if you want to allow the user/client to change/order the images you will need to create a theme panel/options. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom background"
} |
Multiple orderby values in WP_Query
I'm trying to come up with a query to sort by multiple orderby values. Here's what I have so far:
$dept_id=2;
$query=new WP_Query(array(
'post_type'=>'wpcontactus',
'nopaging'=>true,
'post_status'=>array('publish', 'pending', 'future'),
'meta_key'=>'wcu_dept',
'meta_value'=>$dept_id,
'orderby'=>'title',
'order'=>'ASC'
));
I'm trying to query a custom post type, and within that post type, query a meta value.
Then, I'd like to first sort by `menu_order` ascending, then by a custom meta value `wcu_lastname` ascending. However, the orderby value didn't seem to be able to take an array.
How can I order the query using multiple orderby values? | $query=new WP_Query(array(
'post_type'=>'wpcontactus',
'nopaging'=>true,
'post_status'=>array('publish', 'pending', 'future'),
'meta_query'=>array(
array('key'=>'wcu_dept','value'=>$dept_id, 'compare'=>'='),
),
'meta_key'=>'wcu_firstname',
'orderby'=>'menu_order wcu_firstname',
'order'=>'ASC'
));
By using what @kaiser suggested and the `meta_query` option, I was able to get the query I was looking for. | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 21,
"tags": "custom post types, custom field, wp query"
} |
Permalinks not working (404) for the 'item' post type
I have searched various forums and blogs, however I could not find the isuse so far, neither a way to fix it.
`item` does not seem to be a wordpress-reserved word.
My custom post type registers just fine. I can work with it from admin, edit, delete, preview, assign terms, publish... .
However any time I try to visit the permalink (e.g. ` it goes to the 404 page!
Had someone tried this out with the latest version of WP? | Try updating your permalinks in the backend under Settings -> Permalinks. Be sure to "Save Changes" even if you don't make any changes. It seems to refresh the permalinks.
Also verify the "slug" is set properly when you're setting up your post type. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, permalinks, 404 error"
} |
Failed to connect to FTP Server 127.0.0.1/:21
Tried to install a wordpress plugin on my local machine:
> To perform the requested action, WordPress needs to access your web server. Please enter your FTP credentials to proceed. If you do not remember your credentials, you should contact your web host.
Hostname 127.0.0.1
FTP Username macusername
FTP Password macusernamepassword
Connection Type Connection Type FTP
When I click proceed, I get this:
> Failed to connect to FTP Server 127.0.0.1/:21
Why doesn’t WordPress work with my FTP data? | Depending on your version of OS X, you will need to configure and run FTP and open a port in the firewall. It's best if you google your OS X version - 10.6, 10.7, etc. - specifically and find the docs necessary to set up FTP and Sharing.
You also need to realize the security implications of opening up FTP to your local machine; someone port scanning your IP may be able to find your FTP port.
It's often easiest - and the best for security - to simply download the plugin and move it into the plugins folder. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "local installation, ftp"
} |
How i can get the URL?
How i can get the base URL in the wordpress? `get_bloginfo('url')` returns me the current URL. I just want the base URL e.g ` not any **?page_id=123** with it | Use site_url
`<?php echo site_url(); ?>`
<
Or get_site_url
`<?php echo get_site_url(); ?>`
<
Or even home_url
`<?php echo home_url(); ?>`
<
which returns the home URL for the site.
_**Check the doc links for differences in available parameters._** | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, urls"
} |
How to Change the Default Home Page for the WordPress Dashboard?
Is it possible to change the Default "Home" admin page when logging into the WordPress Dashboard?
I thought about a couple of possibilities...
1. Substitute the content on the Dashboard home page with custom content.
2. Redirect to a different admin page within the WordPress Dashboard upon successful login.
If it is possible to do either of the two options, what hooks would you recommend utilizing? | Easy enough, decided to just do the redirect option. I used the `wp_login` action hook. You could also probably use this for redirecting your users to ANY page on your website. You can also check user capabilities from the `$user` Object passed in as a function parameter if you want to send different user levels to different pages.
/* Redirect the user logging in to a custom admin page. */
function new_dashboard_home($username, $user){
if(array_key_exists('administrator', $user->caps)){
wp_redirect(admin_url('admin.php?page=c2c-overview', 'http'), 301);
exit;
}
}
add_action('wp_login', 'new_dashboard_home', 10, 2); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 11,
"tags": "admin, wp admin, login, dashboard, authentication"
} |
List custom field values in alphabetical order without repetition
The function below lists the custom fields as in this example:
* Frank Capra
* Alfred Hitchcock
* Woody Allen
* Woody Allen
* Frank Capra
* Pedro Almodóvar
* Pedro Almodóvar
I introduce the values in alphabetical order and without repetition. Eg:
* Alfred Hitchcock
* Frank Capra
* Pedro Almodóvar
* Woody Allen
* * *
This is the code:
<?php
$movie_reviews = get_posts('numberposts=-1&orderby=post_name&order=ASC');
foreach($movie_reviews as $post) : setup_postdata($post);
?>
<li>
<?php $director = get_post_meta($post->ID, "director", $single = true);
if($director !== '') {
echo $director;
} ?>
</li>
<?php endforeach; ?>
</ul>
Is this possible? Grateful for any help. | You could do a custom SQL query:
global $wpdb;
$query = "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'director' ORDER BY meta_value;";
$directors = $wpdb->get_results( $query );
foreach( $directors as $director ) :
echo $director->meta_value;
endforeach;
one thing to note here though is that since you're not querying the associated posts, you could get values that belong to unpublished posts, if that's a concern. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom field, list, meta value"
} |
how to add new .webm mime types
i tried google but no success yet.
I am trying to upload .webm and .ogg video types in wordpress ( for html5 video ofcourse) I am getting error like
Baki fula.webm” has failed to upload due to an error
Sorry, this file type is not permitted for security reasons.
tried plugins like
1. PJW Mime Config
2. AP Extended Mime Types
but doesnot seem to work either. I am working locally with easyphp in windows 7 in wordpress 3.4.1.
Can anyone plase help me in solving this issue. Any help is appreciated | The WebM file format isn't known to WordPress by default, you have to add it.
add_filter( 'upload_mimes', 'custom_mimes' );
function custom_mimes( $mimes ){
$mimes['webm'] = 'video/webm';
return $mimes;
}
The .ogg file format is known to WordPress as audio/ogg, if you're wanting to do video with it, the correct extension is .ogv. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "uploads, server, videos"
} |
Is it possible to send blog posts via email to subscribers?
Would like to be able to send the blog post in an email mail to my subscribers, this would be great if it can be achieved through a plugin. | There are many options. Subscribe2 is very popular, although I've never been a fan. <
MailChimp and FeedBurner both offer RSS to Email delivery which can be used for this as well.
JetPack includes a subscribe to new posts function as well: < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, posts, email, blog, html email"
} |
Creating a Freemium plugin in the WordPress Repository
I would like to create a freemium model plugin and put it in the WordPress repository.
I've been going through the rules for uploading plugins into the repository, but haven't got a clear indication on whether this is allowed or not, so I am searching for clarification here.
<
I also came across WYSIJA which is a freemium plugin, and it is hosted in the repository without any problems, so I'm assuming it's ok to do this, however I would like some definitive reply on this. | Define "freemium".
If you mean a free plugin that attempts to up-sell to a paid-for plugin, sure, that's allowed. As long as you do it within the guidelines you've already found.
If you ask a more specific question, you'll get a more specific answer. What do you want the plugin to do that you think may not be allowed? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -3,
"tags": "plugins"
} |
How can I upload a csv file into Wordpress?
I have some customers in my site. My ERP system has customers along with their price reduction level. I extracted from my ERP the list of customers' Tax IDs and price reductions levels and I want to upload it in a custom table in Wordpress. Any idea how to automate that? | I'm not really clear on what you want to do, but there are several CSV import plugins. <
But if you need to link the imported data to specific, existing posts, then it is more of an MySQL question and not purely WordPress. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "uploads"
} |
How to get full content including template HTML
I'm looking to get the page content between the header and footer (as Wordpress already does) that includes the template HTML (as this is going to be an AJAX request).
Is there a function that will allow me to do this? The only things I have found so far all relate to just getting the content straight from the database.
It would also be great to get this content via the pages' permalink. | Here's how to check if the current page is being loaded via an AJAX request, use this to exit from the header/footer/whichever parts
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
return; // it's an ajax request ABORT!!
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "permalinks, templates, ajax, page template, content"
} |
Get multiple db prefix with $wpdb
I have installed wordpress with question2answer as a single signon. The database created by wordpress with wp_ prefix and question2answer prefix is qa_
Now wordpress tables doesnt required to define prefix with $wpdb-> but how can I get question2answer table without query with prefix like I prefer something like as below
$titles = $wpdb->get_results("
SELECT title
FROM qa_posts // with qa_ prefix
");
Its giving output of the title but i want something like below code where I dont have to define qa_ prefix same like wordpress default tables
$titles = $wpdb->get_results("
SELECT title
FROM posts // without prefix
"); | Write a function that uses $wpdb->prefix as a fallback. Something like this:
function wpse65880_table_with_prefix($table) {
// should define array in config file, rather than hard coding
$my_tables = array("table1", "table2", "table3", "table4");
if (in_array($table, $my_tables)) {
// "qa_" should also be a config file setting
return "qa_" . $table;
}
else return $wpdb->prefix . $table;
}
$table_name = wpse65880_table_with_prefix('post');
$titles = $wpdb->get_results("
SELECT title
FROM $table_name // reflects current prefix
"); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "customization, table"
} |
Get Advanced Custom Fields values before saving
Basically, I need to alter the info the user inputs into an advanced custom fields textbox before it is written to the database but I don't know how to grab it. I can only get it after it has been written to the meta portion of the database by using `get_field()`. | Edit - This answer is no longer accurate for the current version of ACF, see their documentation
Use the `acf_save_post` hook.
function my_acf_save_post( $post_id )
{
// vars
$fields = false;
// load from post
if( isset($_POST['fields']) )
{
$fields = $_POST['fields'];
}
// ...
}
// run before ACF saves the $_POST['fields'] data
add_action('acf_save_post', 'my_acf_save_post', 1);
// run after ACF saves the $_POST['fields'] data
add_action('acf_save_post', 'my_acf_save_post', 20); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "post meta, advanced custom fields"
} |
Increment value (value = value+1) of $wpdb->update
This sql query
$wpdb->query("UPDATE log SET total=total+1 WHERE id='1')");
How do I turn it into $wpdb->update() statement?
Ex.
$wpdb->update('log', array('total'=>'total+1'), array('id'=>'1')); | You don't. Not with the WPDB update() function. The update function assumes that the values of the columns are strings. You can override that with the format parameter, but that only allows %d, %f, and %s (integer, float, string). It doesn't allow operations on columns like total+1.
You'd have to use the query() function directly to do your update. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "mysql, wpdb"
} |
Upgrading problem
I am using a CentOs server that managed with Plesk panel. All domains have different users. I have 2 different installation of WordPress. One is installed from FTP and the other one is installed from Plesk.
WP installed from FTP cannot be updated from admin panel of WP. The error is;
> Downloading update from <
>
> Unpacking the update…
>
> Could not copy files.
>
> Installation Failed
WP installed from Plesk can be updated successfully from admin panel of WP. So I check the permissions and file ownership and did the same as WP installed from Plesk. But it doesn't fix the issue.
Any suggestion?
PS: I know how to update from FTP. PS2: I won't disable 'define('FS_METHOD', 'direct');'. | I fixed the problem by changing file ownership to apache:apache | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "permissions, automatic updates"
} |
Taxonomy-{taxnonomy}.php is not working
I have just created a custom post type (portfolio) for a wordpress website. I also have added a Custom Taxonomy called (portfoliocategory).
I have created a archive page for my Custom Post Type (archive-portfolio) which is working properly, but I need help with Custom Taxonomy Template, I have created taxonomy-portfoliocategory.php but it is showing the default archive page and not showing the taxonomy page template!! | In the absence of further information this diagram should explain the template heirarchy system:
!enter image description here
click for bigger
Thus if we have a term 'example' then example.com/portfoliocategory/example will show portfolio posts using the template `template-portfoliocategory.php` and if that isn't found it willl use `taxonomy.php` and then `archive.php` and finally `index.php` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, custom taxonomy, taxonomy"
} |
Can WordPress Plugin Directory Cache Delay the Upload of Images?
I've updated my plugin and I can see the updated text on the plugin page but I don't see any of the screenshots or header image. Is it possible that the cache will move the image files over later? Or did I do something syntactically wrong so they are not showing up?
FYI I did run my readme file through the WordPress readme file validator. | Typically any plugin changes take 15minutes to be reflected on the plugin's pages in the repo.
Did you upload the screenshots and header image to the /assets/ folder of the repo? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, plugin development, wordpress.org, cache"
} |
problems exluding categories
I have done this before but for some reason, it is not working and I can't figure out why. All I am trying to do is exclude some categories from the blog page. I thought this would be a simple matter. I have the index.php file open, and before my loop, I did this
query_posts( $guery_string . '&cat=-6' )
if (have_posts)......rest of loop here.
I have even tried adding the global $query_string; on top but nothing I do will get rid of category 6. Does this method no longer work in the latest version of wordpress? | **Don't use`query_posts()`**. Filter `pre_get_posts` instead:
function wpse65927_filter_pre_get_posts( $query ) {
// If this is the blog posts index,
// and if this is the main query,
// exclude category 6
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-6' );
}
}
add_action( 'pre_get_posts', 'wpse65927_filter_pre_get_posts' );
Put the above hook and callback in `functions.php`. Don't modify any of your template files, including `index.php` or `home.php`, at all. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "exclude"
} |
Is there a maximum number of author for a blog?
I am building a WP blog which will feature the work of many artists and I would like to show, for each post, the artist bio.
Since it is possible for an artist to have many posts over time on the blog, I don't want to insert the bio info directly inside the post and instead use a custom function to show it. This is why I was thinking about using the author meta data to store the info about the artist.
Doing this brings 2 questions:
1. is there a hard limit to the number of authors (or reason not have a lot of authors)
2. is there a reason not to do it this way? (or a better way to do it) | 1. You can have as many authors as you'd like.
2. If the artists are not the authors of the blog posts, I would consider using a custom taxonomy instead, because it would be a more accurate model.
**EDIT** As it's been pointed out in the comments, taxonomies don't have built-in meta data, and custom post types or users are sometimes easier to handle. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "author template, multi author"
} |
I need a custom search page to lead to search.php but it goes to index.php
I built a custom search page with a form like:
<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
trouble is I want the results to appear in search.php
whereas I m led to index.php
How can I force to always go to search.php ? | If I get it correctly Wordpress loads the search template dynamically by the parameters delivered to it. Specifically the `s` parameter. Meaning if you try to send the user to the ` you'll get 404 error page.
For now the only workaround I can think is to create a function which is hooked to the `init` action hook that listens for a parameter in order to load the right file. The function must reside in the `functions.php` of your theme (assuming you are developing a theme). The function goes like this:
function load_custom_search_template(){
if(isset($_REQUEST['custom_search'])){
require('my_search.php');
die();
}
}
add_action('init','load_custom_search_template'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "search"
} |
Use safety filters even if after applied intval?
I have some values to save into postmeta and usermeta table. Before save, I already done this: `$value = intval($value)` . I think this is enough. But I see some plugins still use filters on those numbers. I want to make sure that I can do with `intval` and without safety filter. | `intval()` behaves sometimes a little bit counter-intuitive when then value has leading zeros or when it is a mathematic expression. The result should always be **safe** , but is not always what you might **expect**.
A simple example:
intval( '9223372036854775808' );
will never return this value, because even 64 bit system cannot handle such a large number. You get `9223372036854775807` on a 64 bit system and `2147483647` on 32 bit.
But if you use:
preg_match( '~\d+~', '9223372036854775808', $matches );
`$matches[0]` will return this number unchanged.
So, it depends on the values you expect. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "filters, customization"
} |
How to add pagination to category templates
I have a function which named `kriesi_pagination`, which is a function for showing page numbers in php. I copied the code into the `functions.php` for my site.
The I call this function in the `index.php` file for showing the page numbers on the index page of my site. I use this code like this inside `index.php`: `<?php kriesi_pagination(); ?>`
What should I do if I want to show the page numbers in other places such as on category pages? It just shows the page numbers in home page of site not any other places.
I want to have page numbers for the categories like sports, musics, technology, etc. | You're asking "how to use template tags". Actually there's a Template Tags page in the Codex.
> Template tags are used within your blog's Templates to display information dynamically or otherwise customize your blog, providing the tools to make it as individual and interesting as you are
\- Source: Codex entry about Template Tags
As you've already done, you can write custom Template Tags (basically just php functions) - aside from those provided by core, like `wp_head()` or `the_content()`.
When you want to have specific functions on specific pages, simply open up your theme folder, choose the right template that fits to this specific request and add your Template Tag. To see what template is used when, just take a look at the Template Hierarchy diagram in Codex. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pagination, paginate links"
} |
Check if a different page has any attached images
I am trying to make a notification function for a user's account dashboard that displays if they have not added any images to their profile's gallery. I found this page, which is a function that checks if the CURRENT page has any attachments: Check if post/page has gallery?
How can I change that to check by a specific post ID, i.e. a function that will check if post 2 has a gallery or not? | $args = array(
'post_type' => 'attachment',
'numberposts' => null,
'post_status' => null,
'post_parent' => $post_id
);
$attachments = get_posts($args);
if ($attachments) {
echo "attachments rock!";
}
}
If you want to make sure the atachements are an image, you would use:
if ( $attachments and wp_attachment_is_image( $post_id ) ) {
echo "attachments rock!";
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, gallery"
} |
show author avatar
I have modified the loop.php file to add some comment stuff in. I wanted to show a comment off a link which is working just fine. Now I went to make that comment show more detail by putting the author avatar. So my code looks like this. It does display the default avatar but is should display my image which it is not.
$comments = get_comments( array(
'post_id' => $post->ID,
'number' => '1'
) );
foreach ( $comments as $comment ) {
echo get_avatar( get_the_author_meta( 'ID'), 32 );
echo $comment->comment_author . ' says: ';
echo '<hr />';
echo $comment->comment_content;
} | The get_the_author_meta function gets the Post's author ID, not the comment-author's information.
The get_avatar() function is perfectly capable of accepting the comment object whole and working it out from that all by itself. So just call it like so:
`echo get_avatar( $comment, 32 );` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "avatar"
} |
select wordpress custom post type
I have one wordpress theme which contain Custom Post Type.
And in my theme I can add that as a page which show some different URL.
Now when I call a WP function `(is_page('some-page'))` for wordpress page so this code is working.
Now for my Custom page I write that same code but it's not working.
So my question is how can we call this kind of specific custome page in wordpress. | Please check Wordpress theme hierarchy and you will know which file you need to create for custom post types :-)
<
Most likely you are after archive-$posttype.php | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
Nothing happens on Wordpress Update command
I made a function in Wordpress, which should update one field **status** to **0**. But no changes are made to the database. I don't know what is the reason. Can someone please help. I tried looking into wordpress own **wp-db.php** , and seen that the same array is going there as well.
function updateData($temp_array){
global $wpdb;
$temp_array = array('status', '0');
echo $wpdb->update( 'wp_testing_options', $temp_array, array( 'id' => 1 ) );
} | this:
$temp_array = array('status', '0');
should be
$temp_array = array('status' => '0'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, mysql, wpdb"
} |
Add Submenu Link in add_submenu_page That Opens in a New Window
How can I add a sub menu link using add_submenu_page that will open a new window (`target="_blank"`) instead of opening in the current one (default behavior)? | This has to be solved:
* with an unconventional submenu manipulation, provided by @t31os in this Answer
* and some jQuery
add_action( 'admin_menu', 'wpse_66020_admin_menu_new_item' );
add_action( 'admin_head', 'wpse_66020_add_jquery' );
function wpse_66020_admin_menu_new_item()
{
global $submenu;
$submenu['index.php'][500] = array(
'<div id="wpse-66020">Go to WPSE</div>'
, 'manage_options'
, '
);
}
function wpse_66020_add_jquery()
{
?>
<script type="text/javascript">
jQuery(document).ready( function($) {
$('#wpse-66020').parent().attr('target','_blank');
});
</script>
<?php
}
* * *
**Resulting in this:**
 in a local installation. Do not just upload something you have not tested before.
2. You could manage the directory or your whole installation with a version control software like Git or Mercurial. This way, you could reset the directory content to an earlier state, it would take just one command in a terminal. And some time to learn these tools, of course. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes"
} |
409 error (Conflict) when trying to insert an image into a post
I've uploaded a Wordpress site to the live server and I get this error whenever I try to insert an image into a post:
> **Conflict**
> The server encountered an internal error or misconfiguration and was unable to complete your request.
> Please contact the server administrator, root@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.
> More information about this error may be available in the server error log.
> Apache/2.2.0 (Fedora) Server at www.sitename.com Port 80
Just to be clear - the error appears only when i try to **insert** the image into the page. I can upload it to Media just fine. Also, it happens with external images as well as local ones. It seems enough to have an IMG tag with something in the SRC attribute for this to happen.
It's very weird, I've installed Wordpress on many servers and never had this happen before. | The problem was with ModSecurity settings blocking some of the Wordpress scripts. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "images, errors"
} |
Get user role by using user_id in buddypress
I need to classify the user according to their role, so I need to find the user role by using the user_id alone (not only for logged in users but for all the BP users).
Something like this `$user_role=role($user_id);` | Try this function:
function get_user_role($user_id){
global $wpdb;
$user = get_userdata( $user_id );
$capabilities = $user->{$wpdb->prefix . 'capabilities'};
if ( !isset( $wp_roles ) ){
$wp_roles = new WP_Roles();
}
foreach ( $wp_roles->role_names as $role => $name ) {
if ( array_key_exists( $role, $capabilities ) ) {
return $role;
}
}
return false;
}
I've not included any exception handling like whether the user exist or not, so you can do it yourself or in case you are getting the user ids list wont even be necessary. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "search, buddypress, user roles"
} |
Why cant you place the Loop outside of the index.php?
This may sound like a stupid / noob question. But I'm curious to wonder as to why you can't insert the wordpress php loop functions outside into say a blog.php file but you can in a index.php file?
For instance, when I try running all the loop code in say a blog.php file, and linking the pages up nothing shows. I've tinkered with the reading settings as well just to make sure nothing is off. However, when I move the loop php code into an index.php file the blog page will then display the pages.
Am I missing something, or is there a way to insert the loop into a different .php file instead of the index?
-Thanks, | That's because of the Template Hierarchy WordPress uses. The blog.php you're trying to use isn't part of the default templates WordPress uses. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "loop"
} |
How only display all post related to category
I'm trying to make a custom template for my category pages that only pulls in post under a specific category. At the moment, I am only able to pull in all post and not category specific...
My code so far....
<?php
//Identify current Post-Category-ID
foreach((get_the_category()) as $category)
{
$postcat= $category->cat_ID;
$catname =$category->cat_name;
}
?>
//Print category ID
<h2><?php echo $catname; ?></h2>
<?php
$thumbnails = get_posts();
foreach ($thumbnails as $thumbnail) {
if ( has_post_thumbnail($thumbnail->ID)) {
echo '<li><a href="' . get_permalink( $thumbnail->ID ) . '" title="' . esc_attr( $thumbnail->post_title ) . '">';
echo get_the_post_thumbnail($thumbnail->ID, 'full');
echo '</a></li>';
}
}
?> | You've already got code to figure out which category you want to show posts from, here is how you would grab all the posts in that category:
// create a query to grab our posts in category of ID $postcat
$q = new WP_Query(array( 'cat' => $postcat));
if($q->have_posts()){
// foreach post found
while($q->have_posts()){
$q->the_post();
// code for displaying each post goes here
}
// cleanup after the WP_Query, reset the post data
wp_reset_postdata();
} else {
// no posts were found!
}
Never use `query_posts` to do your queries, always check if any posts were actually found, and always cleanup after yourself.
For more arguements for queries, see here:
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "posts, categories, templates, post thumbnails, listing"
} |
Theme compression/ minifying or W3 Total Cache - which should I use?
I run a WP3.x Multisite setup. One of the themes I use on a site has options for minifying, using Gzip compression and using data URIs for images (not sure what the latter function is or does). In the past, I have used W3 Total Cache, in combination with Cloudflare.
What is the best practise here - should I defer to the theme's compression settings, or is it prudent to let W3 Total Cache take care of everything? | I find that W3 Total Cache works well for me in doing minifying and gzipping. (I'm not sure about the others.)
More generally, if there's a plugin that does something, I use the plugin. It's _very_ rare to see a do-it-all theme do something better than a specialized, single-function plugin, particularly when that plugin is of the caliber of W3 Total Cache. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "customization, plugin w3 total cache, cache, compression"
} |
Redirect Main Site to Subsite in Multisite Wordpress
I have multi-site wordpress, I want to redirect the main site to one of the sub-site but redirection in .htacecss gives error. Is there any way to redirect a main site to its sub-site. That looks not possible but I am not a wordpress expert so just verifying.
The redirect should be like
redirect 301 www.example.com/main-site www.example.com/main-site/sub-site
Or if there is any other way to do that? | You can use the `parse_request` action to accomplish this. Simply enable this plugin on your primary blog. Place the following code in a .php file and upload it to your plugins directory.
/*
Plugin Name: Redirect Main Site To Sub-Site
Description: Redirect 'main-site' to 'main-site/sub-site/'
Version: 0.1
Author: WPSE
Author URI:
License: GPL2
*/
add_action('parse_request', 'redirect_to_sub_site');
function redirect_to_sub_site(){
global $wp;
#Sniff requests for a specific slug
if('main-site' === $wp->request){
#The URL to redirect TO
$url = '
#Let WordPress handle the redirect - the second parameter is obviously the status
wp_redirect($url, 301);
#It's important to exit, otherwise wp_redirect won't work properly
exit;
}
}
Let me know if you have any questions. | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 11,
"tags": "multisite, redirect"
} |
I need to disable Disqus comments pre-approval, but i can't find where
I've tried contacting Disqus support but they haven't answered. I need to disable pre-approval for comments but i can't find where to set that option. Could anyone help me? Thanks. | Just found the solution: you gotta disable Disqus 2012 features on your website (pre-moderation haven't been implemented on Disqus 2012 yet, despite being almost 2013 already).
Here's the article where i found the solution: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments, disqus"
} |
I submit a non-latin string value and it returns like %23%24%%%
I am sorry I am anaware of the exact terms. I submit in non-latin a string and in the next page the value "%23%24..." returns. How can I retrieve the correct value? Thanks. | urldecode() solves this problem, as suggested by @BrianFegter | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "characters"
} |
Customized wp_new_user_notification
Customized wp_new_user_notification
I'm kind of inexperienced with it comes to editing Wordpress functions, yet i'm currently trying to customize `wp_new_user_notification` in order to personalize the email that administrators and users receive once they register. I'm aware there's some plugins that allow this kind of customization, but I would rather spend some more time on a problem and try to learn/understand it, rather than just install a plugin. Hence, I've placed this function in my `functions.php`, and I believe I'm supposed to add one or more filters, such as:
add_filter('myfunction', 'wp_new_user_notification', ?, ?)
or maybe not. I've read and attempted to follow several tips/tutorials/questions (such as for example), but no matter what I do, I keep receiving emails with standard text/contents (as if my functions is not being considered by Wordpress).
Can anyone help me solve this problem? Thanks in advance! | You can only override pluggable functions in a plugin, not via `functions.php`. The function is already defined when `functions.php` is loaded, which is why your overriding function is skipped. Move the code to your own plugin to enable it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "functions, pluggable"
} |
WP_Error message
`PHP Notice: Object of class WP_Error could not be converted to int in /var/www/vhosts/hayhauler.co/httpdocs/wp-includes/functions.php on line 2568, referer:
I'm not even sure where to start with this or the right question to ask. I know that it is preventing me from posting some information into a database using this:
$wpdb->query($wpdb->prepare(
"
INSERT INTO $wpdb->quotes
(user_ID,origin,destination,broker_ID,quote_ID,estimatedship)
VALUES (%d,%s,%s,%d,%s,%s)
",
$user_id,
$origin,
$destination,
$brokerID,
$brokerID.'-'.genRandomString(),
$estimatedship
));
And this error follows it:
`mysql_real_escape_string() expects parameter 1 to be string, object given in /var/www/vhosts/hayhauler.co/httpdocs/wp-includes/wp-db.php on line 789, referer:
Any help or direction would be greatly appreciated. | One of the variables you're trying to pass into `wpdb::prepare` is a `WP_Error` object. `WP_Error`'s are like exceptions mixed with return codes: some functions in the WordPress API return WP_Error objects to tell you something went wrong (like `get_terms`).
We'll need to see more of your code to be more specific, but you can test for them with the function `is_wp_error`. So, let's say $brokerID was causing the issue:
<?php
$brokerID = some_function_that_gets_broker_id();
if(is_wp_error($brokerID))
{
// do stuff to fix it
}
else
{
// Your original code goes here.
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "errors, fatal error"
} |
How can I implement faceted search with Wordpress 3.x?
I would like to allow visitors to a site to search for posts based on various attributes (categories, tags, custom fields).
I have tried using Solr, but this doesn't appear to work.
I tried using the MySolrServer plugins for a local instance of Solr and a hosted instance, but the plugin doesn't appear to work.
I also tried using Solr for Wordpress, but the plugin wouldn't enable.
I don't want to use something like Taxonomy Drill-down.
Bearing those points in mind, how can I now try to implement true faceted search that will enable site visitors to search for posts based on attributes? | One of my favorite ways to do this is to use the Factious plugin. It is still fairly basic and only has a Sidebar widget by default. However, it has an extenable API(ish thing) that lets you write code to place it elsewhere.
The reasons why I like it are this:
* Written by people who know what they are doing (Code for the People WordPress VIP Partners)
* Simple
* Keeps search within WordPress. For me this is huge I'm always skeptical about using third party services.
* Extendable
Not sure if that is what you are looking for but none the less it should be a tiny bit easier than writing custom `WP_Query` and will be a good "get your feet wet" into WordPress' Objects. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "search, navigation"
} |
Action hook for editing post
I'm looking for the add_action() hook for when a current post is edited and saved. I know there's `edit_post` and `save_post`, but I'm looking for something that ONLY fires when a current post is edited, not created or altered in any other way. | Not a real answer.
Take a look the files that use save_post and edit_post
It will lead you to the hook post_updated
Take a look and see if you can find a hook you need. Keep in mind that you might need to do some checks in the hook.
You'll figure it out. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "actions"
} |
Add Permalink to Post Thumbnail, syntax code issues
I´d like to link `the_post_thumbnail` by using the `the_permalink`.
I do this ( **It Works without link** )
<?php $args = array( 'post_type' => 'xyz', 'posts_per_page' => -1, 'orderby' => 'rand' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_post_thumbnail('wine-flow', array('class' => 'item'));
endwhile; ?>
And I´d like to do further this: ( **Syntax Error** )
<?php $args = array( 'post_type' => 'xyz', 'posts_per_page' => -1, 'orderby' => 'rand' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
<?php the_post_thumbnail('wine-flow', array('class' => 'item')); ?>
</a>
endwhile; ?>
Thanks
ogni | That is because you haven't close php before anchor tag
<?php $args = array( 'post_type' => 'xyz', 'posts_per_page' => -1, 'orderby' => 'rand' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
<?php the_post_thumbnail('wine-flow', array('class' => 'item')); ?>
</a>
<?php
endwhile; ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, post thumbnails, code"
} |
Securing Admin Accounts - Username Discovery
We've had Limit Login Attempts installed for some weeks now, and the number of brute force attempts occurring on wp-admin/wp-login is pretty amazing. At first the attempts were all with the username "Admin," which doesn't exist on our site, so I considered it an annoyance but not much of a threat. However, now we're seeing lockouts occurring with other named admin user accounts and I'm completely at a loss of understanding for how the attackers are deducing the usernames of these accounts.
No content on our site is authored by anyone in particular and I can't find any other location on our site where these usernames are publicly published.
Any idea as to how usernames might be discoverable? | If you have pretty permalinks enabled WordPress will redirect all calls to `/?author=1` to the author archive with the user name, eg.: `/author/bob/`. And then the visitor will know the author name.
Use Login Lockdown, that plugin does not reset accounts, it will block IP addresses. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 9,
"tags": "admin, wp admin, security"
} |
Is there a capability for managing plugin options?
I have an Editor user that I want to let use a plugin's options without being an Administrator.
I can use $user->add_cap but can't tell if any particular capability relates to the permission to edit plugin options. The plugin in question is Redirection, if that makes a difference. | The part of the capability is the job of the developers of the plugin. But normaly use the most plugins for manage options the object `manage_options`.
But if you will, that your editor only change the plugin options from one plugin, than is this not so easy. All options of the core check for this object and also the most plugins. But you can change the role for this object and hide the other plugin settings page and so on with the help if the plugin "Adminimize" for the role of your editor.
You can also change a rolle very easy via plugin "Members". | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "options, user roles, capabilities"
} |
How to empty wordpress custom post Database table
I have around 2000 custom posts. And 7 regular wp pages. I want to delete all those custom post without effecting the pages. I thought the easiest way would be to empty the custom post table but I dont know how to do it. I am familiar with DB operations but I dont know the schema of wp posts, so have no idea where these custom posts are located. I don't mind using a plugin to do it.
Inshort:- Just want to delete all the custom posts and their data. | I used a custom page template to delete all the post from the wordpress database. Everytime I would go to this page it would delete 300 posts.The code for the page template is:
<?php
// Get 300 custom post types pages, set the number higher if is not slow.
$mycustomposts = get_posts( array( 'post_type' => 'movies', 'numberposts' => 300));
echo '<pre>';
print_r($mycustomposts);
echo '</pre>';
foreach( $mycustomposts as $mypost ) {
// Delete's each post.
wp_delete_post( $mypost->ID, true);
// Set to False if you want to send them to Trash.
}
echo '<h1 style=:"color:red;"> DELETED! DELETED! DELETED! DELETED! </h1>';
// 300 custom post types are being deleted everytime you refresh the page.?> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "plugins, database"
} |
Disable wordpress pagination URL rewrite for specific page
I'm hoping somebody could help me out with the following issue. I have a wordpress page: < and there is a list of jobs coming from behance.net via JavaScript. When you click on "Next Page" or a specific page number, the URL is supposed to be as follows: /design-jobs/?callback=Joblist.search.repage&page=2&sort=published_date&status=current
However, WordPress automatically takes the "page=2" and rewrites the URL as
/design-jobs/2/?callback=Joblist.search.repage&sort=published_date&status=current
(I was unable to post more than two URLs hence the shortened version). Notice the number 2 is now out of the query string and "page=2" was removed as well. This then breaks the pagination of the job listing on this page.
I was wondering if there is a way to disable this rewrite behavior for a specific page to allow the pagination to work correctly. | The `redirect_canonical` filter is responsible for this, which you can selectively disable depending on the requested page. This is untested, but should work:
function wpa66273_disable_canonical_redirect( $query ) {
if( 'design-jobs' == $query->query_vars['pagename'] )
remove_filter( 'template_redirect', 'redirect_canonical' );
}
add_action( 'parse_query', 'wpa66273_disable_canonical_redirect' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 4,
"tags": "url rewriting, pagination, rewrite rules"
} |
wordpress pagination fix after the_posts
I am using the_posts action to filter out some unwanted posts - this works fine, but the pagination after this is applied gets broken. If for example there is a page with 10 results before the_posts is applied, then after it gets applied the page displays only 6 posts for example, yet there is 100 posts in total and 20 of them should be excluded.
Pagination shows 1-10 pages when it should show 1-8.
So the question is - how to make pagination work as expected and display 10 posts per page and not to have pages with less than that. | Instead of using `the_posts` filter, you should try `pre_get_posts` action. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "pagination"
} |
Is it possible to use line break in theme description?
I want to give linebreak on Wordpress theme's description in `style.css` (the one in here):
/*
Theme Name:
Theme URI:
Description:
Author:
Author URI:
Version:
Tags:
*/
But it appears the formatting doesn't allow any linebreak. When I tried writing on the line below it, the text won't appear. I tried adding `/n` as a mean to add linebreak, but the `/n/` wasn't read as linebreak.
Is it not possible to add linebreaks in Wordpress theme's description? I think linebreaks may be useful when theme designer wants to outline something in points/bullets (what I've been trying; that is I want to outline several features of the theme). | > Is it not possible to add linebreaks in Wordpress theme's description?
No.
Sorry, to say - the question is valid, but I can't come up with a longer answer. Wouldn't make sense to explain the internals on this topic :) | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "theme development, themes"
} |
Should a child theme share the same theme options row as the parent, or should it have it's own options row?
I'm developing a theme which uses the NHP Theme Options Framework to add some theme options. Naturally, the theme options framework creates a single row in the database to store the theme's options into.
If I create a child theme of the parent, it shares the same theme options as the parent, which leads me to my question:
Should a child theme share the same theme options row as the parent, or should it have it's own options row? Is there a reason why one would be better than the other?
If they are shared and you switched between the two themes, your options would be intact. This can be great if that was the intended behavior. On the other hand, you might go to great lengths to customize the child theme thinking it's independent, switch back to the parent and find your changes overridden. I'm having a hard time choosing one over the other. What are your thoughts? | Neither.
Theme options should be stored as theme mods, using `get_theme_mod` and `set_theme_mod`.
Internally these map on to options, but it is the official way to store theme specific options, that way when you change themes you don't get clashes, and your settings are preserved for if you ever change back. It's the classic adage of _"someone else solved that problem for me, it's their problem now"_
But should you persist in using options, I would advise you prefix all your options with your theme name, and not to share options between child and parent. Setting a child themes options should not affect a site when moving back to a parent theme.
There may be cases when it is advantageous though, so exercise good judgement ( aka use `set/get_theme_mod` )
You can find more about this API here | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "themes, database, theme options, child theme"
} |
Stop WordPress from showing images on non post pages
With regards to how WP displays "preview" text on the home page, category page etc for each post, how do you stop it from including images in this section.
I'm not talking about the featured image for each post, I'm talking about if the post has any included images within the post - I don't want them to show up in the preview text.
This is the code that outputs the content for example..
<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentyeleven' ) ); ?> | Place following code to your theme `functions.php`:
add_filter('the_content','wpi_image_content_filter',11);
function wpi_image_content_filter($content){
if (is_home() || is_front_page()){
$content = preg_replace("/<img[^>]+\>/i", "", $content);
}
return $content;
}
From < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, images, the content"
} |
How does one suppress a 404 status code in a WordPress page?
I've got a WordPress site that includes pages pulled from a different database. The problem is that these other pages return a 404 status code. (The WordPress posts/pages are fine.)
The 404'ed pages display fine, and I removed the "Page not Found" text from the title tag in WordPress. But Googlebot and W3C see the 404 header.
So: wow does one tell Apache to suppress a 404 status? And will Apache override WordPress's 404 header?
Does that make sense? What other info and things should I be looking at?
Can I suppress the status code in .htaccess so I don't change WP core files? | You can either add custom rewrites to your pages. Or on the top of the template files that wrap your other pages just output `header('HTTP/1.1 200 OK');`. | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 13,
"tags": "headers, apache, linux"
} |
Conditonally check if Custom Meta Box has input
I currently display a URL from a custom meta box, but wanted to add a conditional check, so that if nothing has been entered, not to display the link text.
<a target="_blank" href="<?php $urlbox = get_url_desc_box(); echo $urlbox[0]; ?>">Visit Website »</a>
At the moment, even when nothing is added to the URL Meta BOX, the _Visit Website_ text still appears within the post. | $urlbox = get_url_desc_box();
if ( !empty( $urlbox[0] ) ) {
echo sprintf( '<a target="_blank" href="%s">Visit Website »</a>', $urlbox[0] );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "metabox"
} |
How to add element after every post in the loop, but not the last one
I have a pretty common loop:
global $wp_query, $wpdb;
if ( have_posts() )
{
while ( have_posts() )
{
the_post();
get_template_part(
'template_parts/content'
,get_post_format()
);
}
}
else
{
get_template_part( 'no_results' );
}
Now I need to add (for example) a `<hr />` after each single post, but not the last one.
How would I determine if I currently got the second to last post in the current loop?
Note: This should work for paged loops as well. | another possibility:
if( $wp_query->current_post < $wp_query->post_count-1 ) echo '<hr />'; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "loop"
} |
Using wp_editor in shortcode
I am building a plugin for frontend submission. I am using shortcodes API to display the form for content submission, but I am having troubles. The problem is, wp_editor echoe's data, and shortcode should return data. When I integrate wp_editor like this:
$final_form .= wp_editor();
form does render, but not in the place but on top of the post content, where shotcode is included. Do you have any idea how would one use wp_editor in shortcode API? I don't wan't to bother with manually calling TinyMCE etc.
Thank you. | If a function `echo`s data, you can use php output buffering to capture the `echo`ed output and return it instead
// Turn on the output buffer
ob_start();
// Echo the editor to the buffer
wp_editor();
// Store the contents of the buffer in a variable
$editor_contents = ob_get_clean();
// Return the content you want to the calling function
return $editor_contents; | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 7,
"tags": "shortcode, tinymce"
} |
website is still in localhost
I upload my website to the server and I changed the website url and home from localhost to mysite url. But it still is in localhost if I turned off wampserver it won't show the website. Just show me when wamp server is on.
What should i do?
any help will be appreciated | Wordpress hardcodes the domain into many of its permalinks in the database.
An easy solution is to download an SQL dump of the database on your host using phpMyAdmin or an SQL client, and then opening the SQL file in a (robust) text editor, assuming your database isn't enormous.
Then run a Find / Replace for the old domain (localhost) and replace with the new domain, and save the file. Then you'll need to execute the new SQL file on the database, so it is replaced with the same database with the proper domains in the permalinks | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "localhost"
} |
Advanced Custom Fields Validation
Is there way to use custom validation on an advanced custom field? For example, I might not want a textfield to have a value that starts with certain prefix, or I might want a number field to have a value greater than 'x'. I might also want to run a regex against a value and return an error if it doesn't match. | There is now, I just posted a plugin that I wrote to do validation for Advanced Custom Fields to the Wordpress repository. It lets you do server side validation using either PHP code or regex, jQuery masked inputs, as well as unique value settings.
< | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "custom field"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.