INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Redirecting to new URL structure and 301
I had links like `example.com/?location=boston` on my site. These were indexed by Google. Due to obvious SEO reasons, I had to change the URL structure to `example.com/deals/boston`. The old URLs are there on Google results and redirect correctly to new URL.
What I want to know is: while doing the redirect, is WordPress also doing a 301 header so that Google can update its indexes or there is something that I am supposed to do?
Basically, I want Google to update its indexes i.e. replace `example.com/?location=boston` with `example.com/deals/boston` | Really depends on how your redirects are set up. But you can check the status code using Firebug (or a comparable tool with a request profiler).
Open up the "net" tab in firebug, and hit one of your old URLs. You should** see the request show up at the top of the list, and you'll see the response code in the "status" column. If your redirects are working correctly, the first request will have a status of 301, and will be immediately followed by a second request for your new url, with the status 200.
You coud also do this in Chrome developer tools. The tab you'd use there is titled "Network".
** If your intial request disappears from the list, it probably means that the redirect is being done via JavaScript or some other non-legit method. This method of "redirection" is incapable of returning status codes like 301. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "redirect, google search, search engines"
} |
how can i simple change upload folders to %year%/%month%/%day%?
Is there a easy way to do that? Godaddy have a silly limit of 1024 files in one folder and my client upload more than 500 and with the thumbnails we get lot over the limit.
If im able to changed folders into %year%/%month%/%day% i will be safe about that limit
Also another question is if i can make wordpress to generate thumb only when needed. For example home slider will only use 10 images i dont want the other 1000 images have that thumbnail generated.
Thanks for the help! | The Custom Upload Dir plugin can help with this.
For a teaser, they've got a screenshot of someone defining an upload behaviour which is similar to the one you're asking for:
!Example of the Custom Upload Dir plugin in use | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "uploads"
} |
Recent Posts+, how to solve multiwidget?
I have installed the Recent Posts plugin, that came with a widget. Now, i can only add one instance of the widget to the widget areas. I want one instance to show in my widgetarea that only appears on my startpage, and one instance of the widget to my widgetarea that appears on other pages.
Now, the widget doesnt seem to support "multiwidget", but the "widget instances" are supposed to have the exact same configuration. Is there any way to "Force" WP into adding the widget to my other widget area too, even if it means "hacking" the DB? | Easy, Anton!
You don't have to hack the database...
Probably you can find a replacement for this plugin that uses the modern Widgets_API, responsible for the multi-instance widgets. At least as far as I know, because haven't worked much with WordPress pre-2.8.
If you are willing to hack something, hack the plugin using the examples of the Codex.
As for showing one widget in the Front Page and other in the rest, use the plugin Widget Logic. It is very simple and effective. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
How to generate thumbnails when needed only?
I have 1000 images. How can i make wordpress to generate thumb only when needed. For example home slider will only use 10 images i dont want the other 1000 images have that thumbnail generated as its a waste of space and resources.
There is a way to fire add_image_size only when needed ?
Thanks
**UPDATE** As you mention is not really add_image_size what it needs to be fired. What it would be great is to fire the image resize when i use **the_post_thumbnail('slider-thumb');** Maybe this slowdown the first view of the image but that view is usually generated by me when i actually review the post so i dont care.
So between my posts, slider, blog thumbnauls, portfolio thumbnails etc i got 1000 images and i want just 10 images to be resized for the slider i see a lot of wasted resources to generate the thumbnail size for the other 990 images.
Hope its clear now, sorry for my english | ### Take a look at Otto's Dynamic Image Resizer plugin
> This plugin changes the way WordPress creates images to make it generate the images only when they are actually used somewhere, on the fly. Images created thusly will be saved in the normal upload directories, for later fast sending by the webserver. The result is that space is saved (since images are only created when needed), and uploading images is much faster (since it's not generating the images on upload anymore). | stackexchange-wordpress | {
"answer_score": 14,
"question_score": 22,
"tags": "uploads, images"
} |
Add qtranslate language select box to menu
I can't find any info on how to operate qtranslate and add the select box to change language to the right of my header navigation.
Any ideas? | In my header.php I added the following
<div style="float: right; margin: 7px 15px 0 0;">
<?=qtrans_generateLanguageSelectCode('dropdown');?>
</div>
`<?=..?>` is the same as `<?php echo ... ?>` or `<?php function(); ?>`, but I prefer the shortcode
just next to: `<?php ct_primary_nav_menu(); ?>` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, plugin qtranslate"
} |
Remove bulk actions based on user role or capabilities
How can I remove the "bulk actions" based on user roles or capabilities. Actually I have this code to do the job, but now I need to exclude the site admin, I need to let the administrator to access the bulk menu
add_filter( 'bulk_actions-' . 'edit-post', '__return_empty_array' );
add_filter( 'bulk_actions-' . 'upload', '__return_empty_array' );
How can I exclude roles or capabilities from that filter ? | I would do this this way - Just add a new mu plugin or normal plugin:
<?php
defined( 'ABSPATH' ) OR exit;
/** Plugin Name: Limit Bulk actions to Editor & Admin */
add_action( 'wp_loaded', 'wpse_53371_remove_bulk_actions' );
function wpse_53371_remove_bulk_actions()
{
if ( ! is_admin() )
return;
if ( ! current_user_can( 'delete_others_pages' ) )
{
add_filter( 'bulk_actions-edit-post', '__return_empty_array' );
add_filter( 'bulk_actions-upload', '__return_empty_array' );
}
}
this will check if current user is Editor or admin - if not then bulk actions will be removed. For more about Roles & Capabilities look here in the Codex. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "functions, filters, bulk"
} |
automated tests as a user?
I checked out (with svn) the code for Automated Testing. However, I want to run unit tests as a specific user.
Is there a way to do that? That is, is there a way to loggin with php code alone? | $user_id = $this->_make_user('author', 'user_login_name', 'password', '[email protected]');
wp_set_current_user( $user_id );
as long as the class that you define the testcase in inherits from `WPTestCase`, then you can use the `_make_user` function. The function is found in this svn repository, and is defined in `wp-testlib/base.php` line 380.
NEW:
I switched to using `wp_insert_user`.
the following is in my setUp:
$this->user_id = wp_insert_user(array('user_login'=>'test_administrator', 'role'=>'administrator'));
wp_set_current_user( $this->user_id , '');
and the following is in my teardown:
wp_delete_user($this->user_id);
$this->user_id = 0; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "php, users, login, testing"
} |
Image rotator plugin
I have tried two Rotator plugins so far. Nivo-slider and EasyRotator. Nivo-slider was great, but i could only have an image caption, and i need both image caption and image title. Also, i couldn't get the "bullets" for indicating the current slide to work. So i Googled and found the "EasyRotator"-plugin. Great, except it rescales the images, even if i upload in the correct resolution, the generated HTML is all inline styling so it's kind of hard for me to style it as i want from css. Now im wondering, is there any plugin that does the following?
1. Image Title
2. Image Caption
3. Bullets to indicate current slide
Any tip is appreciated! Thank you! | Content Slide can handle that. <
And the plugin site: <
It's a champ and handles all three of your conditions. 'Bullets' are square, you can mod that though. Have fun! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
A Blog's changelog
I'm looking for a plugin that would keep track of a all the structural "changes" journal. For instance, the date+time of each wordpress upgrade, or plugin install/update/activation/desactivation or desinstallation, along with the plugin version.
Do you know of anything related? | With the help of @toscho, i made this plugin < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 4,
"tags": "plugins, revisions"
} |
Custom taxonomies to define versions of a product
I have a custom post type that describes components of a product. As the product is developed new components are added. I'd like to define what version of the product the component was added, and then be able to browse products by that version.
I tried making a custom taxonomy as the version, but my problem is when I browse that version. I only see the components added for that version. I need to include all components for that version and previous versions.
Is taxonomies that right approach or is there another way to handle this in WP? | Taxonomies is not the right approach here, you should use custom fields (post meta) instead this way you can use `compare` argument of the meta query as `<=` ex:
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => '_version',
'value' => '1.0',
'compare' => '<='
)
)
);
$query = new WP_Query( $args ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, custom taxonomy, custom field"
} |
Author can only see own post comment and can moderate
I am trying to make things work like where author can see only them post comment in admin comment section and they can moderate as well. While admin should have all permission.
I am having one code and working fine in all terms like showing only author's post comment but it's not allowing to moderate. Can anyone help me to find solution where author can moderate own post comment.
Code I have:
function my_plugin_get_comment_list_by_user($clauses) {
if (is_admin()) {
global $user_ID, $wpdb;
$clauses['join'] = ", wp_posts";
$clauses['where'] .= " AND wp_posts.post_author = ".$user_ID." AND wp_comments.comment_post_ID = wp_posts.ID";
};
return $clauses;
};
// Ensure that editors and admins can moderate all comments
if(!current_user_can('edit_others_posts')) {
add_filter('comments_clauses', 'my_plugin_get_comment_list_by_user');
} | The default author role does not have the `moderate_comments` capabilities so you need to add that capability to the author role, so add this to your plugin:
function add_theme_caps() {
$role = get_role( 'author' ); // gets the author role
$role->add_cap( 'moderate_comments' ); // would allow the author to moderate comments
}
add_action( 'admin_init', 'add_theme_caps'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "comments, author, moderation"
} |
Does plugin's uninstall.php file have access to the plugin 's object?
I read on the codex that the best way to implement a clean uninstallation functionality to a plugin is by adding a uninstall.php file inside your plugin directory.
I'm wondering: can i use my plugin's Class instance data inside the uninstall.php file?
This is the code sitting in my uninstall.php file:
if(!defined('WP_UNINSTALL_PLUGIN')) exit;
delete_option('my_plugin_options');
$table_name = $wpdb->prefix . $this->dbName;
$wpdb->query("DROP TABLE `$table_name`");
I'm wondering if the table_name variable will be properly retrieved, or if i should hardcode it.
As per my tests, the table remains after deletion, so i guess i'l fallback to using a hook inside my plugin's file, unless i'm missing something? | I'm not in my desktop, but I suspect it won't be retrieved.
But:
* have you tested it? Does the table gets droped?
* I'd say you need to declare _global $wpdb;_ , isn't it?
* if you don't have any, a tool like FirePHP is **really** handy when developing
* anyway, this seems a case where is pretty harmless to hardcode the table name | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, uninstallation"
} |
How to display user role
How to display user role on author page.
I have created my own role (group) so I want to display the user role on below the post and on author list.
I have tried this code but not working as its calling current_user and its showing current user role in all authors profile
<?php
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
if ($user_role == 'administrator') {
echo 'Administrator';
} elseif ($user_role == 'editor') {
echo 'Editor';
} elseif ($user_role == 'author') {
echo 'Author';
} elseif ($user_role == 'contributor') {
echo 'Contributor';
} elseif ($user_role == 'subscriber') {
echo 'Subscriber';
} else {
echo '<strong>' . $user_role . '</strong>';
}
?>
How can I alter this code to display user actual role and not the current user role. | Change:
$user_roles = $current_user->roles;
with
$user = new WP_User( $user_id );
$user_roles = $user->roles;
and the $user_id should e the actual user id who's role you are trying to get.
**Update,**
Sorry i just read the author template part so try this:
//first get the current author whos page you are viewing
if(isset($_GET['author_name']))
$curauth = get_user_by('slug', $author_name);
else
$curauth = get_userdata(intval($author));
//then get the user object with roles
$user = new WP_User( $$curauth->ID );
$user_roles = $user->roles;
.... | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "user roles, author template"
} |
Template tag for /page/# structure
I'm trying to find a template page (or conditional statement) that will target:
> <
but not
> <
home.php and front-page.php seem to target both. The front page displays my latest posts.
Thanks in advance! | WordPress provides `is_paged()` which returns true on any archive or blog that stretches over multiple pages. This isn't what you want, but the `is_paged` Codex article tells us where to go:
> If you need to check which page of the blog you are on, you can look in $wp_query->query_vars['paged']. Remember that inside functions you might have to global $wp_query first.
So, you should be able to use this snippet to only show something on the first page:
global $wp_query;
$my_paged_page = $wp_query->query_vars['paged'];
if ( $my_paged_page == 1 ) {
// do something
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "page template, conditional content"
} |
Running a function with args in add_action()
I've created a plugin, and it has a function that takes two args, like so:
process($tokens, $payloads);
... would this work? :
add_action ( 'publish_post', process($tokens, $payloads) );
Many thanks! | No, this cannot work. Haven't you tested your idea?
A simple workaround would be a class:
class WPSE_53453_Action_Handler
{
public $tokens, $payloads;
public function process()
{
$tokens = $this->tokens;
$payloads = $this->payloads;
// do something awesome
}
}
$WPSE_53453 = new WPSE_53453_Action_Handler;
$WPSE_53453->tokens = array ( 'foo', 'bar' );
$WPSE_53453->payloads = 'hello';
add_action( 'publish_post', array ( $WPSE_53453, 'process' ) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, actions"
} |
Test site pages go to main site
I have a test site installed on www.mydomain.com/testsite.
The problem I have is that if I type in the url www.mydomain.com/testsite/about I get redirected to www.mydomain.com/about.
My page for my test site gives me the permalink: www.mydomain.com/testsite/about
If I click View Page from the page editing screen in the dashboard, I get redirected to www.mydomain.com/about instead of being sent to the permalink.
My htaccess file is located in my root folder and is as follows:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
ErrorDocument 404 /404.php
<Files delete.php>
order allow,deny
deny from all
</Files>
Can anyone help? | Your htaccess file seems to be a little off.
I would suggest the first part of the file should look like the following...
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /testsite/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /testsite/index.php [L]
</IfModule>
And that you store it in the 'testsite' folder not the root. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "permalinks, pages, redirect, htaccess, testing"
} |
Shortcodes in Options Panel textareas
I am using an Options Panel to create my themes, and I would like to make the textareas from this OP to support my shortcodes too.
The code for that creates the textarea fields:
case 'textarea':
$cols = '8';
$ta_value = '';
if(isset($value['options'])) {
$ta_options = $value['options'];
if(isset($ta_options['cols'])) {
$cols = $ta_options['cols'];
}
}
$ta_value = stripslashes($data[$value['id']]);
$output .= '<textarea class="of-input" name="'.$value['id'].'" id="'. $value['id'] .'" cols="'. $cols .'" rows="8">'.$ta_value.'</textarea>';
break;
Any idea how can I do that?
Please let me know if I should provide more details. Thanks. | simply use `echo do_shortcode($textarea_value);` (answer by @Bainternet) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode"
} |
Trimming a custom field to a length
I have a custom field added through the Advanced Custom Fields Plugin. I am trying to trim the content of the field down to a set number of words. I have tried to use the excerpt filter and setting a custom length see code bellow but It's not working, thought?
// set the length of the excerpt
function custom_excerpt_length( $length )
{
return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
// apply the filter and strip crap from 'description'
//
$content = apply_filters('the_excerpt', get_field('description'));
$content = str_replace(']]>', ']]>', $content);
echo $content;
//echo wp_trim_excerpt($content);
I also tried the wp_trim_except() function but it isn't doing anything either. The whole length of the text is being echoed. | The excerpt is a specific field in WordPress and is wholly unrelated to custom fields, which is why the excerpt stuff you tried has no effect.
There is no built in way to trim custom fields, you have to do it manually with a bit of php:
$length = 20;
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec diam enim, egestas ut facilisis sit amet, semper sed turpis. Phasellus dolor nisl, pretium non imperdiet nec, cursus quis turpis. Duis sed lorem tortor, a gravida magna. Integer commodo cursus ante, non varius odio aliquam quis. Aenean tincidunt congue ultricies. Donec ut orci vel ante laoreet bibendum. Aliquam vitae erat arcu. Nam et mi nunc. Proin sed lorem ac odio vestibulum blandit sit amet id dolor. Sed in augue id massa feugiat convallis.';
$words = explode(' ', $text);
array_splice($words, $length);
$text = implode(' ', $words);
echo $text; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "filters, content, excerpt, text"
} |
Can I programmatically login a user without a password?
I'm manually creating users programmatically, and I want to sign in the newly created user. WP makes it easy to access the hashed password, but not the plaintext version. Is there a way to use wp_signon() without the plaintext password?
I found one person who claims to have done this here, but it didn't work for me.
THANKS! | `wp_set_auth_cookie()` will log a user in without having to know their password. | stackexchange-wordpress | {
"answer_score": 42,
"question_score": 47,
"tags": "login, authentication"
} |
pagenavigation not showing the next page just linking back to the main page
Using this on my index.php
<?php if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?>
Using plugin:
WP-PageNavi Wp Pagenavi Style
Not sure what information you need to help me fix this. So please let me know.
Site: <
edit:
code of index.php < | I took a look at the index.php code and I'll explain what's going on.
The theme author is using 2 custom new WP_Queries but is not doing anything with the main global $wp_query object. When you click to the second page you get the same posts because there is no main loop present.
Neither of the secondary loops contain pagination parameters. To fix this assign the query_var page to a variable and add it to the query args array.
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
Add to array:
'paged' => $paged,
Next you need to tell WP pagenavi what query to paginate.
<?php if(function_exists('wp_pagenavi') ) { wp_pagenavi( array( 'query' => $blog ) ); } ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pagination, plugin wp pagenavi"
} |
How to cancel redirection to admin side
My friend asked me to activate a site that someone else did it. The problem is that when I try to run it, and I go to `mysite.com` I arrive to `mysite.com/wp-login.php?redirect_to=/` Where and how can I fix it? | disable all plugins or change theme to default one. AFAIK there is no such function by default in WP to redirect non loged in users to login page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin, login, activation"
} |
How to detect /category and /tag base pages?
In a theme I'm building, I have this structure for detecting what type of page something is. However, if I visit mydomain.com/category/ or mydomain.com/tag/, all I get is the "nothing found" message I have in the have_posts()'s else statement. Is there a way to detect when these links are visited and display something other than what's in the final else statement?
if(is_category()):
echo '<h1>title here</h1>';
elseif(is_tag()):
echo '<h1>title here</h1>';
elseif(is_author():
echo '<h1>title here</h1>';
elseif(is_archive()):
echo '<h1>title here</h1>';
endif;
if(have_posts()):
//the loop
else:
echo '<h1>Nothing Found</h1>';
endif; | If I put this above the htaccess block of wordpress rules, I'm able to redirect the tag and category base pages back to the homepage.
RewriteCond %{HTTP_HOST} ^mydomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^localhost$
RewriteRule ^category/?$ " [R=301,L]
RewriteRule ^tag/?$ " [R=301,L] | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, theme development"
} |
the_permalink() not working in a root installation
I hope someone can help me. I have a root installation of WP, but not as `index.php` (it's actually `news.php`). Consequently `the_permalink()` doesn't work, as the root of the website is a different page.
Is there any way I can fix this? Perhaps something in the .htaccess that detects `?` in the URL and redirects to `news.php/?` etc.
Thanks for any assistance, I'm a newb at WP! | ## Change the name of news.php to index.php.
I don't know of any legitimate use case that exists for changing index.php.
If something else is using index.php then move WP in its own /news directory.
You could change the .htaccess but you might run into trouble down the road. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "posts, permalinks, wp config, theme roots"
} |
do add_action on condition
This snippet for example will email on EVERY post:
function email_friends( $post_ID )
{
$friends = '[email protected], [email protected]';
wp_mail( $friends, "sally's blog updated", 'I just put something on my blog: );
return $post_ID;
}
add_action('publish_post', 'email_friends');
... whereas I just need add_action to run ONLY if the post is in category say "uncategorized", not any other category.
Thanks! | Use `has_category()` to check if a post belongs to a certain category.
function email_friends( $post_ID )
{
if ( has_category( 'uncategorized', $post_ID )
{
$friends = '[email protected], [email protected]';
wp_mail(
$friends,
"sally's blog updated",
'I just put something on my blog: ' . get_permalink( $post_ID )
);
}
}
add_action('publish_post', 'email_friends');
And you don't need to return anything for an action handler. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "plugins, actions, conditional tags"
} |
How To Only Allow Users To View Their Own Buddypress Profiles?
I am currently developing a social-network sort of site using Wordpress + Buddypress and the client has asked that profile pages not be publicly visible for the time being. Basically the client is okay with logged in users viewing their own profiles, but if they try viewing a profile page of another user it should redirect to the homepage.
I found the function: bp_is_my_profile() and tried using the following code at the top of the members/single/profile.php file to redirect users away, but it doesn't appear to be working. Any pointers?
<?php
if ( !bp_is_my_profile() )
{
wp_redirect(site_url(), 302);
}
?> | I solved this issue myself, it was quite easy and I'm surprised nobody else supplied an answer. Having said that, the solution is to add a few lines of code that check what the author ID is of the profile you're viewing and compare it to the ID of the currently logged in user.
This code goes at the top of members/single/profile.php
<?php
// Global $bp variable holds all of our info
global $bp;
// The user ID of the currently logged in user
$current_user_id = (int) trim($bp->loggedin_user->id);
// The author that we are currently viewing
$author_id = (int) trim($bp->displayed_user->id);
if ($current_user_id !== $author_id)
{
// redirect to home page url
wp_redirect(home_url());
exit();
}
?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "redirect, buddypress, wp redirect"
} |
WordPress Admin very slow
Hi my wordpress admin is acting really slow, is there some diagnostic plugin I can use (like Debug queries on the front end) to see which plugin is slowing down the dashboard? | First i recommend you to use Chrome Ctrl+Shift+j -> Timeline, click record button and refresh admin page and in that timeline you will see what caused the longest load. if HTML then php/sql part is slow, but maybe some javascript causes slow load.
Second - one by one disable plugins and test loading time. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "admin"
} |
Wordpress Plugin to for moving home page slideshow?
How can I create a moving skideshow similar to the one on this site? Is there a plugin doing this already? I have searching using the "moving slideshow" keywords. Any tips? Many thanks. | It really depends what you want?
If you need it to be controlled from the WordPress CP then you may have to write your own or try reading through the descriptions on these plugins listed here. - <
If you dont need so much control you can look into jQuery Slider plugins such as Orbit by Zurb (a personal favourite) - < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "plugins, slideshow"
} |
Getting Thumbnail in fetch_feed from custom field
i have setuped showing rss from my network site using fetch_feed();
include_once(ABSPATH . WPINC . '/feed.php');
$rss = fetch_feed('rss link here');
$maxitems = $rss->get_item_quantity(5);
$rss_items = $rss->get_items(0, $maxitems);
THen i can use foreach to get these
$item->get_description();
$item->get_permalink();
$item->get_title();
get_date('j F Y | g:i a');
But i am not sure how to get thumbnail in my feed or here in this system. But in my posts i do have a custom field called post-img for displaying posts.
Help is appreciated. Thanks | According to the Codex, fetch_feed() uses the SimplePie engine for parsing RSS.
So, if `$item->get_title();` is working, then you should be able to do:
> `$item->get_thumbnail();`
as per the SimplePie documentation, as long as there are any thumbnails already on the feed.
**UPDATE:**
Before running the above, you have to insert the images on your feed. Check for _display featured image in RSS feed_ and _How to grab first image attached to post and display in RSS feed?_ topics on it. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 0,
"tags": "rss, feed"
} |
How to stop the wp_mail function?
I'm using wp_mail filter function.
`add_filter('wp_mail','check_the_mail_content');`
If my condition satisfied then the mail should go, otherwise I need to stop, my function is
add_filter('wp_mail','check_the_mail_content');
function check_the_mail_content($query){
if(mycondition){
//mail should go.
}
else{
//stop the mail.
}
} | Filter `'phpmailer_init'`, not `'wp_mail'`. To prevent sending the mail out reset the PHPMailer object.
_Prototype (not tested):_
add_action( 'phpmailer_init', 'wpse_53612_conditional_mail_stop' );
function wpse_53612_conditional_mail_stop( $phpmailer )
{
! my_condition() and $phpmailer = new stdClass;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp mail"
} |
Wordpress redirect on login
I have downloaded my site to a production environment. I have set up both the live site and the production site to use the same DB. When i login to the admin panel i get redirected to the live site. I know that wordpress stores URLs in the DB so i want to modify (hard code) my production site not to redirect anywhere.
Where and how?
Edit: I found the solution to this particular problem here <
But when one problem was tackled two new ones appeared and as discussed below, it's not worth it. | I think getting the site to redirect to the proper location on login would only be the beginning of your issues with this setup.
What would happen when you want to use any WordPress function to retrieve the site url? You would possibly have to re-write those functions as well, so that they return the production url instead of the url from the database.
If your production site is on your local machine you might try editing your HOSTS file so that your local machine thinks that its the real server. When you are finished working on your local machine you could then switch your hosts file back to normal to see the real live site again.
Check this URL < for more info on using a hosts file. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
Password in wp-config. Dangerous?
I don't know a lot of Wordpress yet, and I'm just wondering:
Before installation you have to fill in the correct data in `wp-config-sample.php` but this also includes the database password. Isn't that dangerous? I mean, can some one explain how this is protected from just reading the file and thus getting the password of your DB? | The "Hardening WordPress" page of the Codex contains a section on "Securing wp-config.php". It includes changing the permissions to 440 or 400. You can also move the wp-config file one directory up from the root if your server configuration allows for that.
Of course there is some danger to having a file with the password like this if someone gets access to your server, but, honestly, at that point they already are in your server.
Finally, you don't have much of a choice. I've never seen an alternate means of configuring WordPress. You can lock it down as much as you can, but this is how WordPress is built, and if it were a **serious** security threat, they wouldn't do it that way. | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 10,
"tags": "wp config"
} |
Putting footer content in a "page" - Doing it wrong?
So, in my shortish WordPress development career, I've gotten in the habit of creating a "page" for the content in a footer, and adding different fields with the wpalchemy class. Everything with this approach seems to work fine, except for the fact that users can go to mysite.com/footer and see something I do not want them to see.
Should I somehow force this url to 404? or is there something fundamentally wrong with my approach? | I don't think there's anything fundamentally wrong with your approach, I see it pretty often.
You could hook `parse_request` and 301 redirect any requests to footer to the front page. I wonder though how visitors would end up there in the first place, as long as you exclude it from the sitemap and don't link to it anywhere.
Or you could create a custom post type for this kind of content and make it not publicly query-able. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "pages, 404 error, footer"
} |
Styling Previous/Next Pages differently from Index
A friend of mine pointed me towards using child elements to style my index page so that I could have one loop and several different visual styles (a featured post, a smaller sub-featured post, and several smaller thumbnails). This is very helpful in that I can add posts and the existing posts will just flow through this styling.
For example, I can style the .hentry class by:
.hentry:nth-child(3)
{
background-color:#00000;
}
And so on.
The problem I run into is when clicking on the next/previous links on the bottom of the content portion, those following pages maintain that styling. Is there a way I can style those pages differently?
URL: <
Thanks in advance! | Your theme's `body_class` can be used to target specific pages:
body.home /* front and subsequent pages */
body.paged /* any page *except* front page */ | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "pages, archives, css, previous, next"
} |
Where is phpMyAdmin inside WordPress?
Even if I've been coding (mainly Java and Python) for some years, I'm totally new with web apps and PHP. So please forgive me if this is a novice question.
I had a WordPress blog with a friend who was managing all the WordPress hosting. Now my friend has decided to go away and he sent me the blog backup:
1. All the WordPress files.
2. The dump of database in `dump.log`.
I have purchased hosting where I can restore the old blog. Looking for how to set up the blog again, I found everywhere the guideline "Restore the database from phpMyAdmin", but I don't know where can I launch phpMyAdmin from the backup I have.
Please explain to me what I have to do. | phpMyAdmin is software typically installed by your host and available via your hosting control panel, it is not part of WordPress.
A search on web for `[your host] phpMyAdmin` will probably tell you what you need to do. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "database, backup"
} |
Get current Wordpress page then add #post ID to the end
I'm trying to find out the PHP code that will get the current URL and add a hash ID onto the end of it so a link can be generated and linked to.
The end goal is to create a link that returns: < This should a) take users to the news page and b) jump to the part of the news page where the post ID of 123 is displayed.
Ideally I need a solution that can handle pagination within Wordpress, this is my code to get the curent page URL that I spotted on another thread but how do I create a new string from it?
<?php
$Path=$_SERVER['REQUEST_URI'];
$URI= get_bloginfo('url').$Path; // get the current web address for my WP site
?> | Your answer should return: `` so from there you just do this:
$final_url = $URI.'#'.get_the_ID();
Which _should_ echo ` which is kinda good for linking. But if your looking for a "bookmarks" link it would be best practice to do this (inside the loop):
echo '<a href="'.the_permalink().'" title="'.the_title().'">'.the_title.'</a>';
Which will echo "Interesting Page" (note the title attribute gets stripped by the SE engine) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, urls"
} |
Gravity Forms field ID $entry not working
So my script is simple right now just to test out the $entry field id's.
add_action("gform_after_submission_3", "set_post_content", 10, 2);
function set_post_content($entry, $form){
$subject = $entry["28"] . 'Applied as: ' . $entry["2"];
mail( $emailremoved, $subject, $message);
}
Right now entry 28 is a dropdown, this one returns the selected value.
Entry 2 is the name field with split first and last. This returns nothing. Ive also tried $entry["2.1"] and get nothing.
Entry 34 (not added) is a multi checkbox. This value is not echoed out either.
This is a multipage form, but that shouldnt matter.
Any ideas why the values are not returning? They are saving to the form entry. | To debug you should print what's in $entry.
echo '<pre>' . print_r($entry,true) . '</pre>';
die();//You may need to kill the script to view..
Or email to yourself in your current mail function.
$message = '<pre>' . print_r($entry,true) . '</pre>'; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin gravity forms"
} |
Remove field in the form : only works for "url", not for "email"?
I would like to remove the email field in the comment form. It works for `url` but not for `email` : the email field is still there. Do you know why?
<?php
function url_filtered($fields)
{
if(isset($fields['url'])) {
unset($fields['url']);
}
if(isset($fields['email'])){
unset($fields['email']);
}
return $fields;
}
add_filter('comment_form_default_fields', 'url_filtered');
?>
Thanks | This works fine for me:
<?php
add_filter('comment_form_default_fields', 'wpse53687_filter_fields');
/**
* Unsets the email field from the comment form.
*/
function wpse53687_filter_fields($fields)
{
if(isset($fields['email']))
unset($fields['email']);
return $fields;
}
One reason that it could be failing on your theme is that args were passed into `comment_form`. Specifically, the theme author passed in a `fields` key into the `$args`.
As the filter name (`comment_form_default_fields`) implies, the fields are only defaults.
Fortunately there is another filter! `comment_form_field_{$name}`. Just hook in and return false and it should get rid of the email field.
<?php
add_filter('comment_form_field_email', '__return_false'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "forms, email, comment form"
} |
TinyMCE - Insert media at the beginning of post
I want to modify TinyMCE in WordPress so that it inserts media (image etc.) always at the beginning of post contents. For this I need to change the cursor position to the beginning, insert media and possibly restore old cursor position. I am not sure how to achieve it. Please advise. | I found this which helped me moving caret to start of post before inserting media. My modified code is:
var root = ed.dom.getRoot();
var node = root.childNodes[0];
if (tinymce.isGecko) {
node = node.childNodes[0];
}
ed.selection.select(node);
ed.selection.collapse(true);
// The following is required to work in IE, don't remember from where did I get this =)
if ( tinymce.isIE) {
ed.focus();
ed.windowManager.insertimagebookmark = ed.selection.getBookmark();
}
if ( tinymce.isIE && ed.windowManager.insertimagebookmark )
ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "tinymce, media"
} |
Sharing a custom taxonomy - No posts?
I've been writing up some code which enables two post types to share a custom taxonomy. From the admin side, it works fantastically - but for some reason, when I look at the taxonomy archive itself on the site,
/country/{country} , despite the fact that there are two posts (one from each type) in the taxonomy, it comes back with 'No posts found' but _not_ a 404 error. I wonder if I've missed something to make it work - my code is below.
register_taxonomy(
'country',
array('hotels', 'attractions'),
array(
'label' => __( 'Country' ),
'hierarchical' => true,
'sort' => true,
'args' => array( 'orderby' => 'term_order' ),
'rewrite' => array( 'slug' => 'country' )
)
); | As the page is returning with "no posts found", it's possible that whatever template page is generating term archives isn't including your custom post types in its query.
If you take a look at the template that should be easy to see. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, taxonomy"
} |
add data-attribute to all images inside the_content()
I wonder if it's possible to add a filter to all images inside `the_content()` to create the following image pattern for all images …
<img class="digest" src="smallest-file.jpg" data-fullsrc="largest-file.jpg" alt="something"/>
So I'd like to add a `class="digest"` to the img tag. Additionally the `src` attribute of the image should always link to the smallest-file wordpress creates and a `data-fullsrc` that links to the largest file of the image.
Any idea or approach on how to do this? I'd really appreciate your help with this as I'm completely helpless right now. | You will need to take a look at the `image_send_to_editor` filter.
This will not update existing records but it if you get it working it will apply to each newly inserted image.
very basic filter:
function give_linked_images_class($html, $id, $caption, $title, $align, $url, $size, $alt = '' ){
$html; //contains the string you need to edit, you might want to consider to rebuild the complete string.
return $html;
}
add_filter('image_send_to_editor','give_linked_images_class',10,8); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "images, filters, the content"
} |
the_permalink() not working
I have WordPress installed in a subfolder called `news`, but links to comments, posts, categories, etc all link to `domain.com/?p=99` instead of `domain.com/news/?p=99`. The only link that points to the correct folder is the `edit post` link.
I have set my WP folder to, `domain.com/news`, and my site domain, `domain.com`. I also tried deleting my `.htaccess` file. Nothing has helped!
Part of the issue might step from the fact that WP _used_ to be installed in the root folder.
Any idea what I can do? :( | Usually this is because the "Site URL" field in Settings > General is wrong. It probably says "domain.com" where it should say "domain.com/news". | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, installation, configuration"
} |
Can you exclude child pages of a specific parent within a navigation?
For example, I'm using wp_list_pages to display the navigation, the child pages (and their children) appearing on hover as is typical. However, I want one of these parents to _not_ display the children. Essentially I want something like exclude_children_of to work in the wp_list_pages arguments; is there a way of doing this anybody?
thanks
Rob | try -:
if your page ID = 999
<?php
$child_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE $wpdb->posts.post_parent = 999 AND $wpdb->posts.post_type = 'page' AND $wpdb->posts.post_status = 'publish' ORDER BY $wpdb->posts.ID ASC");
$exclude = implode($child_ids,', ');
wp_list_pages('exclude=' . $exclude . '&title_li=<h2>' . __('Pages') . '</h2>');
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, wp list pages, children"
} |
Friendica integration using wordpress authentication
I currently have a BuddyPress community with bbPress forums and a MediaWiki based collaborative area.
I'll soon be adding Friendica support for good integration with other friends Diaspora websites plus other social network integration that Friendica can provide.
I basically want Friendica to use BuddyPress for authentication, single sign on. If the user is logged in on BuddyPress, they are logged in on Friendica.
I may have to develop this from scratch, in which case I document what I do and post it as an answer here, but before I do that, if anyone has already done this and can post instructions on how to do it, that would be a big help. | The way I think this needs to be done:
1. Examine how an existing integration allows a particular CMS to authenticate using wordpress. Possibly this MediaWiki integration. Work out how this authenticates a wordpress user.
2. Examine an existing friendica authentication plugin, such as the LDAP one that comes with the CMS, and update this to use the wordpress authentication method calculated in step 1.
_(If no-one beats me to a more complete answer, I will add more detail as I work through this. Otherwise I hope this partial answer will inspire a more complete answer)._ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "customization, authentication, single sign on"
} |
Assign post type to many users
I am working on a small course engine that has a Course custom post type and a list of users. Users should apply for courses.
I was thinking about the Posts 2 Posts plugin to create the relationship, but is there any straight forward way to assign many users to a single post type (course) and see only things for that specific post type? Any premium plugin that could do that without making everything really heavy?
P.S. A user could attend several courses as well. | On a total fluke, I saw this WPSE answer just after reading your question. It's a plugin called "User Specific Content" that seems to do exactly what you want. "Role Scoper" is a good plugin, but it's probably overkill for what you need. Best yet, the "User Specific Content" plugin was the result of a WPSE answer's code snippet! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, users"
} |
Ability to set character limit in BuddyPress?
I would like to limit characters in BuddyPress posts to certain limit . Ex: Set it to the limit of 150 ... just like twitter's 140.
Googled about it and found nothing. Does any one have Idea on this?
Thanks | Simple solution is to add a maxlength attribute to the textarea field. For example
<textarea maxlength="140">
</textarea> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "buddypress, limit"
} |
Basic Multisite Question - Managing Content Centrally
Is it possible to manage content on multisite installations centrally? If I have a network of 20 sites, is it possible to change the content on one site and have it update across the network, or will I have to make the change on each site one at a time? More specific case, If I have a Terms and Conditions page that must appear on each site, that requires periodic changes can I make the change once and have it replicate.
Any suggestions/directions/resources for managing this process effectively would be appreciated. | I've successfully used the ThreeWP Broadcast plugin to do this on a WPMU installation.
The basic concept is that you have one 'broadcasting' site from which you can broadcast content to other sites. The content can be posts, pages, custom post types, custom taxonomies, post meta or attachments.
If content is updated on the 'broadcasting' site, the updates will be reflected on the other sites. More info can be found on the ThreeWP Broadcast WP Plugin Directory entry linked above. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 6,
"tags": "multisite"
} |
Custom Taxonomy Tag Search
I have an existing WordPress search function, what I'd like to be able to do is extend the search to the tags from my custom taxonomy...how do I do that?
<form method="get" id="searchform" action="<?php echo home_url(); ?>">
<input type="text" value="Product Search..." name="s" id="s" />
<input type="image" src="<?php bloginfo('template_directory') ?>/images/icosearch.png" id="searchsubmit" value="" />
</form>
I tried to use the "Search Everything" plugin, but that functionality doesn't seem to extend to custom taxonomies. I'm not sure if there is a different plugin or some kind of filter that would get the job done.
Thanks in advance!
Josh | One plugin that I've used successfully is Relevanssi: <
Also, you could try to make your custom taxonomy into a search filter, like it's described in this post: < . I've used this on my projects and it worked wonders!
Hope this helps! | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, theme development, custom taxonomy, functions, search"
} |
Creating a subdomain network in a subdomain
I've installed Wordpress on subdomain.domain.com.
I've enabled the Wordpress Network on this installation, choosing a subdomain install.
I've created a wildcard subdomain in cpanel, which is *.subdomain(.domain.com), which points to /public_html/subdomain
I've created a site: site.subdomain.domain.com, but I cannot visit the dashboard of this site, nor does it show under the My Sites dropdown menu after creating it - I get an ISP Site Not Found page.
Is this situation not workable: creating a subdomain network in a subdomain? | It turns out the ‘wildcard’ DNS entry was not in the zonefile for *.subdomain.
Tech Support fixed this for me, and it is up and running, except for the fact that the new website is still not listed under the Sites dropdown menu. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, subdomains"
} |
Force page to open in html mode
Hi I have a page that always gets messed up when opening in Visual mode, can I force this particular page to always open in HTML mode for all users in the dashboard? | Try this Force html edit plug-in. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "pages, tinymce, dashboard"
} |
how does $wpdb differ to WP_Query?
I'm going to write a function to return the next/prev post in a specific category. can anyone tell me what the differences would be in using `$wpdb` as opposed to `WP_Query()`; eg `new WP_Query(args)`? what determines which of these should be used?
cheers,
Gregory | The `wpdb` class is the interface with the database. `WP_Query` uses `wpdb` to query the database. You should use `WP_Query` when dealing with the native WordPress tables, to integrate your code properly with the WordPress environment. Use `wpdb` directly when you need to access data in your own tables. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 6,
"tags": "wp query, wpdb"
} |
why do I have to use required parametres?
Why, when I want to use
add_filter( 'author_link', 'foo', 10, 3 );
function foo ( $link, $author_id, $author_nicename ) {}
I have to use 3 required parametres? Why cant I do this:
add_filter( 'author_link', 'foo' );
function foo ( $author_id ) {}
If you can, please give me some literature about this.
PS beginner in WP. | You don't _have_ to specify number of arguments, in which case it will default to one.
Essentially this argument gives you control on how many arguments hook will pass to function, which matters in few too many situations to come up with generic explanation.
In a nutshell if hook can pass N arguments, your options are:
* pass 1 argument (default)
* pass <=N arguments by specifying number
* do not pass any arguments by specifying 0 (rare, but highly useful at times)
Note that you cannot change order of arguments passed, if you need Nth you will need to pass as many and then ignore unwanted ones in your function (which only makes sense in few hooks, because first argument tends to be meaningful one, rarely second). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, author, parameter"
} |
get_the_category_list or get_the_tag_list for custom post types and taxonomies?
Basically I've setup a custom post type and taxonomy for a set type of posts and I'm creating a child theme from twentyeleven.
When I use the default WP Posts and then I tag them and categorize them, get_the_category_list and get_the_tag_list do their work and display below the post.
Now I would like to do the same with my custom post type with two taxonomies that behave as tags and categories. Is there a way I can do this without having to redo the work that get_the_category_list and get_the_tag_list already do? | You can use the generic `get_the_term_list()` for all taxonomies. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 6,
"tags": "custom post types, custom taxonomy, theme twenty eleven"
} |
Force the_content() to show full post in RSS feed
I'm making a custom RSS feed where I want the full article to display. The problem is that when I use the_content() to output the article, it will only show the excerpt if there is a 'more' tag in that article. How do I force the_content() to output the full article, or is there another function that will achieve this? | Setting the $more variable to 0 seem to solve the problem for me. I put the following at the top of my function which output the RSS feed:
function outputRSS(){
global $more;
$more = 0;
//Output my RSS below...
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "rss, the content"
} |
Change Page Template Based on Category
How can I display a post with a certain category in the page template instead of default category template.
For an example, I want to show all posts under category "Scott" with the page template ("page.php"). | I'm pretty sure you could also do what you want by filtering `template_include`. This is super-untested, but maybe this can get you headed in the right direction:
function wpse53871( $template ) {
global $post;
// check if is a Post and in the 'scott' category
if( is_single( $post->ID ) && has_category( 'scott', $post ) ) {
return get_template_part( 'page' );
} else {
return $template;
}
}
add_filter( 'locate_template', 'wpse52871' );
Here's another example of the filter in use.
**Additional**
You can also add a filter to single_template
`add_filter( 'single_template', 'wpse53871' );` | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "template hierarchy"
} |
making sense of admin-ajax
So I'm working with ThemeTrust's "reveal" theme, and there is an ajaxed in chunk-of-content that I'm really trying to change (grab custom meta fields (images) + insert into a slideshow). As far as I can tell the following piece of code grabs the content from the normal tinymce box and drops it in the `#projectHolder` div - but I can't figure out how to piggyback my php code on this request.
function loadProject(projectSlug) {
// Scroll to the top of the projects
jQuery("#projectHolder").load(
MyAjax.ajaxurl,
{
action : 'myajax-submit',
slug : projectSlug
},
function( response ) {
}
);
}
I suppose my answer lies somewhere in the 1500+ lines of `wp-admin/admin-ajax.php` but that seems awful daunting... | The function that returns the contents of that ajax request will not be in admin-ajax.php. That is the core WordPress file that handles ajax requests, but it is not used for specifying the data returned by ajax functions in themes / plugins.
In the theme (somewhere), will be a line that looks like this:
`add_action('wp_ajax_myajax-submit', 'some_function_name_here');`
The function called "some_function_name_here" (which will be named something different than some_function_name_here, as this is just an example) is what determines the data returned to jQuery.
Do a search in the theme files for "add_action('wp_ajax_myajax-submit'" and you should be able to find it.
If you don't find it with that search, then look for
"add_action('wp_ajax_no_priv_myajax-submit'" | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "custom field, ajax"
} |
changed custom post type now $image_attributes[0]; broken
i wanted to change the slug of a custom post type
so i
renamed
single-myslug.php
to
single-mynewslug.php
changed
$the_query = new WP_Query(array('post_type'=>'myslug','posts_per_page'=>8));
to
$the_query = new WP_Query(array('post_type'=>'mynewslug','posts_per_page'=>8));
and changed
*post type in wp-admin from
myslug
to
mynewslug
now only some image thumbnails are showing up when i use
style="background-image: url(<?php echo $image_attributes[0]; ?>)
certain images show
style="background-image: url()
some have images some dont.
<
thumbnail on some of these has dissapeared from wp-admin editor why would some just unattach themself from the post? | I don't know what you used to change the slug in the `wp-admin`, a plugin perhaps?
But I'm not sure if your method will update existing database posts. And if it does the way it did is probably where _something_ went wrong.
What **exactly** did you use to update your slug in the `wp-admin`? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types"
} |
Multiple post type queries (with specific arguments for each)
So i know how to combine post types into 1 loop and out put the loop. Below is what i have:
<?php
$args = array(
'post_type' => array('post','movie','actor'),
'posts_per_page' => '20',
);
query_posts( $args );
while ( have_posts() ) : the_post();
the_title();
endwhile;
?>
This works as expected, however is it possible to specify different arguments for each post type, while keeping them within the same original loop.
So for example i need to add a `meta_key=value` argument to the `movie` & `actor` post types. Is this possible? | Could you do something like this?
<?php
$args = array(
'post_type' => array('post','movie','actor'),
'posts_per_page' => '20',
);
query_posts( $args );
while ( have_posts() ) : the_post();
global $post;
if (($post_type == 'movie') && (get_post_meta($post->ID, 'meta_key', true) == 'your-value')) {
// Display your content for Movie Post Type with meta value set
} else if (($post_type == 'actor') && (get_post_meta($post->ID, 'meta_key', true) == 'your-other-value')) {
// Display your content for Actor Post Type and Other Meta Value
}
endwhile;
?> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "custom post types, wp query, query posts, post type"
} |
WordPress plugin for Limited days user
I have free demo use of my application for 10 days then use automatically disable. Not delete.
After he pay us for using that application for 1 year we can extend that time duration.
If there is no any plugin, any snippet suggestion ? | The Membership plugin does that pretty much out of the box, if i recall correctly. Not sure if only on the paid version, though. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, users"
} |
How does Wordpress handle sessions?
I know that Wordpress is stateless and doesn't use any global session variables, but when a user logs in via Wordpress, it must somehow keep track of who is logged in, right? Does Wordpress keep track of that in cookies?
I'm working on a plugin that must keep track of something similar. I can easily store some data in transients, but is there a unique identifier available that can identify a user, whether he or she is logged in to Wordpress or not? I would then use that to access the transient, for example. | Yes, WordPress uses cookie to keep track of who is logged in in cookies. But you don't have to rely on it. If you want to check if user is logged in, you can just use is_user_logged_in function and you can identify a user by his/her ID which you can get by calling get_current_user_id function. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "login, transient, session"
} |
Which Versions of WordPress Ship with the Patched TimThumb?
Do you recall when the TimThumb exploit occurred? Which versions of WordPress bundled with this exploit? I need to inform a client that they should be upgrading to at least the version of WP when this exploit was patched.
Yes, I'm aware of the separate issue where TimThumb is also used in plugins -- that's a separate issue. I'm talking about the TimThumb used inside WP in older versions. | TimThumb has never been bundled with WordPress, it is/was entirely a third-party theme/plugin issue. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "security, wordpress version, timthumb"
} |
How to check if the Menubar contains no items?
I'm using the Menubar plugin to place a menu at the top of my website. However, I need to find a way to check if the menu contains items or not. My menu is called 'menubar'. Currently, I'm loading the menu like so:
do_action('wp_menubar', "menubar");
It loads fine, but I need to check if there are items in it or not so I can adjust and display other things instead. Any ideas? Or is this question too vague? | Try this:
$meniu = count(wp_nav_menu( array('menu' => 'menubar' )));
if($meniu > 0 ){
//here goes your stuff if we have items in menu
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, menus"
} |
How to determine (via php) if site is using a static home page?
I have a script that needs to know if the site is using a static home page. In other words, at "Settings > Reading > Front Page Displays > a Static Page ___ _"
Is there a a get_option() or method call that can be used to determine this? | get_option( 'page_on_front' );
If this value is not `0`, there is a static page.
Additional note from Johannes Pille:
get_option( 'show_on_front' );
… returns `post` or `page`. But be aware of custom post types as front page.
A good way to find common options is to visit the (hidden) page `wp-admin/options.php`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development"
} |
WordPress Network (MU): Copy Main Site to Sub-Site
I would like to copy all the posts, users, and pages from my main site into a sub site. I've tried exporting and importing, but the main site has thousands of entries and hundreds of users, and the import seems to fail at around 250 posts without an error. Any ideas for the migration would be greatly appreciated. | I was able to use the standard WordPress import and export by raising the maximum memory limit in `wp-config.php`:
define( 'WP_MAX_MEMORY_LIMIT', '1024M' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "migration, multisite, post duplication"
} |
How to convert that page to a wordpress template?
Couple of days I am trying to integrate THAT page in wordpress. I converted it to wordpress theme but can't make the images to loads. All I see is the loading circle. I changed the path in javascript that call the ajax file:
$.get('
but no result.
I changed even the paths in thumbs.php (example from ../thumbs to full path or with blog_info command )...and again-no result.
Any ideas what else I have to change? I deactivated all plugins, but the site still doesn't work.
I would be very grateful if you help me.
p.s.sorry for my english | ok, i found the answer: In thumbs.php change `../images` and `../thumbs` to `../wp-content/themes/YOURTHEMENAME/images`, `../wp-content/themes/YOURTHEMENAME/thumbs`. Same in js. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, themes, javascript, customization"
} |
Code to make a post sticky
How is it possible to upgrade a post to make it sticky directly from code, not by admin area? Is it possible through a code like:
update_post_meta($post_id, $meta_key, $meta_value, $prev_value);
In this case, the $post_id is known, but the $meta_key?
Thank you in advance for your answers | The sticky posts are saved as an array of post IDs in the _wp_options_ table. Hence,
$stickies = get_option( 'sticky_posts' );
$stickies[] = $post_id;
update_option( 'sticky_posts', $stickies );
will make the post in question sticky.
**EDIT:**
Even better, the core provides functions to stick and unstick posts (had to have 'em).
stick_post( $post_id );
unstick_post( $post_id );
\--> See source on trac | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 6,
"tags": "posts, sticky post, post meta"
} |
Uploading PDF files from the front-end
I am working on a Wordpress site that has a custom front-end form for submitting posts. I need to add a field in the form to allow users upload a single PDF file along with the post. How can I achieve this? | I have done a simple function for that, but i allow all types of media. So this could be a start:
function insert_attachment( $file_handler, $post_id, $settpdf='false' ) {
// check to make sure its a successful upload
if ( $_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK ) __return_false();
require_once( ABSPATH . 'wp-admin' . '/includes/image.php' );
require_once( ABSPATH . 'wp-admin' . '/includes/file.php' );
require_once( ABSPATH . 'wp-admin' . '/includes/media.php' );
$attach_id = media_handle_upload( $file_handler, $post_id );
if ( $settpdf ) update_post_meta( $post_id,'_pdf_id', $attach_id );
return $attach_id;
}
and then a input like: `<input type="file" name="uploaded_pdf">`
You can retrive the meta like this:
$pdf = get_post_meta($post->ID, '_pdf_id', true);
echo '<a href="'.$pdf.'"><?php __('Download PDF','mytheme'); ?></a>'; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "uploads, forms, front end"
} |
get current user not working
I was trying this code to get current user info, but showing nothing. My WordPress version is 3.3.1
<?php
wp_get_current_user();
/**
* @example Safe usage: $current_user = wp_get_current_user();
* if ( !($current_user instanceof WP_User) )
* return;
*/
echo 'Username: ' . $current_user->user_login . '<br />';
echo 'User email: ' . $current_user->user_email . '<br />';
echo 'User first name: ' . $current_user->user_firstname . '<br />';
echo 'User last name: ' . $current_user->user_lastname . '<br />';
echo 'User display name: ' . $current_user->display_name . '<br />';
echo 'User ID: ' . $current_user->ID . '<br />';
?>
**The output is:**
Username:
User email:
User first name:
User last name:
User display name:
User ID: | Have you tried to go with the "Safe usage" alternative given in the commented section?
I honestly don't have any experience with `wp_get_current_user()`, since I never use it, but anyhow, this ought to work:
global $current_user;
echo 'Username: ' . $current_user->user_login . '<br />';
echo 'User email: ' . $current_user->user_email . '<br />';
echo 'User first name: ' . $current_user->user_firstname . '<br />';
echo 'User last name: ' . $current_user->user_lastname . '<br />';
echo 'User display name: ' . $current_user->display_name . '<br />';
echo 'User ID: ' . $current_user->ID;
`wp_get_current_user()` should do the same, as it is nothing but a wrapper for the first two lines above, nonetheless, the above has got to work. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 1,
"tags": "user meta, users"
} |
Can local WordPress installs share /wp-content/ folder and database?
On my local machine, I have multiple wordpress versions installed so I can test the themes and plugins I develop.
I was wondering if I could somehow create a central wp-content folder and database, which are linked to each version of wordpress, so I don't have to continually copy my projects between the them? | For `wp-content` folder you need to add WP_CONTENT_DIR with path to this folder to each `wp-config.php` file of each your sites. All of these WP_CONTENT_DIR constants should have the same path to one folder. Read more about it here: <
To share the same database, you just need to setup the same database settings in each `wp-config.php` files. Read about it here: <
**UPDATE:** To make your urls work correctly define `WP_SITEURL` and `WP_HOME` constants which will override options settings. Read about it here: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "database, content, customization, local installation"
} |
How do I get the $handle for all enqueued scripts?
Is there some way to get the $handle for each script that has been enqueued?
Is there some array that holds all the handles so that I can loop through it and do something using each $handle? | the `$wp_scripts` global holds all the script data:
function wpa54064_inspect_scripts() {
global $wp_scripts;
foreach( $wp_scripts->queue as $handle ) :
echo $handle;
endforeach;
}
add_action( 'wp_print_scripts', 'wpa54064_inspect_scripts' ); | stackexchange-wordpress | {
"answer_score": 32,
"question_score": 25,
"tags": "wp enqueue script, scripts"
} |
Default PHP document / names needed for a Wordpress theme?
I am hosting my own version of Wordpress, and I'd like to do a custom theme for it to suit my website.
However, with so many bits and pieces of examples on the Internet, I'm not really sure how many PHP documents I should have, and what names are they given inside a theme.
So far, i only understand that there are the following PHP documents inside a Wordpress Theme itself :
404.php
comments.php
footer.php
functions.php
header.php
index.php
page.php
sidebar.php
single.php
style.php
Are there anymore? Is there a full list that I can refer to (like a cheat sheet)? | The template files list in Codex contains most of the templates. See also the template hierarchy page for dynamic, content-specific templates like `single-{post_type}.php`.
Note that a valid theme only needs to have a `style.css` and `index.php` files, all other template files are optional. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development"
} |
WordPress save thumbnail but don't show it
WordPress don't show image thumbnail but save them.
I have all version of image (eg. image.jpg, image-300x250.jpg) but WordPress don't detect them.
Anybody got same problem as here? | I changed my thumbnail size to 300x240. It's odd but now it works! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post thumbnails, thumbnails"
} |
Is there any way to dynamically alter widget titles?
I have a case where that are a lot of widgets in several custom sidebars. I am wondering if there is a simple way to alter the titles of each widget dynamically. Typically a widget has a title field you can set manually or on the plugin itself.
I wish to add something like a meta field value per post to each widget title.
The logic would be something like:
$dynamic_title = get_the_title();
// add a filter to change the widget titles per post value
//
// The widget title would be something like "Recent Posts for $dynamic_title"
I know there is a `widget_title` filter but how do you target specific widgets?
ps. I cannot use the regular `register_sidebar` parameters due to having many widgets needing specific titles. | You can use the `widget_display_callback` (fired, predictably, just prior to displaying a widget :) ).
add_filter('widget_display_callback','wptuts54095_widget_custom_title',10,3);
function wptuts54095_widget_custom_title($instance, $widget, $args){
if ( is_single() ){
//On a single post.
$title = get_the_title();
$instance['title'] = $instance['title'].' '.$title;
}
return $instance;
}
The `$widget` argument is an object of your widget class, and so `$widget->id_base` will contain the ID for your widget (if targeting a specific widget class). | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 9,
"tags": "widgets, title"
} |
Is there a way to show attachment IDs on the attachment info screen?
I want to use attachment IDs for shortcodes, but if the image is published with a permalink, it's harder to find the ID.
I've found some functions online that can turn the attachment url into its ID, but that's ridiculous if I have to use a function every time I want to use the shortcode in my posts.
Trying to do: `[stuff include="1,4,55"]`
Instead of: `[stuff include=" | You could hook into `'attachment_fields_to_edit'` and just add a row:
<?php # -*- coding: utf-8 -*-
/**
* Plugin Name: T5 Show Attachment ID
* Version: 2012.06.04
* Author: Thomas Scholz <[email protected]>
* Author URI:
* License: MIT
* License URI:
*/
if ( ! function_exists( 't5_show_attachment_id' ) )
{
add_filter( 'attachment_fields_to_edit', 't5_show_attachment_id', 10, 2 );
function t5_show_attachment_id( $form_fields, $post )
{
$form_fields['t5_id'] = array (
'label' => 'ID',
'input' => 'html',
'html' => "<strong>$post->ID</strong>",
);
return $form_fields;
}
}
Result:
 Thank you for pointing me .. :) | You need to use custom endpoints for it. Read The Rewrite API: Basics article for more information, especially section **Add Custom Endpoint**. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, urls"
} |
Trying to display terms from custom taxonomy within function
I have a function that is giving me this error - `Catchable fatal error: Object of class stdClass could not be converted to string in.... blah blah`
Below is some of the code from the function. It is the last line that is giving the error but I can't work out why. I'm trying to display the term with ID 7 in the project_cats taxonomy.
$html_content .= "<h3>" . rgpost('input_1') . "</h3>"; //Title
$html_content .= "<p><strong>Category:</strong> " . rgpost('input_5') . " | <strong>Budget:</strong> " . rgpost('input_3') . "</p>"; //Category & Budget
$html_content .= "<p>" . rgpost('input_4') . "</p>"; //Description
$html_content .= "" . get_term_by('id', 17, 'project_cats') . ""; | Function `get_term_by` returns object or array (based on `$output` arg) on success and false if failed. But you treat it as string and try to concatenate it. So your code should be following:
$cat = get_term_by('id', 17, 'project_cats');
$html_content .= "<h3>" . rgpost('input_1') . "</h3>"; //Title
$html_content .= "<p><strong>Category:</strong> " . rgpost('input_5') . " | <strong>Budget:</strong> " . rgpost('input_3') . "</p>"; //Category & Budget
$html_content .= "<p>" . rgpost('input_4') . "</p>"; //Description
$html_content .= $cat->name;
Read more about this function in codex. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, taxonomy, errors, terms"
} |
Check which user saw which page
How can I have analytics which show which registered user saw which page? Is there a plugin that can provide this functionality? | If you use Google Analytics, you can add custom variables to the tracking code to pass a user ID. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "statistics"
} |
Add mass action to wp-admin/users.php
I'm heavelly modified my Wordpress, it's amazing what you can do with wordpress hooks, actions.. But i'm not able to find how can i add mass action for users. Let's say i select 5 users and i want to asign them some user_meta value. | Unfortunately this isn't possible. Custom actions cannot be added to the bulk actions dropdown (see trac tickets: < and <
For posts you can use the `restrict_manage_posts` hook to create another drop-down / add buttons to trigger your custom action. But there is no `restrict_manage_*` hook available for the user table.
So the only (and not particularly pretty) workaround is to use javascript to insert extra options into the drop-down menu.
However, there is no (supported) way of handling the action - so this would also have to be handled yourself by hooking into the `load-*` or `admin_action_*` hook. (See the core files here).
You would then need to check the posted data (the user IDs, the action identifier, nonce, etc) inside that hook and then you would need to check the nonce and the current user's capability to perform that action.
See related question: Custom bulk_action | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "wp admin, user meta, bulk"
} |
Is Timthumb still broken? What security measures should be taken?
A client has requested we use a theme, and that theme has a Timthumb dependency. I know that there has been some serious vulnerabilities in the past, but what is the current state of that plugin?
Can someone point me to an authoritative resource that addresses this vulnerability? It doesn't appear that the plugin is still being maintained / available in the repo?
Thanks | Take a look here: < I assume you know who Matt is. Also, Matt mentioned this guy in that link, and he's got some updates on the issue posted to his site <
The short is, there's now TimThumb 2.0 which is fixed. It's available here < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, security, timthumb"
} |
Get number of widgets in sidebar
How can I get the number of widgets that are active on a specific sidebar? Is there a core function for this?
I want to add a class to each widget on a sidebar based on how many of them are displayed.
Thanks. | After some research and based on the answer from Eugene Manuilov I made a function that adds custom classes to widgets in a specific sidebar ('sidebar-bottom' in my case) based on the number of widgets set in that sidebar. This will suit perfectly in horizontal sidebars and themes based on twitter bootstrap that need spanX class to adjust the element's width.
function cosmos_bottom_sidebar_params($params) {
$sidebar_id = $params[0]['id'];
if ( $sidebar_id == 'sidebar-bottom' ) {
$total_widgets = wp_get_sidebars_widgets();
$sidebar_widgets = count($total_widgets[$sidebar_id]);
$params[0]['before_widget'] = str_replace('class="', 'class="span' . floor(12 / $sidebar_widgets) . ' ', $params[0]['before_widget']);
}
return $params;
}
add_filter('dynamic_sidebar_params','cosmos_bottom_sidebar_params'); | stackexchange-wordpress | {
"answer_score": 13,
"question_score": 8,
"tags": "widgets, sidebar"
} |
How can I remove the first two words and shorten get_the_title()
Some of my posts' titles have leading words, followed by a colon. I am removing the leading words and the column of every post title in the loop with the following:
<?php
$title = get_the_title();
$title_array = explode(':', $title);
$first_word = $title_array[1];
echo $first_word;
?>
How can I also limit the total length of the remaining title by character count? | $title = get_the_title();
$title_array = explode(':', $title);
$first_word = $title_array[1];
$total_length_limit = 100;
echo mb_substr( $first_word, 0, $total_length_limit ) . '...'; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, php, loop, title, get the title"
} |
Pronamic Info Window
I am using Pronamic Google Maps (< to add Google Maps to my post...I would like to do a couple of things:
1. I noticed that the balloon, or info window, has to be clicked in order for it to appear, is there a way to make it appear by default?
2. Also on the balloon, or info window, I see a scrollbar which appears regardless of how much content is being shown...is there a way to remove the scrollbar when not in use?
Thanks in advance! Josh | I ended up just switching plugins...I am now using MapPress: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, customization"
} |
Per Post Type Revision Numbers
In `wp-config.php` you're able to change how WordPress deals with post revisions. Specifically you're able to turn them off or specify a max number of revisions.
I'd like to be able to set a max number or revisions on a post type basis.
Is this possible? | 1. Remove the action `'wp_save_post_revision'` from `'pre_post_update'`. It is set per default in `wp-includes/default-filters.php` with the default priority (10).
2. Add your own function to this hook. You get the `$post_ID` as parameter, so detecting the post type is easy.
3. In your callback copy the code from `wp_save_post_revision()` but use the constant `WP_POST_REVISIONS` for the post type `post` only, and use different values for other post types. Not sure if it is possible to pass extra values in `register_post_type()` … | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 7,
"tags": "custom post types, post type, revisions"
} |
CRUD operations using WordPress database API
What is the correct way to query a WordPress database?
I would like to achieve a similar output as seen in the _links_ section of WordPress Dashboard so as to be able to perform _edit_ and _delete_ operations on given table rows / columns, individually.
I've made use of knowledge drown from several articles on setting up database tables in WordPress and as such was able to build the front-end so as to accommodate both _edit_ and _delete_ operations; what I currently need is a solid example of how to make use of the WordPress database query API in order to perform all CRUD operations. | Querying in WordPress is done by using the the `wpdb` variable. Be sure to always prepare your sql so WP can make it database safe.
Example:
global $wpdb;
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `{$wpdb->prefix}TABLE_NAME` WHERE `var` = %d", 1) );
Then you can loop through the data and output it as for example a table (table formatting not included).
foreach($rows as $row)
{
echo $row->post_title;
}
Please note that the SQL query above doesn't work because it contains dummy data. Please change it so it fits your needs. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "database, query, mysql"
} |
How do I make header.php use different css for different pages?
I register styles in `function.php` with
function my_scripts() {
wp_deregister_style( 'header' );
wp_register_style( 'header', get_template_directory_uri() . '/css/header.css' );
wp_enqueue_style( 'header' );
}
add_action( 'wp_enqueue_scripts', 'my_style_sheets' );
I'd like to use different header style sheet for the same header.php file used on another page. How do I do that?
In general, how do I use styles differentiated by template instead of using a global setting like the one above? | Create a primary stylesheet and enqueue as normal. Then, make a series of conditional statements using WP core functions - `is_home()`, `is_404()`, `is_page_template('template.php')` and so on. In each of those conditionals, enqueue the stylesheet you want that overwrites your core stylesheet, using your primary (`style.css`) stylesheet as a dependency.
Untested code, but should work:
function my_styles() {
wp_deregister_style( 'header' );
wp_register_style( 'style', get_template_directory_uri() . '/css/style.css' );
wp_enqueue_style( 'style' );
if (is_home()) { wp_enqueue_style('homestyle', get_template_directory_uri(). '/css/homestyle.css', 'style'); }
}
add_action('wp_print_styles', 'my_styles'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "css, wp enqueue style"
} |
How do i 'deactivate' a plugin only on a certain page template?
I have a plugin which is great but it's kind of aggressive, and it changes a lot more than it should (but there are no settings to fix this).
I have a custom page template that calls wp_head('less') ... header-less.php, and i have an equivalent for footer-less.php.
I basically want, in this custom header-less.php to DE-REGISTER the plugin immediately after it gets registered.
note that i dont want to DeACTIVATE the plugin, because i really need the functionality on the other page templates, only on this certain template do I want to basically 'destroy' the plugin or deactivate it somehow | A quick glance at that plugin shows that it loads the filters from an option, `trueedit_options`. You might be able to add a filter to `option_trueedit_options` and check the context of when that option is being loaded and return an empty array. It runs on `init` though, so not sure how you'd determine that.
Another option is to add the filters back on in your header file. If you look in `/wp-includes/default-filters.php` you'll see all of the filters that are added to the content which could potentially be removed by the plugin:
add_filter( 'the_content', 'wptexturize' );
add_filter( 'the_content', 'convert_smilies' );
add_filter( 'the_content', 'convert_chars' );
add_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'shortcode_unautop' );
add_filter( 'the_content', 'prepend_attachment' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, headers"
} |
getting the post_id from the post_meta
I need to find out the post_id of a post_meta record where the custom key is 'XYZ' and the is 'ABC'? Is there an API for that?
Or do I need to run a regular select SQL with wpdb class? | You should use WP_Query in this case ...
$my_query = new WP_Query( array( 'meta_key' => 'XYZ', 'meta_value' => 'ABC' ) );
$post_ids = array();
while ( $my_query->have_posts() ) {
$my_query->next_post();
$post_ids[] = $my_query->post->ID;
}
wp_reset_postdata();
... and read on here. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post meta"
} |
remove admin bar show hide option from profile settings
Do not misunderstood.
I am trying to remove/disable Show toolbar option (not talking about hide/disable admin bar) but talking about The Option into Profile Settings.
I tried to search but in all I found only how to disable admin bar from front and back but nowhere I found how to remove the check-boxes from profile settings. | the fields are hard coded there is nog filter or action to disable it.
You could hide it with CSS....
If you want you could replace the entirely page with a different one you custom create. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "profiles, admin bar"
} |
What is the most efficient method for loading widgets in functions.php
I have seen WordPress developers use two different methods for loading custom widgets from the functions.php file.
The first:
include("functions/my-custom-widget.php");
The second:
require_once(dirname(__FILE__) . "/functions/my-custom-widget.php");
Which one of these methods is more efficient. I'm particularly interested in performance if there is a difference at all. Does the require_once follow better 'best practices' ?
I'm sure there are plenty of other ways of doing this. If anyone has a better recommendation I would love to hear it.
Thanks. | Both are acceptable but not recommended. Use `locate_template()` instead because a child theme can overwrite the loaded file then.
Example:
$found = locate_template( 'functions/my-custom-widget.php', TRUE, TRUE );
The first `TRUE` tells WordPress not only to _search_ for the file but to _load_ it actually. The second makes it a `require_once` call.
The function return the path to the located file in case you need it later. If nothing is found it returns an empty string. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "functions, widgets, include"
} |
Display Notification Bar on Header on Certain Post Count
I want to display notification bar on header in my Wordpress theme when user submit certain number of post. I want to notify my author once they are submit amount of post. e.g.
if (authorpost === 50){
// congratulations! you have submitted total 50 posts bla bla.
} else if (authorpost === 100) {
// congratulations! you have submitted total 100 posts bla bla.
} else { // nothing will display }
I want this into header.php and will place my div right after tag. Also I want to display only when they submit certain number of post as I mention above as soon as they cross that number it won't display anything. | A simple way to achieve this would be to do something like the following;
<?php
$user_id = get_current_user_id();
$post_count = count_user_posts($user_id);
if ($post_count >= 50 && $post_count < 100) {
// Congratulations you have submitted 50 posts!
} elseif ($post_count >= 100) {
// etc etc...
} else {
// do something else, or nothing.
}
?>
You can place this within your header.php file, or for that matter in any template file should you choose to display this information elsewhere as this can run from out-side of your post loop.
WordPress API resources:
* `get_current_user_id` LINK
* `count_user_posts` LINK | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "posts, author, count"
} |
How to make media upload private?
> **Possible Duplicate:**
> How to Protect Uploads, if User is not Logged In?
I know how to mark a Page or Post as visible only to members, using the Member Access plugin. This way, the public cannot view them; instead, you have to log in to see the page.
How do I mark a PDF or other Media upload as visible only to members? | Searching this Stack, I can see two possible solutions for this question (not tested).
### One
The answer is not fully developed, but can provide some insight.
Restricting access to files within a specific folder
### Two
How to Protect Uploads, if User is not Logged In?
_Frank Bueltge's_ answer seems interesting but the code is quite complex. As he himself admits his english is nasty, but I can assure his coding skills are superb :)
And the answer provided by _hakre_ could be operational:
* Protecting one or more folders inside `/wp-content/uploads/` through `.htaccess` as detailed there.
* Moving the desired files to this upload folders according to User or Post-ID, and for that the answer I provide to this question should do it. And, with the examples provided, maybe you can think of other kind of filtering. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "plugins, security"
} |
Single database for multiple instances
I would like to create two instances of WP on a single domain. For example, I would like wp1.domain.com and wp2.domain.com to use a single database (same comments/posts). One for production and one for development. Is this possible, and if so, how? | It's considered best practice to have two separate databases (one for production, one for development) then migrate the database as detailed here. If you, for example, install a database-changing plugin on one but not the other, you risk breaking one of your sites until you duplicate those changes over. If you're working late tweaking code, you might end up breaking your live site and not realizing it until the angry client calls to rip you a new one.
Really, keep your production and development sites completely separate. It will save you a number of hassles down the road.
If you only have access to a single database, set each site to use a different database prefix. This ensures easy duplication with standard SQL tools while keeping separate dev/prod environments. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "database"
} |
Should I remove_filter in order to replace a filter?
If a plugin modified one of wp's filters by "add_filter", and I want to discard the modification and modify the wp's filter by my own codes. Should I remove the plugin's filter before I add my own filter? | Yes, you need to remove it first and then add your one. You can do it by calling remove_filter function like this:
remove_filter( 'wp_core_filter_hook', 'wp_core_filter_hook_handler', 10 );
Pay attention at third parameter passed to function: it is priority, it should be the same as defined when the function was originally hooked, otherwise the filter hook won't be removed.
If you want to remove all hook handlers, you can call remove_all_filters function:
remove_all_filter( 'wp_core_filter_hook' );
// or with priority
remove_all_filter( 'wp_core_filter_hook', 10 );
This function takes two parameters: filter name and priority (optional). If you pass priority then all handlers with specified priority will be removed.
And finally if you want to check if any filter has been registered for a hook, use function has_filter. It takes two parameters: filter name and function name (optional). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "filters"
} |
How to change "Draft" string for status of custom post type to "Unavailable"?
**ANSWER MOD** : just an important mod to the chosen answer:
// check if you actually have drafts; also avoids extra '|' separator
if (isset($views['draft'])) {
// 'Drafts' should be added (and come first) if you don't want to end up with 'Unavailables'
$views['draft'] = str_replace(array('Drafts','Draft'), 'Unavailable', $views['draft']);
}
and the mentioned caveat is not showing up for me on 3.4. :D
* * *
Only for one particular custom post type `employee`, I want to change the name/string "Draft" (which stands for the `'draft'` status) to "Unavailable" for any `employee` post that has a `'draft'` status, anywhere the name shows up on the admin screens and basically throughout the entire site, i.e.
!enter image description here
Is there a hook for this? Or is there a better way to do this? | I was investigating the issue for this question, and one option is using the plugin Edit Flow.
It can be configured to display custom `post_status` in specific CPT's, but further tests are necessary to see if it applies to this case.
* * *
Other option is using toscho's Retranslate plugin, where you can define the string to be translated and the `post_type`: <
It gets almost all the job done, because, curiously, there's one string (the very first one of the screenshot) that don't gets translated and one extra code is necessary:
add_filter( 'views_edit-employee', 'wpse_54330_custom_draft_translation', 10, 1);
function wpse_54330_custom_draft_translation( $views )
{
$views['draft'] = str_replace('Draft', 'Unavailable', $views['draft']);
return $views;
}
One caveat of this method is that just after "quick editing" the post status, the word _Draft_ appears... | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 6,
"tags": "custom post types, filters, actions, customization, post status"
} |
How to remove this filter?
I can't remove a filter that added by media-tags plugin. it was originally added this way:
add_filter( 'attachment_fields_to_edit', 'mediatags_show_fields_to_edit', 11, 2 );
I tried to remove it this way:
remove_filter( 'attachment_fields_to_edit','mediatags_show_fields_to_edit', 11, 2 );
Where I did wrongly? How can I remove this filter? | It depends on the call sequence. Are you sure that the `remove_filter` is called after the `add_filter` and before the `attachment_fields_to_edit` filter is invoked? Add few trace statements and verify. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "filters"
} |
Wordpress redirection to get url friendly
I want to get url friendly for pass data to page from other page. I explain :
I have on i classic wordpress page, url like it : ( example.com/agent/name_agent ) it's url build dynamically. ( get_permalink($id_page_agent) . $name_agent )
In my loop-agent.php , i can manage $_GET['agent_name'] to make a filter.
I need to build redirection example.com/agent/name_agent > example.com/agent/?agent_name=name_agent
I don't know if you understand ? | Rather then trying implement something for you, I would recommend you to read these two nice articles about Rewrite API: The Rewrite API: The Basics and The Rewrite API: Post Types & Taxonomies. Spare no effort to read these articles and it will help you a lot in a future. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "url rewriting, htaccess"
} |
query_posts doesn't order by title
It seems like stupid bug, but how can i order by title? It anyways orders by date! I'm using:
query_posts( array(
'post_type' => 'page',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC'
) );
I want to use this in function as SHORTCODE. What i'm trying to achieve is to create site map / index of all entries in alphabetic order. Also i'm using newest WP. | Thanks to Chip Bennett who told me that i'm doing wrong by using `query_posts` inside content. So i used `get_posts` and i got what i wanted, thanks!
Here is sample of how can you do it, if you got the same problem as me:
function some_name(){
global $post;
$tmp_post = $post;
$args = array( 'post_type'=>'page', 'numberposts' => -1, 'orderby'=> 'title', 'order' => 'ASC' );
$myposts = get_posts( $args );
if ( !empty($myposts) ) {
foreach( $myposts as $post ) : setup_postdata($post);
the_title();
echo '<br>';
endforeach;
}
$post = $tmp_post;
} | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 3,
"tags": "query posts, title, order"
} |
Restored Wordpress on new Server - Can't auto-update plugins
I have installed a new Ubuntu server and have set everything up for Wordpress. I have also extracted mySite directory in the /var/www/ and did a `mysql -u mysqlusername -p databasename < blog.bak.sql` to restore the data to the database.
It all worked smooth and works beautifully.
The only problem I have discovered is when I try to auto-update the plugins.
Please click to see the screenshot (I don't have enough reputation to insert a screenshot here) <
Well, I have never setup any FTP on my previous server. How comes this is now asking me this information? And yes I was able to auto-update plugs on my other server without a problem.
Thanks, | This is most likely because of file permissions on your server. WordPress needs to be able to write to the `wp-content` folder. I highly suggest you read this article about changing file permissions for WordPress.
You may also need to CHOWN the directory that contains WordPress to the user that your web server uses. More here. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, ftp, automatic updates"
} |
How to edit/delete single row items in a table on my own menu page
I have successfully created a wp-LINKS-list-table that displays the output of WP's core "Links" table in the WP Dashboard, and I have it displaying on a menu page I created. Step 1 accomplished!
But now I would like to be able to have the single row edit/delete (database) functionality just like the Links page. Right now I can edit/delete the links, but it's just adding/removing items from the actual links database table. I'm assuming that I not only have to create a different database table for my own queries, but I need to process my pages outside of the WordPress core as well. Right?
Or is there a core WP functionality that I can use to edit/delete my own table items? | Wordpress allows you to use a class called wpdb
Here is an example of how you would use it
function add_to_db() {
global $wpdb;
$your_table_name = $wpdb->prefix . "wp-LINKS-list-table";
$the_value = '123';
$wpdb->insert( $your_table_name, array('column_name' => $the_value,));
this will insert 123 into the column_name. You can read more here
Note: If you are creating a menu page that reflects the tables similar to the wordpress tables there is another class you can use to help you. It is called WP_List_Table I would suggest reading that and getting the Custom List Table Example Plugin it is very helpful showing examples of using WP_List_Table. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugins, php, admin, database"
} |
How can I stop TinyMCE from converting my HTML entities to characters?
Here's the problem: I paste the HTML entity code for, let's say, a service mark (`℠`) into the HTML view of the editor. As soon as I switch to the "visual" tab, my entity code is turned into an _actual service mark character_ (I guess the corresponding UTF-8 character or something? I don't know from character encodings...). I don't want this--I want it to stay as the entity reference.
Is there some kind of configuration I can change to stop TinyMCE from doing this? My understanding from reading the internets is that this is not the default behavior--that TinyMCE should actually be doing the opposite, and converting characters to their entities. So is this something specific to WordPress' version of TinyMCE? | According to this page, you can use the `tiny_mce_before_init` filter, make sure the entity encoding is set to `named`, and then add whichever special characters you want to the entities array. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "tinymce, editor, wysiwyg, encoding, characters"
} |
Disable pingbacks and trackbacks in blog posts
Just created a new self-hosted WordPress blog, and among the very first things, I "unchecked" the `Allow link notifications from other blogs (pingbacks and trackbacks)` option under **Settings** > **Discussion**.
I was fixing a few things for the to-be-launched-soon blog, when I noticed a pingback on the default **"Hello world!"** post on my blog.
But I've already disabled pingbacks/trackbacks, so why exactly is this happening? What could be wrong? | The thing is, the default post has both comments and pingbacks/trackbacks enabled by default. And post or page level settings override the site-wide settings.
So, for ONLY the **"Hello world!"** post (if you are not deleting it), you'll have to specifically uncheck `Allow trackbacks and pingbacks on this page.` option which is available when you check the **Discussion** option under **Screen Options** menu:
!ping/track | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pingbacks"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.