INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to make certain page templates visible to admin only
Making a site for a client, I have some pages that the client won't be able to edit or delete. These pages rely on specific page templates.
However, I don't want these templates to be available for the client when creating new pages. Is there someway to hide these certain page template from the page attributes dropdown when creating new pages?
Thanks | Rather than defining them as custom page templates, you have an alternative.
Use the page specific templates, e.g. for a profile page, with the slug `profile` you could create a `page-profile.php` in your theme, or you can use `page-21.php` where `21` is the ID of that page/post. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "pages, admin, wp admin, page template"
} |
Rename page URL
I have the following URL structure:
`id` specifies the `id` of the post.
`gallery` is a normal page inside which I am accessing the `id` of the post and fetching the attachment images using `WP_Query()`.
I want to replace the URL of this page to:
in which the parameters `place` and `new-delhi` may vary in multiple other options and `topic` is the keyword which remains the same.
I have tried using some unfruitful `.htaccess` file code.
Can anyone please help? | I have tried some add_rewrite_rule magic and query variables and it worked. Thanks for the help everyone.
If in case anyone want to refer the answer:
add_filter( 'query_vars', 'wpse26388_query_vars' );
function wpse26388_query_vars( $query_vars ){
$query_vars[] = 'custom_gallery_id';
return $query_vars;
}
add_rewrite_rule(
'topic/([^/]+)/([^/]+)/gallery/([0-9]+)/?$',
'index.php?pagename=gallery&custom_gallery_id=$matches[3]',
'top' );
I was able to solve my problem with this. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "url rewriting, urls, rewrite rules"
} |
Remove some pages from search
On my site, I want some pages to not be queriable by the search form (so they don't appear when I've got something like www.ex.com/?s=banana)
Is there a way to "Remove" pages from the search results page (without just blindly do a condition of if is_page(id), display:none) | In WP_Query() there is a 'post__not_in' argument where you can exclude specific post ID's.
You would create a new WP_Query inside of your search.php and use the current $query_args, then add on your 'post__not_in'.
If you wanted to make it more dynamic, you could also build in some post meta where you could do a meta query and exclude all that have "exclude" checked. (look up 'register_meta_box_cb' in register_post_type ).
For example,
add_action('pre_get_posts','wpse67626_exclude_posts_from_search');
function wpse67626_exclude_posts_from_search( $query ){
if( $query->is_main_query() && is_search() ){
//Exclude posts by ID
$post_ids = array(7,19,21);
$query->set('post__not_in', $post_ids);
}
} | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 10,
"tags": "search"
} |
How to replace or display the special characters from JSON API plugin
!enter image description hereI started using the JSON API plugin. It works good ! But the problem i am facing is, If i enter any text containing special characters through CMS The output is not same as the given text. Why this is happening?
Example: It's a good app (Input) The output looks like It ' s a good app. Please suggest any tips/methods to get rid of this situation.
Eagerly waiting for your response. Thank you | That's probably because the "JSON API plugin" htmlescapes your text. So if you would just display it on site it should print OK, but if you need to work with it on the backend than just use `html_entity_decode()` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, plugin json api, web services"
} |
Use wp init hook to call other hooks?
I want to know if it is a good practice according to WordPress theme or plugin development.
add_action('init','all_my_hooks');
function all_my_hooks(){
// some initialization stuff here and then
add_action('admin_init',-----);
add_action('admin_menu',----);
// more like so
}
thanks | In general: Yes, wait for a dedicated hook to start your own code. Never just throw an object instance into the global namespace. But `init` is rarely necessary.
You hook in as late as possible. If your first code runs on `wp_head` do not use an earlier hook. You can even cascade hooks:
add_action( 'wp_head', 'first_callback' );
function first_callback()
{
// do something
// then
add_action( 'wp_footer', 'second_callback' );
}
Regarding the `init` hook: Use `wp_loaded` instead. That runs after `init` and after `ms_site_check()` was called. This way you avoid to run your plugin on an invalid sub site in a multi-site installation. Everything else is the same. | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 13,
"tags": "hooks, customization, init, admin init"
} |
get_the_category_list() does not give me all my categories
I am trying to use `<?php echo get_the_category_list(); ?>` in my `footer.php` file to display my categories. On the home page, this function is showing only two categories and in inner single posts it shows that post's related category. In pages, this tag shows nothing. I have even tried to use `<?php wp_reset_query(); ?>` after each `WP_Query`, but that did not help.
How do I make this work properly? | `get_the_category_list()` shows categories that have been assigned to a particular post/page.
If you want a list of **all** categories you've defined then you should use `wp_list_categories()` (Link to Codex) | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "categories"
} |
Facebook 'Share' and 'Like' on individual posts
As the name of the thread indicates, I want to add to my website a Facebook 'Share' and 'Like' buttons to each of my individual posts. On each post page I will have those two buttons so people can like or share that individual page.
I can't seem to find a way to do that, so i would like to ask you guys how can i achieve that effect (with a plugin or a code solution). | 1. Install 'Simple Facebook Connect' Plugin.
2. Go to 'Simple Facebook Connect' under 'Settings' in WordPress Admin.
3. Configure the plugin. There is a help tab to help you.
4. Enable 'Like Button' and 'Share Button' modules.
5. Change the 'Like Button Settings' according to your requirements.
You are done.
**More Info**
1. This plugin is from Otto. Visit this plugin on Ottopress.
2. This plugin properly outputs Open Graph tags.
3. From the plugin description
> "Simple Facebook Connect is a framework and series of sub-systems that let you add any sort of Facebook functionality you like to a WordPress blog. This lets you have an integrated site without a lot of coding, and still letting you customize it exactly the way you'd like." | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, facebook"
} |
register_post_status and show_in_admin_all_list
I have a custom post status which should be public visible but not displayed in the "all" list of the edit screen.
This is how I register the post status:
register_post_status('my_custom_post_status', array(
'label' => __('The Label', 'domain'),
'public' => true,
'exclude_from_search' => true,
'show_in_admin_all_list' => false,
'label_count' => //blablabla
));
The `show_in_admin_all_list = false` should hide the status in the all-list but it doesn't. Only if I set the public to false it is not visible. But I need `public = true`!
Any ideas
Codex: < | This solves my problem:
register_post_status('my_custom_post_status', array(
'label' => __('The Label', 'domain'),
'public' => !is_admin(),
'exclude_from_search' => true,
'show_in_admin_all_list' => false,
'label_count' => //blablabla
));
`!is_admin()` makes the status only public on the frontpage.
If you find a better solution please post it here! | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 6,
"tags": "post status"
} |
Change the avatar ratio in bbPress login widget
I am using bbPress on my site and have (bbPress) Login Widget on my sidebar. Is there a way to change the default image size from 40 to 80 or other number? here is the code from the core files:
` <?php echo get_avatar( bbp_get_current_user_id(), '40' ); ?> `
How do I change that default 40 px without editing the core files?
Can i filter it somehow?
Thanks in advance, you are my last hope to find answer to this problem of mine! | You can filter `'get_avatar'`:
add_filter( 'get_avatar', 'wpse_67657_new_avatar', 10, 5 );
function wpse_67657_new_avatar( $avatar, $id_or_email, $size, $default, $alt )
{
// create a new img element or …
$new = str_replace( 's=40', 's=80', $avatar );
$new = str_replace( 'avatar-40', 'avatar-80', $new );
$new = str_replace( " height='40' width='40'", " height='80' width='80'", $new );
return $new;
}
Filtering the size only is currently not possible. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "bbpress, avatar"
} |
Why are navigation items saved in the database?
Maybe I am just not grasping the concept of WP right here but why is everything in Wordpress stored as a post of some type? I have a custom set of tables that house hundreds and thousands of items. I would like to programatically create a navigation menu that dynamically updates items to reflect my custom tables. I haven't been able to find a way to do this without using the following function:
wp_update_nav_menu_item()
To my understanding this function stores the item in the array in the wordpress tables as posts/taxonomies? This is needless overhead in my case and looks pretty permanent. My menu items will change pretty much on a daily basis, I don't want to grab items from one table only to have them stored in another table.
Does anyone know how I could directly update the navigation menu each time the homepage loads without requiring any interference from the administration panel?
Thanks. | Filter `wp_nav_menu_objects` and add your custom items dynamically (see this example or this). You get the current list of items and the arguments `wp_nav_menu()` was with as parameters. Then you can just add new items or remove existing ones. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "custom post types, navigation, menus"
} |
What is wrong with using add_option with Multisite instead of add_blog_option in a plugin
I'm working on a new plugin but it's my first to save which will save an option to the database.
Currently I'm using `add_option` and I assumed that
\- activation would fail or \- the wrong value would be saved to the wp_blogID_options table
because I wasn't using `add_blog_option`. All the posts / literature (Wrox, Apress, etc) I've read say I need to use to `add_blog_option`.
But all my testing (and inspecting the SQL table) are proved me wrong. So ... What is wrong with using add_option instead of add_blog_option when making a plugin (that can be single install or multisite)?
To me ... it seems that `add_option` (or even `get_option`) all work fine. I'm guessing the Settings API has some protection wrapper.
However ... that would mean using `add_blog_option` (or get_blog_option) are only for 'purists'. | What I've come to 'learn' is that there are 3 states on plugin activation for a mulitsite setup.
Consider this for a Site Admin who installs a new plugin:
1. Plugin is network activated - but it needs admin to complete setup (call it stateless)
2. Plugin activated, no 'unique features' per blog and it doesn't need an admin user to complete setup (call it active)
3. Plugin activated, has unique features per blog and it does need an admin user to complete setup (call it pending)
Scenario 1: you can safely use 'add_option' on plugin activation (or network activation) as the plugin is _stateless_.
Scenario 2: you must use 'add_blog_option' and loop through each blog - if you do _network activation_ as the plugin will be _active_.
Scenario 3: you must use 'add_blog_option' and ideally you don't allow _network activation_ because the plugin is _pending_.
In my case, my plugin does nothing until the Blog owner creates a page with the shortcode. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 6,
"tags": "plugin development, multisite"
} |
how would I create a custom query to get all users, and a related post based on a postmeta field?
I have about 50 users. Its pretty easy to list them all. However they are related to a special custom post type through a postmeta field called wpp_agents.
So I need to list Users, but also the post title(linked to the post).
1. User 1 | User 1's Post(linked)
2. User 2 | User 2's Post(linked)
3. etc...
I am a mysql noob but getting pretty ok with php.
Here is what I am playing with:
$data = $wpdb->get_results(
"SELECT $wpdb->users*,
"SELECT display_name, user_email
FROM $wpdb->users
LEFT JOIN $wpdb->usermeta ON
user.ID=wpp_agents;",
ARRAY_A
);
but its not right.
I believe I need to SELECT * FROM $wpdb->users LEFT JOIN $wpdb->postmeta
but then not sure.
any help is greatly appreciated. | Gladly there's a function that will output **exactly that query string** for you (still laughing about it :) ).
Here it is: `get_posts_by_author_sql` @queryposts.com, which looks in the core source like this.
In detail it builds the `WHERE` part for you, that you can drop into your query.
So just throw the user ID in and build your string that you can use in your query:
foreach ( $users as $user )
{
$where = get_posts_by_author_sql( 'wpp_agents', true, $user->ID );
echo '<pre>';
var_dump( $where );
echo '</pre>';
}
Take a look at this question on how to intercept the `posts_clauses` (or even better the `posts_where`) filter.
Maybe you find a way to simply alter the main query to spit this out on a single call. Hint: You should have some serious caching mechanism or add the result as transient. This can get intense. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "query, mysql"
} |
Building an email signup form. Where should the information be saved in the DB?
I would like to try build a simple plugin that collects and stores the name and email address of the person who filled in the form. I realize there are probably dozens of plugins out there that do this already but would like to build my own, for practice.
If the user enters their name and email address, where should this be stored? Should it be created as a "subscriber" custom post type or a whole new table in the WP database? What are your thoughts? I'd like to eventually export the data to a .csv file if that influences where it should be stored. | There are multiple storage mechanisms in WP so it can be bit tricky to pick one and sometimes there is no single right choice.
Let's examine your criteria for storage:
* persistent (you don't want data just evaporating)
* processable (you want to export it and probably navigate)
* simple to implement (you don't want go building something (semi)custom just for the heck of it)
* extensible (in case you want to capture more data down the road and such)
As for me the best storage to satisfy these condition would be using custom post type. It comes with a lot of functionality out of the box (like admin interface), requires no messing with storage (custom tables or whatever) and is perfectly suited to store arbitrary information in custom fields. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, plugin development, database"
} |
How to get the month argument from permalink in wordpress?
I am working on a custom Wordpress template for the archive. I have the archive set up by category but now I want to organize by category and month but I can't figure out how to access the month argument from the permalink. How would I get access to that argument. | the standard WP function for that is:
the_date();
(source) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "archives, permalinks"
} |
Converting the_content string to an array?
I have created a custom taxonomy, this taxonomy is dedicated to image attachments, when I upload my images `$post->post_content` returns a string like:
'[caption id="attachment_98" align="alignnone" width="300"]
<a href="
<img class="size-medium" title="title" src=" alt="cardinal2" width="300" height="225" />
</a>
caption[/caption]'
By calling `the_content()` this string becomes an HTML markup, at codex I couldn't find a function that allows me to get the source of the image and caption/description/title of it in a dynamic way, is there a way to output the content without using `the_content()` function? Should I _split_ the result? | Filter `'img_caption_shortcode'`. You get three arguments: an empty string, the attributes (including the attachment id), and the caption content. If you return anything but an empty string WordPress will print your return value instead of its own code.
See `wp-includes/media.php` for details.
Another option: hijack the caption handlers and create your own output or change the output WordPress builds before it is sent back to the content. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, wp query, wpdb"
} |
Hide php Notices in Dashboard
When I program a theme, I put WP-DEBUG on. Which ensure a proper PHP code.
Sadly most Plugin developers keep using non existing vars :
echo $args['title'];
Notice: Undefined index: title in /wp-content/plugins/easy-fancybox/easy-fancybox.php on line 301
Instead of
echo ( isset($args['title']) ? $args['title'] : '' );
So I permanently get tens of Notice errors with some plugins (even MU gets one !)
Thanks to a Debugbar I don't see them on my websites, not in the middle, they are all deported to the bottom.
But how could I hide them in the Dashboard the same way? I would like to push them to the bottom of the page.
**UPDATE: Actually, Debugbar hides them in Admin and Website the same way, I just didn't notice that it didn't work for this particular plugin for once. Notices errors were between`<script>` tags** | I don’t know how to move the notices to the bottom or if that’s possible at all. To disable the debug mode in `wp-admin` write in `wp-config.php`:
define( 'WP_DEBUG', FALSE === strpos( $_SERVER['REQUEST_URI'], '/wp-admin/' ) );
_Untested:_
You could try to enable warnings in admin with:
// happens early in wp-admin/admin.php
add_filter( 'secure_auth_redirect', 'wpse_67728_error_warnings' );
function wpse_67728_error_warnings( $in )
{
// anything but notices
error_reporting(E_ALL ^ E_NOTICE);
return $in;
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 6,
"tags": "php, errors, dashboard, wp debug, notices"
} |
Create a new template for twentytwelve
Twenty Twelve comes with some page templates: Front Page & Full Width. These are in the folder /page-templates.
I've created my own template and saved it into this folder, but it is not present to be selected when editing a page.
There is no mention of the two page templates in functions.php
What do I need to do to include my new page template? | Put the template file in your theme and add the following comment to the top of your file after the
/**
* Template Name: This is the name of your template
*/
WordPress will pick this up and in the page templates dropdown you will see "This is the name of your template" listed as an option | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "page template, theme twenty twelve"
} |
How to display only an excerpt of the content with custom post types?
<?php
/*
Template Name: second
*/
?>
<?php get_header(); ?>
<?php query_posts(array('post_type'=>'event')); ?>
<?php if(have_posts()) while(have_posts()) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" class="entry">
<div class="thumbnail"><?php the_post_thumbnail('full'); ?></div>
<h1 class="title"><?php the_title(); ?></h1>
<div class="content page">
<?php the_content(); ?>
<?php wp_link_pages(array('before' => '<div class="page-link">'.__('Pages', 'cpotheme').':', 'after' => '</div>')); ?>
</div>
</div>
<?php endwhile; ?>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
The page acts like an index.php What should I amend in order to make the title as the link to the full page and make display only an excerpt of the content? | You only need two small changes (1st and 3rd lines), though I also took the liberty of tweaking the classes on the div to what seemed more appropriate:
<h1 class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<div class="excerpt event">
<?php the_excerpt(); ?>
<?php wp_link_pages(array('before' => '<div class="page-link">'.__('Pages', 'cpotheme').':', 'after' => '</div>')); ?>
</div> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "templates, excerpt"
} |
Shortcode output always showing at top of page
my shortcode output won't appear where I put it, but rather at the top of the content (top of the post/page content).
And here is my code
function service_shortcode_index() {
global $content;
$output = include ( TEMPLATEPATH . '/service.php' );
return $output;
}
add_shortcode('service_mid', 'service_shortcode_index');
there are some regular HTML lists with widget in "service.php"
The content displays correctly, just in the wrong position. | I think your problem is with the `$output = include ....` statement. `include()` returns true or false based whether it was successful - not the content of the file being included. Use output buffering to get the content.
function service_shortcode_index() {
global $content;
ob_start();
include ( TEMPLATEPATH . '/service.php' );
$output = ob_get_clean();
return $output;
}
add_shortcode('service_mid', 'service_shortcode_index'); | stackexchange-wordpress | {
"answer_score": 13,
"question_score": 5,
"tags": "shortcode"
} |
How can I specify the width and height of the Featured Image in TwentyTwelve theme?
I am trying to get set the width, height and position of the Featured image for a new page I created. | To set the height and width of `the_post_thumbnail` use the following:
`the_post_thumbnail( array(height,width))`
Where it would show in code like this:
`if ( has_post_thumbnail() ) the_post_thumbnail( array(200,999))`
More Info on Post Thumbnails | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post thumbnails, featured post, customization"
} |
How do I translate this string - PHP syntax question
I need some help on how to correctly format this code snippet for translation:
<?php next_post_link( '%link', __( '<span class="meta-nav">←</span> Nästa nyhet') ); ?>
I've used this method in my theme before:
_e( 'Nästa nyhet', 'mytheme');
But I don't know how to correctly type the _e translation method in my link output. I want to translate "Nästa nyhet".
Anyone? | Don't wrap the entire section in `__()`, just wrap the part you need to translate:
<?php next_post_link( '%link', '<span class="meta-nav">←</span> ' . __( 'Nästa nyhet', 'mytheme' ) ); ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "php, theme development, translation, localization"
} |
Is this the proper usage of creating / using a transient?
I'm new to using transients. Is this the proper format to create a transient and have it pull from the DB instead of using the http api?
I have standardized my snippet so others can double check their code as well...
function google_transient() {
$url = '
$the_whole_body = wp_remote_retrieve_body( wp_remote_get($url) );
$transient_name = 'google';
// Get any existing copy of our transient data
if ( false === ( $transient_name = get_transient( $transient_name ) ) ) {
// It wasn't there, so regenerate the data and save the transient
set_transient( $transient_name, $url, 60*24); // 24 hour cache
}
return $the_whole_body;
} | No quite: Get the transient’s content first, **then** do the expensive work to fetch the external resource.
function google_transient() {
$transient_name = 'google';
$content = get_transient( $transient_name );
// done
if ( $content )
return $content;
$url = '
$content = wp_remote_retrieve_body( wp_remote_get($url) );
set_transient( $transient_name, $content, DAY_IN_SECONDS ); // 24 hour cache
return $content;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "transient"
} |
Add action hook conditionally - only when home.php in use
I am trying to add action hook in functions.php only if the page is `home.php` but the following does not work
if ( is_page_template("home.php") ) {
// do stuff
}
To make sure that file being used is `home.php` I do this
global $template; echo $template; | Use `is_home` instead, as `is_page_template` will not work for `home.php` as its technically not a page template in the traditional sense.
add_action('template_redirect', 'are_we_home_yet', 10);
function are_we_home_yet(){
if ( is_home() ) {
//your logic here
}
}
# Revised:
add_action('template_redirect', 'are_we_home_yet', 10);
function are_we_home_yet(){
global $template;
$template_file = basename((__FILE__).$template);
if ( is_home() && $template_file = 'home.php' ) {
//do your logic here
}
}
The revised answer is actually what you really need, it will check if you are on the home page, in addition to getting the template file being included and check to see if that file is in fact your `home.php` file and if so, you can go about your logic... | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 4,
"tags": "functions, hooks, actions"
} |
How to i18n text coming from the db or from an external source
I'm writing a plugin and i wanted to i18n correctly text which i'm storing in the db or in an external file. How should i do that?As of now we are generating pot files with wordpress and so all the Translatable text is in calls
__( 'text', 'plugin_name');
But there is some text i would like to store in the db or in another format and that i don't know how to put into the POT files.
The only thing that come to my mind is to use arrays for these data structures so that i can translate the values, but are there other options? | Short answer: You don't. Not with the I18N functions. Data in the database is data that can change, and should be translated via some separate means. Data in the code is hard-coded, and doesn't change, and can be translated via the I18N functions.
If you want to store all your translatable text in a single PHP file as an array, and then reference it from elsewhere in the code, then that works fine. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin development, translation, localization"
} |
custom header navigation has odd spacing
Live site.
I'm using a custom header on my blog page which features the same coding as my regular heading for `nav`. The `nav` looks fine on all pages but the blog page- the Blog button shifts left. Any ideas why? | I'm not sure what's causing the causation of your problem, but for some reason the `<li>` tags are not being added around the "portfolio" menu item, when you visit the blog page. Maybe you can see why in the custom header menu code?!
The `<li>` tags are what creates the spacing(padding-right) in between each menu item, so without them on the portfolio item, the blog menu item shifts to the left. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "css, navigation, html, headers"
} |
Where does the Media Library live in the database?
I'm exporting a Wordpress site from localhost to a web host, and I am unable to import the Media Library, as the web host is unable to contact localhost.
I've uploaded all of the localhost files from /wp-content/uploads/..., and I'm thinking I just need to isolate the part of the MySQL database which contains the Media Library, and adjust the URL, then import the SQL into the web host database.
Can you tell me where the Media Library lives in the MySQL database please? | The Media Library lives in both **wp_posts** and **wp_postmeta**.
* **wp_postmeta** contains the image URL
* **wp_posts** contains an entry for each image insertion into a post, along with the post ID.
Exporting and importing these 2 tables as SQL did not work for me - I received 'duplicate entry for key 7'...
Exporting and importing these 2 tables as CSV _did_ work, using "CSV using load data".
Before importing, I emptied the 2 tables in the recipient database. | stackexchange-wordpress | {
"answer_score": 39,
"question_score": 48,
"tags": "import, export"
} |
Get the name an the description of a link category
I have a link category with the id `$id=23;` and the slug `$slug=friends;`. I managed to read all links from that category using `get_bookmarks($id)`.
Now I also want to use the name and the description ob the link category. How geht I get these values? I tried for example:
$cat = get_the_category($id);
$output .= "<p>Description: ".$cat[0]->category_description."</p>";
unfortunately this (and other things) did not work.
So how can I receive the name and the description ob the link category with the id=23? Is it also possible to recieve this via the slug of the link category? I tried `get_category_by_slug($slug)`, but this always gave an empty result,... | <
example:
<?php
$link_id = 23;
$link_category = get_term_by('id',$link_id,'link_category');
var_dump($link_category);
?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "categories, slug, link category"
} |
Multisite, turn off "create new site"
If someone enters the wrong URL to my wordpress multisite, they get the option to create another site in the network. Why does this happen, and how do I turn it off? | This setting is controlled under: Network Admin > Settings > "Allow new registrations." You may want "Registration is disabled."
!Screenshot of "Allow new registrations" setting | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "multisite, customization"
} |
Creating a nav menu
I am not very familiar with WordPress so my knowledge with this is limited. I am working on a travel website where I need to show navigation menu and I am not sure how I can achieve the desired behavior. Here is my case:
I need to show destination based drop-down menu and another as category based. Like
Destinations
-Delhi
-Destination1
-Destination2
-More Destinations
-Mumbai
-Destination1
-Destination2
-More Destinations
More
For categories I need to show them as
Category
-Adventure
-Hills
-Romantic
-More
For category part I can create a parent category with child categories and can assign categories to posts as applicable but now sure how to achieve hierarchical menu structure for destination part.
Is there anything like hierarchical tags in Wordpress or what are the possible ways to achieve this?
Thanks in advance | First, be sure your theme supports `wp_nav_menu` which is goes into a template file - such as header.php - with the template tag function
`<?php wp_nav_menu( $args ); ?>`
which also requires a function in functions.php. See <
That will initiate the WordPress 3 menu system that will appear in Dashboard>>Appearance>>Menus
Next, read < on how to make a menu with custom links that point to each category permalink, i.e. `yourdomain.com/category/mycategoryname`
Form the page structure with parent/child pages first, and then make the menu to follow your page structure. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, menus, sub menu"
} |
How to add orderby parameter for sorting on category.php
I'm on a Category.php page which does the loop like this:
<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
I usually do a custom loop like this:
<?php //Define the Loop
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query('posts_per_page=2&orderby='.$orderBy.'&paged='.$paged);
?>
I want to add the orderby variable to the first loop (the one on category.php) but can't figure out how to implement it. | You can use the `pre_get_posts` action hook to set the order on your category archive like so:
add_action('pre_get_posts', 'filter_category_orderby');
function filter_category_orderby( $query ){
if( $query->is_category()){
$query->set('orderby', 'title');
}
}
just paste this snippet in your theme's functions.php and you should be fine. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories, loop"
} |
"Conflict" with jQuery (or its plugins)?
I've been working on localhost and everything looks fine but then when I uploaded my Wordpress theme online, all of the jQuery plugin functions are undefined!
One solution that worked (which I haven't tested a lot so I still don't know if it will work in the long run) is to import the javascript file from the plugin's main website or github page. I don't really prefer this "solution."
Another is the solution here but I haven't tested this a lot also. My issue here is I've used jQuery in another theme and everything works using just `$`, but in my new theme it doesn't work with `$` and so I have to use `$j` instead. It's just that I'm very used to using just `$`.
Can someone explain this weird phenomenon? Thank you! :) | You can use `$` but it is advised you don't. Use `jQuery` or something like the example in your link, if you must use `$` you can do so like this;
$.noConflict();
jQuery(document).ready(function($) {
// $() will work as an alias for jQuery() inside of this function
});
//$ will cause problems if put here:)
To use it for just a function you can append jQuery to the end like:
(function($) {
// $() will work as an alias for jQuery()
})(jQuery); //dont forget this part | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, jquery, javascript"
} |
Setting a page link in the footer?
What is the proper process for setting a page up with a link to it in the footer?
Currently, all my pages are in Appearance -> Menu...and of course displayed in the main menu.
However I want a batch of them to be in the footer.
I have decent HTML,CSS, PHP skills but new to WP. | What may be easier (if you don't necessarily want all the same menu items to appear in the footer) is to:
* Create a new menu, "Footer Menu" for example
* Add-in whatever links (pages) are needed there
* Add a widget (called Custom Menu) to a footer widget position (if your current theme supports it).
Let me know if that helps. Thanks! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "links, footer"
} |
Excerpt not alway available
I have a php function that should print last three posts with title and excerpt.
For the first post printed there is no excerpt.
Here is the code:
$posts = wp_get_recent_posts( array('numberposts' => 3, 'post_status' => 'publish') );
foreach ($posts as $post)
{
setup_postdata($post);
echo "<h2 style='font-size:18px'>".$post['post_title']."</h2>";
if($post['post_excerpt'])
echo $post['post_excerpt']." <a href='".get_permalink($post['ID'])."' style='font-size: 17px;'><b>Continue...</b></a>";
else echo 'no excerpt';
echo "<br><br />";
}
I want to show the excerpt for the first post printed too (the last posted one). What is wrong in my code? Why it's not working for the first post printed? | Excerpt is stored in database and available in post object only if it was added manually in post editor. Do not access such properties directly, use template tags instead - `get_the_excerpt()` in this case. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "excerpt"
} |
Font shows up as Arial instead of Times
I am the webmaster of Palo Alto High School's online publication, The Paly Voice. We're using Wordpress, and for some reason occasionally chunks of stories change fonts. Here is an example.
I inspected it, and there's no surrounding element - just text. But why? How can I fix this? | The paragraphs that show up differently are not inside `<p>` tags. Therefore the font rule in your `story.css` file (line 111) does not apply to them. To fix this you can do one of two things:
1. Put the paragraphs that are showing up with the wrong font inside `<p>` tags.
2. Add a new rule in story.css for the entire section that sets the font. The rule would be something like this:
.story-content {
font-family: Georgia;
font-family: Georgia, serif;
font-size: 14px;
line-height: 1.7;
margin: 20px 0;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, css"
} |
How do I disable dashboard update notifications for subscribers?
For registered users to my blog, if they click on the dashboard, they get an alert suggesting that they tell the site administrator (me) that the new version of WordPress is available.
All I want is to hide dashboard alerts from the subscribers. Where can I find the code to change this?
I found a site here that suggests that I'm looking for the code:
add_action('admin_head','addDashboardAlert');
But I don't know where to look for it.
## UPDATE
I found some more relevant code to make the alerts conditional on user role, here:
if (!current_user_can('delete_posts')) { | you can include some custom css in your functions.php that hides the update_nag (notifications) element dependent on user capability:
add_action('admin_head','admin_css');
function admin_css()
{
if(!current_user_can('administrator'))//not and admin
{
echo '<style>';
echo '.update_nag{display:none}';
echo '</style>';
}
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "dashboard, updates"
} |
How to redirect to correct pages after permalink structure change
I am changing my permalink structure from `/%year%/%monthnum%/%postname%/` to `/%category%/%postname%/`.
Is it possible to redirect old links using old permalink structure to the new link? Possibly via the postname? | Wordpress should handle all redirections correctly, without you needing to worry about them. For example, if your old post was < any links should auto-magically be redirected to < I just tested it on a site with Wordpress 3.4 installed, and it worked just fine. Wordpress can _read your mind_. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permalinks, url rewriting, htaccess"
} |
How does WP handle multiple matching rewrite rules?
Here is my url to a custom type :
When I go to this link, I'm redirected to
which results in a 404 error.
I use Rewrite Rule Inspector wordpress plugin for listing the matching rewrite rules.
It appears that my url matches three rules : (regex new-url source)
* movie/([^/]+)(/[0-9]+)?/?$ index.php?post_type=movie&name=$matches[1]&page=$matches[2] movie
* (.?.+?)(/[0-9]+)?/?$ index.php?pagename=$matches[1]&page=$matches[2] page
* [^/]+/([^/]+)/?$ index.php?attachment=$matches[1] post
Witch one Wordpress will choose for resolving my url ? Why do I have a 404 error ? | I think it matches the first one in the array. So you enter specific rules above more general ones. In your case it should be matching the movie rule if it has a lower array index number than the other ones. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, custom post types, theme development, url rewriting, rewrite rules"
} |
Add a class at specific element in custom Menu Walker
I have customised my menu in wordpress by extending the Nav_Menu_Walker class and now i cannot figure it out how could i add a class at a specific ul element. I have this function which adds classes by depth:
function start_lvl(&$output, $depth) {
$indent = str_repeat("\t", $depth);
if ($depth >= 1)
$output .= "\n$indent<ul class=\"subsubmenu\">\n";
else
$output .= "\n$indent<ul class=\"submenu\">\n";
}
When the $depth is 0 i would like to add a different class at the third element from $depth =0 rather than "submenu".
Could you please provide me some suggestions ? | Count the level 0 elements in a static variable in the method and add an extra class if you hit the third. Sample code, not tested:
function start_lvl(&$output, $depth) {
static $column = 1;
$indent = str_repeat("\t", $depth);
if ($depth > 0)
{
$output .= "\n$indent<ul class='subsubmenu'>\n";
}
else
{
$column += 1;
$extra = 3 === $column ? ' third-column' : '';
$output .= "\n$indent<ul class='submenu$extra'>\n";
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "menus, css"
} |
How to include external library in wordpress plugin
How can I make an external PHP library available with my plugin.
Where the library files need to be placed? | The best way to include an external library is to put it in your plugins folder. Then just use `require_once()` wherever you need it. Depending on the size of the plugin and your type of programing this might be in the main plugin file or wherever you need that functionality. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugin development, library"
} |
custom comments form for custom post type
Hello everyone I am creating a theme dedicates to hotels display and booking in which I have created a custom post type 'Hotels' so now I want a mechanism to book the hotel rooms and a "book now" button in the hotel page to book the room which will send a request to the admin and also send an acknowledgement mail to the user for this I thought if I make some changes in comments form for post type hotel and display the comments form throw a comments_popup_link(); and add some more meta fields throw add_comments_meta();
* * *
But the question is how can I display the different custom comments(book now) requests in the admin panel with all the comments meta information related to the comments. Is it possible or do I have to think of some different mechanism to do what I'm expecting. | This is possible : you can fetch the comments form the database in the admin side in the same way you would do it on the client side with get_comments.
Now the question is : where exactly, in the admin side, do you want to display you custom comments ? You can for example create a meta box in the Hotel edit page. Or you can create a single custom admin page where all the booking will be listed. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, plugin development, theme development, custom field, comments"
} |
Custom ID for certain menu item?
I'm displaying Wordpress menu using this function:
wp_nav_menu( $args );
Menu is set in wp-admin/nav-menus.php.
Can I somehow attach ID of my choice to one of the items? I want the menu to look like:
[ Link 1 ] [ Link 2] [ LOGO (that is Link 3 also ] [ Link 4 ] [ Link 5]
I know I could style ID of the logo link such as "menu-item-123", but I'd love to change it to "logo" or something that has a meaning :)
Thanks. | Simply use the "Class"-field for styling. Give it a unique class, target it in your CSS file. Done.
> !WordPress menu item class | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 8,
"tags": "menus, navigation, logo"
} |
Comparing Time with the_time();
I am trying to make a function that will check the time associated with a future event (cpt) with the current time, to see if the event has past. When I first collect the time it is in seconds and I can then convert it easily with date_i18n() to whatever, but I am not sure how to compare that results with the wordpress function the_time() to retrieve the current time.
Is there a way to have the_time() spit out the result in seconds, and I can then compare the two simply by ><= ?
or is there a way to compare two dates formatted in the same way? So formatting my date_i18n() result the same way as the_time() result and then comparing somehow | `the_time()` doesn't return the current time, it returns the time of the current post, also it echoes the result.
If you need the current time, simply use PHPs native `time()` function. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "date time, comparison"
} |
get_terms with more than x post count
Is there an argument for get_terms which I can fetch terms that only have say over 2 posts associated with it?
I have a terms page which lists all my terms for 'artists', the page is huge but a lot of these terms that only have one post so I would like to show only significant terms. | Give:
$terms = get_terms("my_taxonomy");
$count = count($terms);
if ( $count > 0 ){
echo "<ul>";
foreach ( $terms as $term ) {
if ($term->count > 2) {
echo "<li>" . $term->name . "</li>";
}
}
echo "</ul>";
}
a shot. It will grab all the terms and then run a check to see if the `$term->count` is greater than 2 and if so, print out those terms. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "tags, terms"
} |
How to get the unfiltered excerpt, without [...] or auto-excerpting
The standard way of getting an excerpt is to use `the_excerpt()` or `get_the_excerpt()` template tags. I am trying to get just the actual content of the Excerpt field.
If there is an excerpt, I want to display it in full (without being abridged or appending [...]). If there is no excerpt, I don't want anything to be displayed.
Is there a straightforward way to do this in Wordpress?
Something like this:
$real_excerpt = ???
if ( $real_excerpt ) {
echo $real_excerpt;
} // shouldn't show anything if there isn't a custom excerpt | Why don't you use the global `$post` variable? It contains an object with the content as it is on the db row corresponding to that post. Here's how to use it:
global $post; // If for some reason it's readily accessible, invoke it
if($post->post_excerpt != '') {
echo($post->post_excerpt);
}
Or:
$my_post = get_post($post_id);
if($my_post->post_excerpt != '') {
echo($my_post->post_excerpt);
}
Very simple, but let us know if you're having trouble getting it working. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 6,
"tags": "excerpt"
} |
function to include is_home, is_archive, is_category, is_author etc in one function?
I'd like a way to target only blog-area pages for specific formatting.
So far,
<?php if (is_home() || is_single() || is_category() || is_archive() ) { ?>
works okay, but is there a way to combine all of those into one single function to shorten it up a bit? so maybe in the functions it would set is_blog() to equal those four (or however many I want).
Seems a bit simple and probably is.... I just dont know what to search for to find information on this. Thanks!! | Based on what you described:
function is_blog()
{
return ( is_home() || is_single() || is_category() || is_archive() );
}
And then just call the is_blog() function whenever needed.
I also found this, which looks like a more specific way to do the same thing < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "functions"
} |
How to restrict user to choose 1 category for a post
I wish to restrict the user posting a new article to select only 1 category for that post. It doesn't matter which category he chooses as long as he chooses just one. This way posts are maintained under a hierarchy (and I want to avoid users clicking all categories so that their posts appear everywhere).
I don't want to restrict the user to a specific category, I just want to limit the number of categories the user can choose for a post to 1.
Is there any way to achieve this in Wordpress? | I've solved this in the past for a client by using `remove_meta_box` to hide the default categories meta box, then adding my own meta box via `add_meta_box` which outputs categories as a drop-down select list, which effectively limits selection to a single item. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "categories"
} |
Get URL of Post You Are Editing
I can't seem to find this anywhere, Is there a way to retrieve the URL of the post (which is of a custom post type) you are editing. Basically I want to somehow get the same URL that shows up like this: Permalink: (link to post) on the edit screen. | You should have the `$post` variable (you may need `global $post;`) from which you can get the post ID (`$post->ID`). Then `$perm = get_permalink( $post->ID );` should give you what you want.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, permalinks"
} |
posts stuck as drafts
I've recently seen a new bug appear on a site running WP e-commerce. New products (or certain existing products) get stuck as 'drafts'. Once they are marked as draft clicking 'publish' does not do any good, and the only way to make the products publicly accessible is by directly editing the entry in the MySQL database.
**UPDATED** Further investigation shows that this is not an wp-ecommerce problem - it affects all posts.
Switching to twentyten theme fixes the problem, so clearly the inability to publish must lie somewhere in the custom theme I'm using. Seeing as it's my own theme, I guess I'm to blame ;-)
Error reporting throws up a mention of an incorrectly called register_script() function, however I don't think this is what's causing the problem, as it's not in my code. | You probably have some custom functions in your themes functions.php Add a `return;` on top of this file. If the problem is solved: Move it below the first function. Proceed this way until you've found the function that is causing the problem.
If this doesn't work: Go and do the same for one template file after each other until you found the file that is causing the issue. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": -3,
"tags": "theme development, post status"
} |
using get_option to add a different js
I'm trying to us `get_option` in my plugin to choose to load 1 of 3 js files.
I started with this (and it works) ...
add_action('wp_footer','isotope_vpl_set_style');
function isotope_vpl_set_style() {
include("inc/myfile.js");
}
then I changed it to ...
add_action('wp_footer','isotope_vpl_set_style');
function isotope_vpl_set_style() {
$style = (get_option('damien_style');
if $style = ("isotope"){
include("inc/myfile.js");
}
}
And it's not working ... I checked the SQL table and the option name and value are set.
My PHP error log tells me I have an unexpected ; on this line `$style = (get_option('damien_style');`
Where have I gone wrong please :) | You had an extra `(` before `get_option` and the if statement syntax was wrong. Here is the revised code:
add_action('wp_footer','isotope_vpl_set_style');
function isotope_vpl_set_style() {
$style = get_option('damien_style');
if($style == "isotope") {
include("inc/myfile.js");
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugin development"
} |
Get the Google+ and Twitter links - Wordpress SEO plugin
I want to use the Google+ and twitter links that can be added in User's profile using the WordPress SEO plugin and display them on the author page. Is there any way I can get those links from the plugin or do I need to fetch them using some other method say directly from database.
SEO Plugin @the official repo | I found a way to do it in author.php file
Just use the following to display the Google+ and Twitter links:
<?php
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
echo $curauth->googleplus;
echo $curauth->twitter;
?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "user meta"
} |
Plugin for conditional redirect
Lets say, I create page1 and page2 in wordpress, in Page1 there is a hyperlink which takes me to page2. How do I ensure that visitor has clicked that hyperlink and have come to page2 and not directly on page2, by typing page2 url in the address bar.
if someone has come directly to page2 I want them to be redirected automatically to page1. In old days I was able to crack this with some javascript and and later also in ASP. If I recollect correctly had used querystring and url redirect.
What is easy way in wordpress? unfortunately in wordpress plugin directory all I am getting is plugins for 404 and 301, Please help me here. | if ( ! isset( $_SERVER['HTTP_REFERER'] ) AND 'your_page1' !== $_SERVER['HTTP_REFERER'] )
{
exit( wp_redirect( $target, 301 ) );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "redirect"
} |
Pull certain Wordpress posts on custom CMS instead and 301 wordpress to it?
Say a site has its main custom CMS on www. and a wordpress blog on blog. Up to now some really good reviews have been posted over years on blog. but believe now they would be best served on www. Is there a way to pull this content in all its glory and still use WP to power it behind the scenes but display on the www? Not only that but then have a 301 setup to move them all across and no longer show on the blog. subdomain?
Appreciate anyone who could point me in the best direction to do this if its possible. Many thanks in advance. | If you are moving content permanently to the CMS I would advise to actually **move** it, rather than fiddle with integration. Not worth the trouble for static move.
As for redirect it is common use case and I would do some digging at `redirect` tag at official plugin repository. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization"
} |
how to find user ids of all commenters in a post
Is there a function in wordpress that grabs all the users(user ids) who have commented on a post? I have the post id available. | The get_comments() answer by Poulomi Nag is correct. This will be somewhat more efficient.
global $wpdb, $post;
$query = sprintf("SELECT user_id
FROM {$wpdb->comments}
JOIN {$wpdb->posts} ON {$wpdb->posts}.ID = {$wpdb->comments}.comment_post_ID
WHERE comment_post_ID = %d
AND comment_approved = '1'",
$post->ID);
$authors = $wpdb->get_col($query);
$authors = array_unique($authors);
$authors = array_diff($authors,array('0')); // Remove those where users are not registered
Another alternative is to use WP_Comment_Query < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, comments, users"
} |
Woocommerce product page is not showing custom css
I am using woocommerce plugin for wordpress to make an eCommerce website. It is working fine with little bit customization. As I have configured shop page as the default product page so that in that page every product can be seen and a user can buy product from that page. But now I want to use some highlights image for special discount on that item and I just placed all that item just over the products page by posting images in that page. But in order to style that images I used WordPress Page Specific CSS Plugin to write some custom css, but it is strange that in that particular page custom css is not working. Can somebody tell me why this is happening and how to solve this? Any help and suggestions are welcome :) | You can add this to your body tag of your current theme `<body <?php body_class('class-name'); ?>>` and then specifically target the container.
body.post-id #yourdiv { border: 2px solid red; }
Always work for me. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "custom post types, css, plugins, page specific settings"
} |
Get the author of the latest revision
I would like to display the author (username) of the **latest revision** of a post from inside the loop.
I tried `get_the_author()`, which echoes the username and `$post->post_author()`, which returns the user_id, but both return the original post author and not the latest _revisor_. | Try `the_modified_author()` or `get_the_modified_author()`, this should give you the display name of the last user that modified the post. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "posts, loop, author, revisions"
} |
Buddypress Add unserialized Profile Fields in Members Loop
I'm trying to show profile fields with **checkboxes and drop-downs** in the members directory loop.
**Example: Next to each member in the directory I want to show the Gender they selected**
This code works for text fields:
echo xprofile_get_field_data('Full Name', bp_get_member_user_id());
BUT **how do I echo profile fields for drop-downs or checkboxes** (unserialized data)? | I believe xprofile_get_field_data is unserializing the data for you, but it is still in an array.
xprofile_get_field_data can return an array or a comma-separated string.
xprofile_get_field_data( $field, $user_id = 0, $multi_format = 'array' )
@param string $multi_format
* How should array data be returned?
* 'comma' if you want a comma-separated string
* 'array' if you want an array | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom field, customization, buddypress, profiles"
} |
Sort posts by custom taxonomy name
Is it possible to **sort posts (custom post type) by category / taxonomy** (name, desc)?
For example my categories would be
* Season 2012
* some post
* some post
* some post
* Season 2011
* some post
* some post
* some post
* Season 2010
* etc.. | One solution would be-
$terms = get_terms('taxonomy-name');
foreach($terms as $term) {
$posts = get_posts(array(
'post_type' => 'custom_post_type_name',
'tax_query' => array(
array(
'taxonomy' => 'taxonomy-name',
'field' => 'slug',
'terms' => $term->slug
)
),
'numberposts' => -1
));
foreach($posts as $post) {
// do what you want to do with the posts here
}
} | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 2,
"tags": "wp query, loop"
} |
How to display numbered pages in a category
How in category.php to output a numbered list of links to pages like:
1 2 3 4 5
when the number of posts in the category exceeds the number of posts to display? | As an alternative to using a plugin like PageNavi(as suggested in another answer), you could also use a wordpress native function
<
Though the plugin solution seems the easiest to setup | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories, pagination, navigation"
} |
Two pages named the same thing, on a different level but conflicting url paths in menus and direct links
I've just changed some titles of pages and child pages around, simply I've got Work as top level page, and Blog as a top level, with Play and Work as children.
The paths are:
/work/
and
/blog/work/
However, if I create a menu directing the user to /blog/work/, either using a page tag in wordpress or a direct link it takes the user to /work/.
Why is this, and how can I fix it?
< \- Check out blog/work link, at the moment it's a custom format to point to < | Afaik, you can't "fix" this, as this is the internal behavior of WP.
You maybe could use some other slug like `blog-work`. Then go and redirect to your desired URI. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, pages, urls"
} |
documentation on arguements?
I have seen many different parameters or arguments that can be passed to a query. For example, category_ _in, category_ _and term_id to name a few. Some of these can be found by using print_r to print out the object. ( If I have that right ). Others like the category__in I have been unable to find in codex. Is there a trick to learning about these parameters? How do I find them? | They're all in the codex page for `WP_Query`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "documentation"
} |
How to delete post revisions?
I haven't set a limit to the number of revisions, which makes some of my post have more than 20 revisions, so how to delete these revisions?
By the way, I am using WPMU and have many blogs, so how to delete WordPress revisions for all my blogs? | This is a much safer query to use and will remove related entries from the postmeta and term_relationship, unlike _deathlocks_ query in his answer.
Change the {id} to the id of each blog posts table. You can combine this query to run all the post tables at once, but try this on one table first. I've used it many times on single WP installs.
DELETE a,b,c
FROM wp_{id}_posts a
LEFT JOIN wp_{id}_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_{id}_postmeta c ON (a.ID = c.post_id)
WHERE a.post_type = 'revision'
After you run it, optimize the database in phpmyadmin.
And add this line near the top of wp-config.php to prevent future revisions:
define('WP_POST_REVISIONS', 0);
or save one revision:
define('WP_POST_REVISIONS', 1); | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 10,
"tags": "multisite, revisions, customization"
} |
How to pass code from header.php to footer.php
I'm initializing a variable with a value in the header.php file. I want access to that value in footer.php, but it doesn't exist upon checking. Example:
**header.php**
$status = true;
**footer.php**
var_dump( $status ); // is null
What's a best practice for doing something in footer.php, or other files if they have the same behavior. | Avoid global variables, they could be overwritten by other code. You could use a helper function with a static internal variable instead. Sample code:
function wpse_69365_var_storage( $var = NULL )
{
static $internal;
if ( NULL !== $var )
{
$internal = $var;
}
return $internal;
}
// first call:
wpse_69365_var_storage( 4 );
// later call:
echo wpse_69365_var_storage(); // print 4 | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "theme development"
} |
Hook for post and page load
I need to run a function when a particular post or page is loaded. Is there any hook that lets me check whether a post is being displayed during page load ? | You can use the `wp` hook and check the `global $wp_query` object or any conditional.
add_action( 'wp', 'wpse69369_special_thingy' );
function wpse69369_special_thingy()
{
if (
'special_cpt' === get_post_type()
AND is_singular()
)
return print "Yo World!";
return printf(
'<p>Nothing to see here! Check the object!<br /></p><pre>%s</pre>',
var_export( $GLOBALS['wp_query'], true )
);
}
See: `wp` in codex.wordpress.org and `wp` in developer.wordpress.org | stackexchange-wordpress | {
"answer_score": 34,
"question_score": 28,
"tags": "custom post types, posts, pages, hooks"
} |
shortcodes output before content
> **Possible Duplicate:**
> problem with short code
**Shortcodes are broken.**
For those of you playing at home, heres an easy step by step to replicate my problem.
* * *
1) Open a fresh Wordpress install (3.4.2).
2) Go into twentyeleven/functions.php and add the following:
function test() {
echo '-TEST-';
}
add_shortcode('testshortcode', 'test');
3) Edit the 'hello world' post to say:
Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!
[testshortcode]
foobar
4) Save and view, my results look like the following:
-TEST-
Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!
foobar
when it should look like this:
Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!
-TEST-
foobar
**What on earth is going on here?** | Shortcode callbacks have to return, not output. So use the following:
function test() {
return '-TEST-';
}
add_shortcode( 'testshortcode', 'test' );
More info: <
If you have to use echo you can also do it this way(useful if there's a lot of markup & it's difficult working with strings)-
function test() {
ob_start();
echo '-TEST-';
return ob_get_contents();
}
add_shortcode( 'testshortcode', 'test' ); | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 10,
"tags": "shortcode"
} |
Minimising number of queries on a page when using Advanced Custom Fields
I'm currently working on a site where there is extensive use of the popular Advanced Custom Fields plugin. However, as a result the page loading time can be quite slow, especially when using the Gallery plugin.
Does anyone have suggestions regarding what the best practice is with managing a large number of custom fields? In some cases I am effectively working with thousands of variables, and need to reduce the page load time from some cases around 5s.
Quite an open question I know, though really it would be great to have some suggestions regarding how number of queries in a page can be minimised (such as through directly accessing values in the database perhaps rather than relying on a plugin's APIs?). | Performance optimization doesn't really work in vaccum, it takes hands-on profiling an looking for actual bottle necks (which often turn out to be different from perceived ones).
But it general there are several approaches to the need of lots of database data:
1. Optimize fetching from database, for example by concatenating multiple requests into retrieving single larger set of data.
2. Install persistent object cache and keep data in memory for faster turnaround.
3. Cache resulting calculations or markup fragments to reduce how often they need to be retrieved and possibly making it async from actual page load. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "wp query, advanced custom fields"
} |
Get custom field from page, in a post?
I'm not quite sure how it works, if you're on a post (single.php), does it count page.php as the page it's on?
What i need to do, is get a custom field assigned to a page, from a blog post. I need it because i want the user to be able to change the "Read more" text in the post excerpt.
I could get the custom field by just using a static page id, but if the user decides to change things up the id might change, i need it to be dynamic.
What would be the best way to go about this? | I would suggest a different approach. The option for manually adding post excerpt should go in a theme option as opposed to a custom field. Also you should use this hook for modifying the excerpt's more text
<
If the user is supposed to enter custom excerpt on a per-post basis, they can do it from the admin panel anyway. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, page template, blog, id"
} |
Save Plugin Version Number as Option?
I seem to recall seeing a tip somewhere saying that it was a best practice to save a plugin's version number as an option. I'm working through releasing a plugin, and I'm considering whether to do it, but since all the plugin does is make a widget (right now, it literally has no other options), I'm struggling to understand what I would ever do with that option. I'm already setting a constant with the version number for use in a couple places (mostly `wp_enqueue_*`).
Can someone either point me to a good resource or explain the use cases for saving the version number as an option? | You need to save the version to the database-- aka. save it "as an option"-- so that your script has a comparison case. That is, your script should...
1. Check the database for a version number
2. Compare that version number to the new version number-- a variable or constant in your plugin file.
3. Update things if need be
4. Save the new version number to the database
If all you have is a constant in your .php file. It always matches, meaning it is pretty much useless for any automated updating. Of course, you can keep track of the plugin versions with just the constant, but the point of saving it to the database is to be able to automatically update things when needed.
As you say, if the plugin is simple enough it may not be necessary. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 4,
"tags": "plugin development, plugin options"
} |
Create a comments template for custom post types
Is it possible to create a comment template for custom post types? I want the wording for comments on a custom post type to be different for wording on a regular wordpress post.
I tried comments-posttype.php but that didn't seem to work. | In the single template of the custom post type i.e. "single-posttype.php" (create one if it doesn't exist). In the function `comments_template()` the first parameter represents the filename, so make it `comments_template('/comments_file_name.php');`
Reference- < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, theme development, theme options"
} |
excerpt in characters
I have code in functions.php:
function string_limit_words($string, $word_limit)
{
$words = explode(' ', $string, ($word_limit + 1));
if(count($words) > $word_limit)
array_pop($words);
return implode(' ', $words);
}
but i need to limit excerpt in number of characters, could you help me with that? | I used this code in one of my last projects:
function ng_get_excerpt( $count ){
$permalink = get_permalink( $post->ID );
$excerpt = get_the_content();
$excerpt = strip_tags( $excerpt );
$excerpt = mb_substr( $excerpt, 0, $count );
$excerpt = mb_substr( $excerpt, 0, strripos( $excerpt, " " ) );
$excerpt = rtrim( $excerpt, ",.;:- _!$&#" );
$excerpt = $excerpt . '<a href="'.$permalink.'" style="text-decoration: none;"> (...)</a>';
return $excerpt;
}
I got it from here:
<
<
It has the advantage of not allowing punctuation on the end and ending with the last complete word
Using the filters as suggested by @medhamza7 or @bainternet or @fuxia is preferable. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "excerpt, characters"
} |
Integrating Custom Database with Wordpress
I Have a Wordpress Site with few users who are my college students
They Registered using their RollNumbers/HallTicket Numbers as their usernames in Wordpress site
Now I Have Another Database with Their Personal Details like Marks, Rank etc
Now I want to Integrate this Database to Wordpress so that when student/user logins , then he/her could see their respective marks and other details
I Just want your suggestions/ideas to implement this, Not asking for a Complete solution
Thankyou | You can use `wpdb` class to query your custom data from MySQL. Depending on your implementation you would either use:
* global `$wpdb` object, if your custom data is in same database as WP itself
* new custom instance of `wpdb` class if you need to connect to different database for custom data | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, database, mysql, customization"
} |
How do I map a subdomain in wordpress to the primary domain in a multisite setup?
We have a multisite setup, the primary domain needs to have domain.com, www.domain.com and secure.domain.com mapped in wordpress so the primary site's content loads on them. The problem we are facing is everything except secure.domain.com works. secure.domain.com always ends up at: <
The headers returned from the server are as follows:
Status: HTTP/1.1 302 Moved Temporarily Date: Tue, 16 Oct 2012 19:55:53 GMT
Server: Apache
Location: <
Content-Length: 0
Connection: close
Content-Type: text/html; charset=utf-8 | In the end I just added the following to .htaccess
RewriteCond %{HTTP_HOST} ^secure\.domain\.net$
RewriteRule (.*) [P,L]
This appears to be working fine, but I'm not sure of what types of unforeseen effects it may have if any. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "redirect, ssl"
} |
How Would You Enqueue A Google Web Font?
I'm using the Rosario font from the Google Web Fonts in my theme and I want to enqueue the font so that if there was ever a plugin that used a fancy font that there wouldn't be any conflicts or wasted bandwidth.
I want to use the Normal 400, Normal 400 Italic, and Bold 700 in my theme. How should I enqueue the font? Is it worth including the last font variant in case the other script uses it?
Several options I've been thinking about:
* Single
wp_register_style( 'rosario', " );
* Combined with Handle
wp_register_style( 'rosario_400_400-italic_700', " );
* ALL together
wp_register_style( 'rosario_400', " );
wp_register_style( 'rosario_400-italic', " );
wp_register_style( 'rosario_700', " );`
The third option looks the most explicit and but the multiple calls for same font will probably be more inefficient than simply loading the font twice.
Thoughts? | You should be able to just use ` which is the "combined" URL given by Google when selecting multiple weights/styles of a font. You can then just register the font once. You don't need to over-complicate the `$handle` either, something like `google-fonts-rosario` should do just fine as long as it is unique as mentioned in the codex. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 4,
"tags": "wp enqueue style"
} |
How to obtain the user ID of the current profile being edited in WP-Admin?
Is there a way of obtaining the user ID of the profile being edited in `wp-admin`?
I know it's in the URL if you are editing a user, EX: `./wp-admin/user-edit.php?user_id=427`. Could always `$_GET['user_id']` to retrieve the user's ID, but what about when you're editing your own profile in `wp-admin`? The user ID wouldn't be in the URL. EX `./wp-admin/profile.php`
Is there an easy or broad way of retrieving the user ID of the current user profile being edited in `wp-admin`? | There is a global variable called … `$user_id` available on that page. Always.
From `user-edit.php`:
$user_id = (int) $user_id;
$current_user = wp_get_current_user();
if ( ! defined( 'IS_PROFILE_PAGE' ) )
define( 'IS_PROFILE_PAGE', ( $user_id == $current_user->ID ) );
if ( ! $user_id && IS_PROFILE_PAGE )
$user_id = $current_user->ID;
elseif ( ! $user_id && ! IS_PROFILE_PAGE )
wp_die(__( 'Invalid user ID.' ) );
elseif ( ! get_userdata( $user_id ) )
wp_die( __('Invalid user ID.') ); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 7,
"tags": "admin, wp admin, users, profiles, id"
} |
Broken Gravatar images in comments
I have no idea why, but recently, all new comments on my WordPress site have broken avatar image links. Here is a page that shows the issue: <
Any idea why this is happening? I haven't installed any plugins recently, so why has it started playing up all of a sudden? | Okay, so it turned out that the default path for the fallback image wasn't being set. I have fixed that (in functions.php) and it is working correctly!
Thanks to @markratledge for leading me down the right path. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "avatar, gravatar"
} |
Widget queries even when there are no sidebars?
I'm trying to reduce my database queries. I don't have any sidebars or widgets set but I noticed the following query
SELECT option_value FROM wp_options WHERE option_name = 'widget_pages' LIMIT 1
Similar queries happen for widget_calendar, widget_links, widget_tag_cloud, and widget_nav_menu.
5 database queries for no reason. How do I disable this?
remove_action('widgets_init') doesn't do anything. | Does unregistering them the also disable the database queries?
Goes in functions.php:
//Unregister all Default Widgets
function unregister_default_wp_widgets() {
unregister_widget('WP_Widget_Pages');
unregister_widget('WP_Widget_Calendar');
unregister_widget('WP_Widget_Archives');
unregister_widget('WP_Widget_Links');
unregister_widget('WP_Widget_Meta');
unregister_widget('WP_Widget_Search');
unregister_widget('WP_Widget_Text');
unregister_widget('WP_Widget_Categories');
unregister_widget('WP_Widget_Recent_Posts');
unregister_widget('WP_Widget_Recent_Comments');
unregister_widget('WP_Widget_RSS');
unregister_widget('WP_Widget_Tag_Cloud');
}
add_action('widgets_init', 'unregister_default_wp_widgets', 1); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "widgets, database"
} |
Deprecated function get_user_by_email($email)
I tried to find replacement function for get_user_by_email($email) but no luck. This function I am using to allow user to log in by email address or user id. Is there any replacement function or alternate way to do that? | `get_user_by` is the replacement for `get_user_by_email`:
$user = get_user_by( 'email', '[email protected]' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "functions, email, deprecation"
} |
How to implement a plugin featuring foursquare like check-in
I need to add a check-in feature (very similar to foursquare check-in) in worpress based site.
There will be "Check in" button at the top of the web site, and clicking on it the visitor will be presented with a list of places.
1. Can somebody guide me to decide which one is more suitable for wordpress architecture?
i. Clicking the "Check-in" button, make an AJAX call and present the list of places as a modal dialog. ii. Clicking the "Check-in" button, present a Worpress page with list of places and a submit button.
2. Where should I host the server side API? Use Wordpress XML RPC or as a separate API application(May be on a different server and cross site AJAX call can be made via php-curl proxy)? | I would use an AJAX call + modal dialog.
And for the API, just create a plugin, and follow the steps on this page to create your own custom ajax action. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, ajax"
} |
Paragraphs removed when using get_post_custom()?
I'm using a custom field plugin called Advanced Custom Fields to create custom fields, but i don't think that's what's causing the problem.
When i fetch the custom fields from a template using get_post_custom(), the
tags in the field is removed. If i view the source, it's written out like a big chunk of text but with "normal" line breaks, but that's not visible unless you view the source ofc.
How do fetch the custom fields and keep the
tags? I tried adding a tag around some text and that went fine, no issues displaying it. It's just
tags, grr.
Any ideas? | Advanced custom fields plugin has it's own set of functions to use, use them instead. Also text fields there have an option of weather to save HTML or pure text
<
They also have nice examples if you go to the documentation of the particular field type | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, custom field, html, content"
} |
How do I create Widget within plugin that uses its own class?
I wrote WordPress plugin and want to include 2 extra Widgets with it...
if( !class_exists('plugin_name') ) {
class plugin_name {
// plugin code
}
}
// include widgets code
require_once( 'include/custom_functions.php' );
...and Widgets (according to WP codex) should be created like this within "custom_functions.php":
class My_Widget extends WP_Widget {
// widget code
}
function sfp_register_widgets() {
register_widget( 'My_Widget' );
}
add_action( 'widgets_init', 'sfp_register_widgets' );
I can't put "class SFP_Search extends WP_Widget" inside my plugin's class and if I place it outside, I get an error:
Class 'WP_Widget' not found in /Applications/XAMPP/...etc
Is there any other solution? Thanks! | There's no need to nest classes (and you can't anyway), you just create a new instance of the class. The code below would automatically call the My_Widget class to create a widget based on your existing code.
Class plugin_name {
// Call the widget class
public function __construct(){
$this->widget = new My_Widget();
$this->widget->getWidget();
}
}
Class My_Widget extends WP_Widget(){
public function getWidget(){
//Do my widget stuff.
echo "I'm a widget";
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, widgets, oop"
} |
How To Limit Hierarchical Pages Depth (For Custom Post Types) To Children Only
Is there a way to **limit the creation of pages** (custom post type) to a **specific depth** \- e.g. level 1 (where 0 = parent, 1 = child, 2 = grand-child, etc.)?
For example, let's create a 'Summer' recipe page (custom post type: Recipe) with a slug '/summer'. Let's now create a 'Pie' page (a child of 'Summer') with a slug '/summer/pie'. I want to prevent the user from creating a page which is a child of 'Pie' or of any other sub-page.
* example.com/summer -> GOOD
* example.com/summer/pie -> GOOD
* example.com/summer/pie/apple -> BAD
* example.com/summer/pie/blackberry -> BAD
Thanks. | function my_test($a) {
$a['depth'] = 1;
return $a;
}
add_action('page_attributes_dropdown_pages_args','my_test');
Put that in a theme's function.php or in a plugin. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 6,
"tags": "custom post types, hierarchical, child pages"
} |
Automatic connect wordpress to facebook with featured image?
I want, when I publish any post, that it shows my facebook with featured image. Most of the plugins don't show feature images but shows other images.
How can I do it - simply connect to facebook and add link to facebook. I have already used a sample connect facebook plugin but it's not publishing automatically.
I'm also using it on `dlvr.it` and `twitterfeed.com`. It posts automatically but don't show featured images. It shows the previous post featured image.
How I can solve this problem. My site | Change your Facebook plugin. I recommend you change the plugin to the official Facebook plugin \- it's been made by some of the same people and allows you to publish immediately.
Image in your RSS feed:
Your RSS feed should be found here (but it's not there?) because you are using another RSS feed plugin.
Your RSS Feed is here, so check if your RSS plugin has a setting to include image.
You might try a plugin like this Featured Image In RSS Feed as well
Also if it is showing an old image, check if you do not have a website cache plugin as that may be caching old content. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "facebook, featured post"
} |
Localise settings section headline
Assuming i've got a bunch of setting sections. I add these sections to my plugin page in the following way.
$sections = array('notifcations', 'updates');
foreach ($sections as $section)
{
add_settings_section(
$section .'_section',
$section,
array( $this, 'disable_callback_warnings' ),
'sgnc'
);
}
Everything works as expected but i wonder how to localise the section headline? As far as i know i can't pass any variables to the locale functions `_e()` and `__()`. So this won't work:
$sections = array('notifcations', 'updates');
foreach ($sections as $section)
{
add_settings_section(
$section .'_section',
__($section),
array( $this, 'disable_callback_warnings' ),
'sgnc'
);
}
< | Localize the headings in your initial array:
$sections = array(
'notifcations' => __( 'Notifications', 'your_text_domain' ),
'updates' => __( 'Updates', 'your_text_domain' )
);
foreach ($sections as $section => $header )
{
add_settings_section(
$section .'_section',
$header,
array( $this, 'disable_callback_warnings' ),
'sgnc'
);
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, options, localization"
} |
How to get the post ID when creating JS variables with localize_script
how do you set the current post ID as a JS variable with localize_script? It seems like the $post variable isn't availible in the functions.php file. When is it created? Do i have to add localize script to a hook? Which? | You should declare `global $post;` before attempting to access this variable, but to answer your question regarding when it is created, the 'wp' action hook is the safest bet.
As such I'd suggest the following in your functions.php file as a simple solution
function my_localize_post_id(){
global $post;
wp_register_script( 'your_script'... /** other parameters required here **/ );
wp_localize_script( 'your_script', 'the_name_for_your_js_object' , array( 'post_id'=>$post->ID ) );
}
add_action( 'wp', 'my_localize_post_id' ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "wp localize script"
} |
Page downloads as file in Chrome
I'm looking to see if I could get pointers in where to look to solve this issue.
## Issue
In Chrome, viewing the blog < in Chrome v21, the page downloads as a file "download", rather than opening normally.
The rest of the site on the same server loads fine in Chrome.
All pages load fine in Firefox.
## Background
I suspected that it was something to do with the APC caching for Apache, and/or WP Super Cache. However, after disabling both, and clearing my browser cache, the problem continues. | The page is sent with:
Content-Type: application/x-gzip
Change the Content-Type to `text/html`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, plugin wp supercache, apc"
} |
Logged in user ID as post ID
Is there a way to automatically insert the current user ID as the post category name or maybe have WordPress display only the post with a category name that matches the current logged user ID?
<?php
$query = new WP_Query('category_name=current-user-id');
if($query->have_posts()) : while($query->have_posts()) : $query->the_post();
?>
<?php
the_content( __('Read the rest of this page »', 'template'));
endwhile; endif;
wp_reset_postdata();
?> | You can get information on the currently logged in user using the get_currentuserinfo() function.
For example:
<?php
global $current_user;
get_currentuserinfo();
$username = $current_user->user_login;
$user_id = $current_user->ID;
?>
You can then use $username or $user_id in your custom loop.
<?php
// assign the variable as current category
$category = $user_id;
// concatenate the query
$args = 'cat=' . $category;
// run the query
query_posts( $args );
if ( have_posts() ) : while ( have_posts() ) : the_post();
// do something here
endwhile;
endif;
wp_reset_query();
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, functions, query posts, get posts"
} |
Headers already sent - Wordpress core
I'm getting an error on my site regarding "headers already sent":
> Warning: Cannot modify header information - headers already sent by (output started at ........./wp-admin/menu-header.php:161) in ....../wp-includes/pluggable.php on line 881
I read the Wordpress FAQ that discusses this, but - as you can see - this error is caused by the Wordpress core (and not even at the end of a file).
Interestingly, I don't get this error on my local machine. Only on my server.
What can I do about this?
I'm running Wordpress 3.4.2 | Wordpress provides a way to prevent the header HTML from being rendered, by appending `&noheader=true` to the url.
That will cause the header HTML to wait for you to call it manually, so that you can do a redirect before that.
To later render the header HTML from your page, you'll have to use this:
if ( isset($_GET['noheader']) ) {
require_once(ABSPATH . 'wp-admin/admin-header.php');
}
For more information, read this article: **WordPress and wp_redirect() function problem**. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "redirect, headers, wp redirect, core, core modifications"
} |
Translate widget titles using qTranslate plugin
I'm actually using the qTranslate plugin to translate my website. It works really well with everything except one thing. the titles of my sidebar widgets.
Actually, to translate some words we need to put tags like this:
<!--:en-->My English Title<!--:--><!--:fr-->My French Title<!--:-->
When I use this in the content of my widget it works well. But in the title when I save the widget. It actually remove my tags and just displays:
My English TitleMy French Title
Anyone know how to fix this? | I just found the answer and instead of putting this in the Title:
<!--:en-->My English Title<!--:--><!--:fr-->My French Title<!--:-->
We need to put this code:
[:en]My English Title[:fr]My French Title
and qTranslate does the rest :) | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 9,
"tags": "widgets, sidebar, title, translation, plugin qtranslate"
} |
Combining two meta_values within one row with query
I've added two new meta_keys to the `wp_usermeta` table:
`bid_user_lat` and `bid_user_lng`
And I need to be able to get both of these values within a single row, along with the `user_id`.
`ROW - (user_id) 220 | (bid_user_lat) 45.099080 | (bid_user_lng) -140.09099`
Now comes the tricky part ... I then need to use these values within a calculated radius statement:
`( 3959 * acos( cos( radians( @lat ) ) * cos( radians( **bid_user_lat.meta_value** ) ) * cos( radians( **bid_user_lng.meta_value** ) - radians( @lng ) ) + sin( radians( @lat ) ) * sin( radians( **bid_user_lat.meta_value** ) ) ) ) AS distance`
In the end, I'm making sure that the user is within a certain radius, and if so, I will return it within the query.
**But the most important part is being able to query the`wp_usermeta` the way I need to!** | You can use the `WP_User_Query` class which works much like `WP_Query`.
The docs: <
Below is a dump of the WP_User object that it will return, in this example using:
$wp_user_search = new WP_User_Query( array( 'fields' => 'all_with_meta' ) );
$get_users = $wp_user_search->get_results();
!user var_dump
This should set you in the right direction because it was not obvious how your new meta_keys are set up and exactly how you want to run the query. The second question isn't really related to WordPress :)
If you don't want to use `WP_User_Query` you will have to use `$wpdb` which is more direct mySQL query.
it would be something like:
global $wpdb;
$get_map_user = $wpdb->get_results("SELECT * from $wpdb->usermeta WHERE meta_key = 'bid_user_lat'");
It would probably be better if you had one `meta_key` with 2 values for your long/lat, instead of 2 meta keys.
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "query, post meta, user meta, wp user query"
} |
Generate featured images old posts
I am looking for a way to generate featured image per post based on the first image in the post for old posts without a set featured image. I'm switching from handmade thumbnails to auto generated featured images. With new posts I got this working, but I don't want to set a featured image of my other 2000 posts by hand. Found some plugins, but they aren't working well or not supported and the info I did find here is all about setting the image with new posts. Any hook, script or function for this? Anyone got an idea? | You can look into this post: <
Or if you're comfortable with MySql try using this (obviously check it on local database first):
INSERT into wp_postmeta (meta_value, meta_key, post_id)
SELECT DISTINCT(ID), post_type , post_parent
FROM wp_posts
WHERE post_type= 'attachment'
AND post_parent !=0
AND post_status='inherit';
UPDATE wp_postmeta set meta_key = '_thumbnail_id'
WHERE meta_key='attachment' | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "functions, scripts"
} |
Adding option to Gallery shortcode
just starting out in WP dev, and I'm looking for any guidance I can get. What I'd like to do is use a hook or filter to add my own option to the core WP gallery shortcode. I would want it to work just like the standard 'exclude' option, but still show those images for Administrators. So it would look something like this: `[gallery exclude="1" hide="2,3,4,5,6" link="file"]`
So, basically I'm looking for guidance on how to create a function that would add the "hide" function to individual image id's within the gallery shortcode which would work exactly like the exclude, but those images would still show up in the frontend for administrators. Thank you for your time, and expertise. | This code should work in your functions.php
add_shortcode('gallery', 'custom_gallery_function');
function custom_gallery_function($atts) {
$user = wp_get_current_user();
// if current user isn't admin, add posts to be hidden to exclude
if(!in_array('administrator', $user->roles))
$atts['exclude'] = $atts['exclude'] . ',' . $atts['hide'];
// call the wordpress shortcode function
return gallery_shortcode($atts);
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, functions, shortcode, hooks, gallery"
} |
Dashboard widget custom positioning?
I cannot figure out how to arrange my custom widgets one left and one right.
I'm using this code to create custom widgets:
//Add my comments. Shows user his last 5 comments
function dashboard_user_comments_widget_function() {
echo 'beh!';
}
function dashboard_user_add_comments_widget_function() {
wp_add_dashboard_widget('my_comments_user_dashboard_widget', 'My comments', 'dashboard_user_comments_widget_function');
}
add_action('wp_dashboard_setup', 'dashboard_user_add_comments_widget_function');
Is there a way to pass a left/right variable into this function?
I read the codex page for it and the way they explain doing positioning is quite complicated, I don't know how to incorporate it. | The dashboard widget function `wp_add_dashboard_widget()` is just a wrapper for `add_meta_box()`. So you can use the underlying function instead.
add_meta_box(
'my_comments_user_dashboard_widget'
,'My comments'
,'dashboard_user_comments_widget_function'
,$screen // Take a look at the output of `get_current_screen()` on your dashboard page
,'normal' // Valid: 'side', 'advanced'
,$priority // Valid: 'default', 'high', 'low'
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, widgets, dashboard"
} |
Users disappeared from wp-admin
I have a WordPress multisite network and the question is related to one of my sites on that network. The site has a login page before you can use that site.
So I created a user from wp-admin with the Subscriber role.
The idea was to let that user log in to the site but not have access to wp-admin, but it didn't work.
So I went in again as a Superadmin and changed the role to " - No role for this website - ".
It worked and that user can't access wp-admin but can still log in to the site.
Now I want to edit that user's information, but the user disappeared from the list shown in wp-admin.
My question is:
**Where do I find that user?**
Some follow-up questions: is it removed but still active? How come? Is there a specific location where I could find that user? | you'll find the user in network admin => users | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp admin, users, login"
} |
Hide comments awaiting moderation from user who submitted the comments
This is a strange one. I host a website that is primarily for children. All posts are moderated. Users are required to enter a user name and location (State), but are not required to be registered and logged in to make a comment. Some users have started using a common user name, allowing them to see one another's posts while the posts are awaiting moderation. This allows them to use the posts awaiting moderation like an unmoderated chat room, until the moderator gets to the comments.
I would like to filter the comments on the posts so that only approved comments are shown, regardless of whether the user just entered a comment that is awaiting moderation.
I have looked in the wp-includes/comments.php, and in the wp-includes/post.php but haven't been able to find where to limit the comments that are seen on the posts.
Can anyone direct me further? | Check in your theme's `comments.php` for the `wp_list_comments()` function. In the Twenty Eleven theme, for example, uses a custom callback function which is in the `functions.php` file and outputs the template for comments.
Within this comments template, you can then use **`wp_get_comment_status()`** and only display a comment if it was approved. Example from the Codex:
$status = wp_get_comment_status( $comment_id );
if ( $status == "approved" ) {
// the rest of the comment loop
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "posts, comments, users, moderation"
} |
Wordpress plugin url for form submit
I am creating a custom plugin that has dynamic forms and I wanted to ask on how I can create a dynamic form action url.
Example is Contact Form 7, how did cf7 create the form action url without creating a new page or a file for submission?
Please share any idea on how to do something like that for plugin.
Thanks | It doesn't need a new submit URL, most of the plugins submit the form on the same page(the one on which the form was rendered), then before rendering the form they check if there is submitted data present. Then for eg. if data is present then they have to show a thankyou message & skip rendering the form, if there is no data present they will just render the form
This logic of course differs a lot | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, url rewriting, routing"
} |
Can I lock a post in position, so it always appears on the homepage?
I'm a complete noob when it comes to Wordpress, but I've joined a company who use it as their website and they need an answer quickly. I want to know if I can I lock a post in position, so it always appears on the homepage ? I don't want to use a plug-in (preferably) Any suggestions or advice is greatly appreciated.
Thanks | Depending on the theme you are using. You might want to look into creating a page for your home page and then going into settings > reading and making that page your static home page. If you want to lock a single post on your front page and your theme lets you... try :
I the Post editor find the "Publish" section. Next to "Visibility" click on edit and then check the "Stick this post to the front page" option there. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts"
} |
change a post status when users update posts?
Is there an efficient way to change a post status from 'published' to 'draft' when a user of a certain type tries to update their posts. I tried something along these lines
function change_post_status($post_id)
{
if(current_user_can('rolename'))
{
$current_post = get_post( $post_id, 'ARRAY_A' );
$current_post['post_status'] = 'draft';
wp_update_post($current_post);
}
}
add_action('pre_post_update','change_post_status');
The code looks good to me but for some reason it doesnt work properly and I think it creates an endless loop(forcing me to restart my SQL server). | So I ended up using the wp_insert_post_data filter and came up with the following, which after testing, seems to be working properly.
add_filter('wp_insert_post_data', 'change_post_status', '99');
function change_post_status($data)
{
if( (current_user_can('role')) && ($data['post_type'] == 'custom_post_type') )
{
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
//then set the fields you want to update
$data['post_status'] = 'draft';
}
return $data;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, post status, draft, wp update post"
} |
How to format shortcode's HTML in external file
I need to add a shortcode in my theme and I would like to put the HTML code not in the function which creates the shortcode but in a template file in my theme directory.
Now I have
function wpse450_show_video( $atts ) {
extract(shortcode_atts(array(
'id' => 0
), $atts ));
if( is_numeric($id) ) {
$ngvideo_title = get_the_title($id);
}
return '<div>'.$ngvideo_title.'</div>';
}
add_shortcode( 'ngvideo', 'wpse450_show_video' );
I would like to put the `<div>'.$ngvideo_title.'</div>` stuff in an external file.
How to do this? | function wpse450_show_video( $atts ) {
extract(shortcode_atts(array(
'id' => 0
), $atts ));
if( is_numeric($id) ) {
$ngvideo_title = get_the_title($id);
}
ob_start();
include 'path/to/file/video.php';
return ob_get_clean();
}
add_shortcode( 'ngvideo', 'wpse450_show_video' );
You can use $id, $atts in our file as you would in your function. The code in your file will behave just like it would have in your function with just one difference that you'll have to echo the stuff instead of returning it like you would for your function | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "templates, shortcode"
} |
Check if user is logged in using JQuery
I want to execute custom jquery code which shows login dialog to user if he clicks a button and he is not logged in. How could I do that? | In case you want to know if the user is logged in at the current moment, try this. The other answers check if the user is logged in or not when the page loaded, not the time when you're running the javascript. The user could have logged in in a separate tab, for instance.
Put this in your javascript
var data = {
action: 'is_user_logged_in'
};
jQuery.post(ajaxurl, data, function(response) {
if(response == 'yes') {
// user is logged in, do your stuff here
} else {
// user is not logged in, show login form here
}
});
Put this in your `functions.php`
function ajax_check_user_logged_in() {
echo is_user_logged_in()?'yes':'no';
die();
}
add_action('wp_ajax_is_user_logged_in', 'ajax_check_user_logged_in');
add_action('wp_ajax_nopriv_is_user_logged_in', 'ajax_check_user_logged_in'); | stackexchange-wordpress | {
"answer_score": 31,
"question_score": 23,
"tags": "jquery, login, jquery ui"
} |
WP doesn't show Array Custom Fields?
I'm wondering why WordPress doesn't list PHP `array()` and any serialized data in Custom Fields in Admin Panel (for Pages, Posts etc.)? Only Custom Fields containing strings and numbers show up and can be edited by user manually.
Edit: Why aren't post meta values displayed if they are stored as a non-string value, meaning, stored as either arrays or a serialized value ?
Example: If a post has a meta key 'custom-meta' with a string value as 'yes', it is displayed in the meta box, but if it has an array value like `array('value' => 'yes')`, it is not displayed in the meta box.
Can I enable this? | There is no filter to change that behavior, you would have to replace the entire metabox.
On the other hand: I think there is no really simple way to show and to save those arrays.
Example for a fictive meta key `'foo'`:
array (
0 => 2,
'hello' => array (
0 => 2,
'hello' => 'world'
)
)
Creating a default interface for such an array would be very hard. This metabox is for simple fields, it should be easy to use. And you cannot just present the serialized string: editing that would probably break it. So I think it is a compromise. Better than nothing, but not perfect. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "custom field, functions, array, sanitization"
} |
how i can increase Featured thumbnails size?
when i open any post then 1st image show my featured image. i want to increase this size . see it or . i already try to increase from single.php to change this code
<p><img src="<?php echo get_template_directory_uri(); ?>/images/thumbnails/thumbnail-leadimg.jpg" width="610" height="320" alt="<?php the_title_attribute(); ?>" /></p>
but it's not working . my orginal code
<p><img src="<?php echo get_template_directory_uri(); ?>/images/thumbnails/thumbnail-leadimg.jpg" width="610" height="225" alt="<?php the_title_attribute(); ?>" /></p>
i don't understand how i can change it. my site < . | It's probably because the original image is not big enough. You can make the image display bigger via CSS :
.post_thumbnail{
height: 320px
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "post thumbnails, thumbnails, customization"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.