INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
On Plugin Activation, How Do I Check for Proper Transport Mechanism?
For a plugin that communicates with somewhere else, I hear we're supposed to use wp_remote_post and wp_remote_get instead of PHP's Curl library.
Okay, but is there a fast and proper way on plugin execution to test for a blog's PHP/host OS to have the proper transport mechanism installed? I mean, I could attempt a test POST, but thought WP might have a better, faster mechanism that I can test for? Doing the following is unacceptable:
if (!function_exists('curl_exec')) {
wp_die('The CURL API is not installed with PHP. You cannot use this plugin without that. Ask your web hosting provider to install it.');
} | I wouldn't cause the plugin to die like that. Just check for cURL each time you need to make a call or fall back on `wp_remote_(post|get)` (eg. write a wrapper function that takes care of the check and send the data/headers you want).
BUT, if you really really want to disable the plugin if cURL is not installed, you can use an activation hook to check for the `curl_exec` function and deactivate the plugin if not.
<?php
register_activation_hook(__FILE__, 'wpse51312_activation');
function wpse51312_activation()
{
if(!function_exists('curl_exec'))
{
// Deactivate the plugin
deactivate_plugins(__FILE__);
// Show the error page, Maybe this shouldn't happen?
wp_die(
__('You must enable cURL support to use INSERT PLUGIN NAME'),
__('Error')
);
}
}
For what it's worth, I believe that the HTTP api tries to use cURL if it's available. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugin development, wp remote get, curl, wp remote post"
} |
Getting the action's tag name within the action
There's a function attached to a set of actions, like this:
add_action('some_tag', 'the_function');
function the_function($maybe_some_vars){
// ...
}
Is it possible to find out the action name ("some_tag") within the_function?
The reason I'm asking, is that I'm attaching the function to multiple actions (some of them custom, some belong to WP like `the_content`). The code that executes within the function depends on knowing the name of the action.
I did manage to get it using `debug_backtrace()`, but I'm pretty sure that's not a very reliable way. | Simple: `current_filter();` (link to plugin.php) or `global $wp_current_filter;`. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "php, actions"
} |
Create WordPress taxonomies based on theme settings
Is it possible to create taxonomies based on theme settings? That is, are theme settings actions run before taxonomies / post types are initialized? | Yes. Post types and taxonomies are (should be) registered on the `init` hook. You are able to use `get_option` inside that hook to retrieve your theme's settings and register your post type/taxonomy with args based on those settings.
(By the way post types and taxonomies are really plug-in territory... :) ) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, actions"
} |
How can I detect if a user changes their password?
I would like to track when a user changes their password. Is there a way to detect when a password has been changed? | WordPress sends an email to the admin's email when a user resets their password.
To get a notification when a user changes their password you could hook into the `profile_update` action which is fired when a user's profile is updated.
When the action is fired WordPress has already validated and updated the user's details we only need to check if the user submitted a password with the request, if it was submitted then the user's password has changed.
function my_profile_update( $user_id ) {
if ( ! isset( $_POST['pass1'] ) || '' == $_POST['pass1'] ) {
return;
}
// password changed...
}
add_action( 'profile_update', 'my_profile_update' ); | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 4,
"tags": "filters, password"
} |
How do I add a promotional message to my posts?
I'm sure this is a dup, but I honestly can't find an answer.
I'd like to add a message to the start and end of my posts:
"Check out my new startup: Facebook For Dogs!"
Is there a simple way to do this, hopefully using a plugin? | You'll want to hook into `the_content` to add a message.
Something like this:
<?php
add_filter('the_content', 'wpse51338_filter_content');
/*
* Filter the content to add a message before and after it.
*/
function wpse51338_filter_content($content)
{
// not a singular post? just return the content
if(!is_singular())
return $content;
$msg = sprintf(
'<p class="special-message">%s</p>',
__('Here is an awesome message!', 'your_textdomain_string') // this is your message
);
return $msg . $content . $msg;
}
As a plugin. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "customization"
} |
Listing all posts from current category on page
I'm trying to list all posts from a certain category, in a list, on the category page that already lists the posts out in blog form. I'm trying to do it in the header area so that you can get an overall look at the posts on the page. I found this:
<ul>
<?php
global $post;
$category = get_the_category($post->ID);
$category = $category[0]->cat_ID;
$myposts = get_posts(array('numberposts' => 5, 'category__in' => array($category), 'post__not_in' => array($post->ID),'post_status'=>'publish'));
foreach($myposts as $post) :
setup_postdata($post);
?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?></a>
</li>
<?php endforeach; ?>
<?php wp_reset_query(); ?>
</ul>
But it always seems to cut one of the posts out of the list. Is there an easier way to do this, without a plugin?
Thanks | Good news! I think you're making things harder for yourself than they need to be. If I understand your question, you're looking for `rewind_posts()`. The always useful _Digging Into WordPress_ has a nice summary of it.
Because both tasks involve looping through the _same query_ , you don't need `get_posts()` at all.
Instead, you'll want to use the aforementioned `rewind_posts()` something like this:
<?php if( have_posts() ) : ?>
<!-- Your list of posts -->
<ul>
<?php while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php rewind_posts(); // second <del>verse</del> query, same as the first ?>
<?php while( have_posts() ) : the_post(); ?>
<!-- your "blog-style" stuff -->
<?php endwhile; endif; ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, pages, loop, array, list"
} |
How to remove welcome screen and its screen option checkbox?
Clicking the screen options on dashboard, the drop down area has welcome checkbox. So even after hiding the welcome screen, if user chooses to display the welcome screen. It still shows.
Is there a way to hide this option completely and turn off the welcome screen? Or otherwise, a way to remove the welcome content completely and replace it with something else? | For WordPress 3.5+, adding `remove_action( 'welcome_panel', 'wp_welcome_panel' );` to your functions.php removes the Welcome Panel from the Dashboard as well as its Screen Options menu.
See < | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 7,
"tags": "screen options"
} |
How to add nofollow to wp_nav_menu
I need to add an option in my theme options panel to set a specific custom menu's links all to nofollow.
Does wp_nav_menu() allow this or does it require a custom walker to manually ad rel="nofollow"? | !Advanced Menu Properties
As you can see above, the **Advanced Menu Properties** are hidden under the **Screen Options** pull down tab located in the upper-right corner of WordPress Dashboard.
**_NOTE:** Make sure that you are in the **Menus** screen: `
W.r.t your question, the **Link Relationship (XFN)** option is what you want "check". Then the appropriate field will show up for each menu item allowing you to define its relationship (`rel="____"`). You can also leave it blank for some items (meaning, no relationship will be specified). | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "theme development, menus"
} |
Get object terms with no children?
Others have asked how to only get parent terms, but I need to get the deepest term for the post of a specific taxonomy.
Is there a way I can only get terms where the number of children = 0? | I have written this function some time ago, it may be a bit sloppy but it does it's job:
function get_low_level_term( $taxonomy ) {
$term = null;
if( is_single() ) {
global $post;
$terms = get_the_terms( $post->ID, $taxonomy );
if( count( $terms ) == 1 ) {
foreach( $terms as $t ) {
$term = $t;
}
}
else {
foreach( $terms as $t ) {
if( $t->parent ) {
$term = $t;
}
}
if( !$term ) {
$count = 0;
foreach( $terms as $t ) {
$term = $count == 0 ? $t : $term;
$count ++;
}
}
}
}
return $term;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "terms"
} |
Modify plugin and submit to directory
Just a quick question: Can I modify a plugin and submit the modified plugin to directory under another name? | It depends on the license of the source plugin. In case you've downloaded that plugin from Wordpress Plugins Directory, then you can modify and upload it as it inherits the GPLv2 license of Wordpress itself or GPLv2-compatible license of the modified plugin.
Here are some guidelines.
Also, it's polite to mention the original author ("Inspired by:", "Based on the plugin of:" etc.).
**Edited** : Licensed precised, link added. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, licensing"
} |
Category Template - Show Last Entry as Featured
I am working on my category template. Here is how I want the page to display:
1. Category Name - `this is done`
2. The latest post for each category be on top `(then styled which I can do)`.
3. The Category description - `this is done`
4. List all the rest of the posts for the category under it - `I can list all the posts, but I want to skip the latest`
Any help in pointing me in the right direction, I would appreciate it. Thanks | Use WP_Query's built in `current_post` counter in your loop:
while( have_posts() ):
the_post();
if( $wp_query->current_post == 0 ):
// this is the first post in the loop
else:
// this is > first post
endif;
endwhile;
EDIT w/html:
<?php
while( have_posts() ):
the_post();
if( $wp_query->current_post == 0 ):
?>
featured post
category description
<ul>
<?php
else:
?>
<li>post</li>
<?php
endif;
endwhile;
?>
</ul> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, templates"
} |
Help with url rewrite
How can I turn a URL like:
`
into:
`
?
I was looking the rewrite doc here: <
and came up with this
// Adding a new rule
function my_insert_rewrite_rules( $rules )
{
$newrules = array();
$newrules['(project)/(\d*)$'] = 'index.php?project=$matches[2]';
return $newrules + $rules;
}
// Adding the id var so that WP recognizes it
function my_insert_query_vars( $vars )
{
array_push($vars, 'project');
return $vars;
}
add_filter( 'rewrite_rules_array','my_insert_rewrite_rules' );
add_filter( 'query_vars','my_insert_query_vars' );
add_action( 'wp', 'test');
function test()
{
global $wp_rewrite;
$wp_rewrite->flush_rules();
if(isset($_GET['project'])){
echo $_GET['project'];
exit;
}
};
but it doesn't work when I access for example < | The PHP code is not enough, you need to edit your .htaccess file correspondingly. (You can do this with `$wp_rewrite->mod_rewrite_rules();` somehow, or edit it manually.) However, be aware that URL rewriting is complicated stuff - are you sure you need it? If you are using pretty permalinks for posts/pages, chances are this will bork it up. | stackexchange-wordpress | {
"answer_score": -2,
"question_score": 0,
"tags": "url rewriting, rewrite rules"
} |
Retrieve or Query Pages by ID
I have a problem with my code, I want to display 3 specific pages on my homepage but my code is not working.. here's the code..
<?php $args = array(
'post_type' => 'page',
'post__in' => array(3,5,7)
);
query_posts($args);
while (have_posts()) : the_post();
$do_not_duplicate = $post->ID; ?>
<div class ="date_author group">
<h3 class="date"><?php the_time('M j, y');?></h3>
</div>
<h3 class="title"><a STYLE="text-decoration:none" href = "<?php the_permalink();?>"><?php the_title();?></a></h3>
<?php the_excerpt();?>
<?php endwhile; ?> | This is an inappropriate use of `query_posts()` which is only for modifying the _main query_ for the page. Additionally, even if you change your snippet to use `get_posts()`, your template tags (e.g. `the_excerpt()`) won't work as `get_posts()` isn't a method of looping through posts, it just returns an array of posts.
What you want is `WP_Query`. Change your first lines of code to this:
$args = array(
'post_type' => 'page',
'post__in' => array(3,5,7)
);
$my_three_posts = new WP_Query( $args );
while ($my_three_posts -> have_posts()) : $my_three_posts -> the_post();
... | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "wp query, query posts, query"
} |
How Do I Make WordPress Run an Event Every Day?
In a plugin I want to build, it deals with contests. A contest has a date on it. Does WordPress have a feature in it where it can run a piece of code every day without requiring someone to create a cron job? Basically I'm wondering if, when you build a blog with WordPress, if WordPress.org or Automattic automatically pings your site once a day or something like that. Because if that's true, I can hook that event and make it run a contest date check. | Check out wp_cron and the cron_schedules filter. There are lots of good tutorials out there like this one from WPTuts or this one from Viper007Bond. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "plugin development, cron, events, date, wp cron"
} |
Prevent empty Post Title on form submit via front end post (wp_insert_post_)
I am creating a post from the front end using (shortened for brevity);
if (empty($_POST['my_title'])){
echo 'error: please insert a title';
} else {
$title = $_POST['my_title'];
}
$new_post = array(
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'post'
$pid = wp_insert_post($new_post);
If no Post Title is present on **submit** then the form returns the error message,
**error: please insert a title**
However WordPress still inserts the post with a title of **(no title)**.
Is there a way through simple PHP validation to prevent `wp_insert_post` from accepting an empty value? _(without using Javascript)_.
!IMAGE | Simply put the `wp_insert_post` call inside your conditional check so its only called if the post title is not empty, something like this:
if (empty($_POST['my_title'])){
echo 'error: please insert a title';
} else {
$title = $_POST['my_title'];
$new_post = array(
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'post');
$pid = wp_insert_post($new_post);
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "front end, wp insert post, validation"
} |
How to encode post content as JSON?
I`m trying to construct a json object but are having difficulties with the_content since it returns newlines, which causes the script to fail. The error messages received is: **Uncaught SyntaxError: Unexpected token ILLEGAL**
**Example of the json:**
[ {image : ' title: 'Example string
with newlines
that outputs illegally!'}]
Ideally I'd want it to output the HTML content (as seen when pressing the HTML tab in the editor). | To output JSON always the function `json_encode( $string )`. The function is not available on all hosts. Don't worry, WordPress offers a fallback in `wp-includes/compat.php`. That's a wrapper for `class Services_JSON::encodeUnsafe()` (see `wp-includes/class-json.php`).
If you take a look at the source you'll see: It's not a trivial job to encode a string. :)
There is a small difference: The native PHP `json_encode()` accepts a second parameter `$options` since PHP 5.3.0. The WordPress fallback doesn't.
New lines are encoded as `'\n'` in JSON; you cannot get the same output as in the HTML tab in TinyMCE.
And there is, of course, also a fallback for `json_decode()` in case you need it. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "the content, encoding, json"
} |
Get post ids sorted by meta_key
I have defined a `post_view_count` meta_key to store the number of post views. I would like to get an array of post ids sorted by `post_view_count` value to use in the `functions.php` file.
Thanks. | It's easy. :) You would use get_posts function. See WP_Query class for complete list of parameters that you can use.
function get_posts_by_view_count() {
$ids = array();
$args = array(
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_key' => 'post_view_count'
);
$posts = get_posts( $args );
if( $posts ) {
foreach( $posts as $post ) {
$ids[] = $post->ID;
}
}
return $ids;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom field, query"
} |
Plugins loading multiple copies of JQuery
I'm having issues where multiple copies of jQuery are being loaded onto the page via plugins that require jQuery.
I Just want to confirm that if I have 3 plugins active on my page, that all properly use **wp_enqueue_script** to load jQuery, will the library be included only once or 3 times? | If all three plugins load jQuery properly using `wp_enqueue_script("jquery")` then only one copy of jquery will be used.
If you are seeing three copies then some plugins are not playing nice. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "jquery, wp enqueue script"
} |
How to tell WordPress that jQuery exists on the page to avoid duplicates via wp_enqueue_scripts
To reduce http requests, I'm combining all scripts that my theme uses into a single minified .js file each time theme options is saved.
One of the files in this .js is the jQuery library.
Rather than including jQuery as a separate file (using wp_enqueue_scripts), I'm including the wordpress core jquery file as part of the output stream of this master .js file
The problem is that since I'm not using wp_enqueue_scripts() to load jQuery, there's is a possibility it can be included more than once on the page via a plugin that does not know its already there.
Can I set a flag so that WordPress knows that file already exists on the page? | You really shouldn't do it, it's not a good practice. You should always use the jQuery version supplied with WordPress package. If you use your own jQuery version in your own file you would have to update it manually every time the jQuery gets updated in WordPress package.
If you really insist on doing that, the most simple, hackish solution I can think of is to first deregister the original jQuery, then register your file (minified.js) as jQuery. You will surely run into problems of incompatibility with plugins sooner or later. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery"
} |
How to remove automatic generated <p> tag in Home page
I am new to Wordpress and need some helps here. I am trying to add posts that have written codes for the demonstrated purpose of programming languages.
I installed SyntaxHighlighter Evolved plugin. The post looks great when I preview it or view the post under category. However, it seems that Wordpress generated `<p>` tag in my Home page and messed up the codes of the post. I am not sure how to fix this.
Any thoughts? Thanks a lot. | On archive pages like a blog home page the `the_excerpt()` is used normally. As the name says it shows just a snippet from your post.
Most content filters are not applied to the excerpt, they work on `the_content()` only.
Fix: change your template, replace `the_excerpt()` with `the_content()` in archive pages. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, code, homepage"
} |
Override typo in multiple parent theme files?
I'm using the lovely Imbalance theme from WPShower. I am able to make almost all the modifications I need through files and filters in the child theme I created. However, there is a typo that appears in multiple files:
<?php printf(__('<span>Filled under:</span> %s'), get_the_category_list(', ')); ?><br />
This line is in archive.php. attachement.php, archive.php, and single.php. Is there a way to change "Filled under" to something like "tags" without directly editing the parent theme files?
Thanks! | You can override it, but you'll have to create Child-Theme versions of `archive.php`, `attachment.php`, and `single.php`.
Since it's a translation string, you might be able to do something hackish, like provide a en_US.MO file that translates "Filled under" as "Filed under" (or whatever you want). But that gets tricky - and This Theme appears to be `_doing_it_wrong()`, putting HTML tags inside of `__()`. So I'm not sure I'd even want to start messing with translation files.
The best solution would be to report the incorrect string as a **bug** , directly to the developer. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, child theme, parent theme"
} |
Which action does wp_update_user triggers?
I am working modifying an ecommerce plugin, and it makes uses of wp_update_user() function, and everytime the function runs another table (created by the plugin), gets updated too. The problem is that the updated data on that second table is incorrect, and I am having troubles finding the part of the code that does it.
**So I was wondering, does the wp_update_user( ) function triggers some "action" so I can search for that in all the files?** like those used in for example:
add_action('wp_logout', 'logout_handler'); | `wp_update_user()` is in `/wp-includes/user.php` lines 1401-1439. It uses `wp_insert_user()` (same file, lines 1254-1380) to update the existing user or add a new one if the user doesn't exist. That function is where the various filters and actions affecting user account info live, and shows everything you can do to the `$user` object. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, hooks, wpdb, actions, updates"
} |
Custom Post Type Date Based Archive URL rewrite
> **Possible Duplicate:**
> custom post types, wp_get_archives and add_rewrite_rule
I have a custom post type called "course" and I would like to create a date based archive similar to the default post archives which look like mysite.com/2012/05.
I want to use urls like mysite.com/ **course** /2012/05.
How can I do this using the WordPress rewrite API? While avoiding plugins.
This solution is very close How to give a CPT (custom post type) a date based url but I would like to avoid using a query var if possible and stick with the year/month based urls. | Had similar situation not long ago. Check the answer to my question here. I believe that will solve your problem. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, url rewriting, archives, rewrite rules, custom post type archives"
} |
Where and how to put inline js in pages
On the Web there are many articles on how to insert external scripts into a document using the `wp_enqueue_script()` _method_.
Among the articles I couldn't find anything explanaining how to add inline, `<script>` tag enclosed scripts.
I use `<script>` tags in the middle of my documents though I suppose doing so is not the most elegant way. There should be a better way to add arbitrary scripts so the code is automatically moved in the head or the footer. Is there? | You can add inline js by using the **wp_add_inline_script** function.
function prince_scripts() {
wp_enqueue_script( 'prince-script', get_template_directory_uri(). 'main.js');
$hide_on_mobile = apply_filters( 'prince_hide_on_mobile', true );
$data = 'var hideOnMobile = ' . ( $hide_on_mobile ? 'true': 'false' ) . ';';
wp_add_inline_script( 'prince-script', $data, 'before' );
}
add_action( 'wp_enqueue_scripts', 'prince_scripts'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 5,
"tags": "functions, javascript"
} |
AZindex related help needed
I want to display list of post in category page using AZindex. So I've created a category template. Now I need help to display posts list by category there. For instance, when I'll go to domain.com/category/health, the page should display only post list from health category using azindex. Is it possible? I need your help. | You can create a custom category template and this can help you. All the best | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
Validate data on attachment_fields_to_save
I'm very glad that there is such a dedicated website for WP.
My problem is data validation upon saving attachment fields. I have added many custom fields to attachment/media library dialog, most of them are marked as mandatory. (Ex. `$form_fields["some_custom_field"]["required"] = true;`) But this just adds the class, but no validation or checking is done on WP side, so I want to check them myself with functions attached to `attachment_fields_to_save` filter. I can check and so on, BUT THE QUESTION IS: How to validate these fields, so if validation do not pas - WP returns an error in it's regular style, just like in registration form if you fill bad email.
In registration process in `register_post` action you can do this `$errors->add('some_error_code', "<strong>Klaida</strong>: Nenurodėte įmonės kodo");` and it will not save data and return to visitor an error. I want that in saving attachment form :D | # THE ANSWER
Well as it happens many times in my life - i found the answer myself. For people who struggles as me here the answer:
`$post['errors']['field_name']['errors'][] = __('Error text here.');`
if you do that - error text will be displayed at the bottom of that field. In my case this doesn't work because i'm using inline media uploader, but with standard WP media uploader (the popup version) it's working just fine.
BTW best article about custom fields is here: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom field, attachments, errors, validation"
} |
Checking for published posts in a certain post type
I run a website for a company with a careers section, with each vacancy posted as a custom post type. When vacancies are available, ie a post type of "vacancy" is published, we want to display a ribbon in the top corner, directing people to the careers page.
To check for published posts obviously I could get_posts for that post type, but that seems a bit inefficient as I'll be battering the database on every page load to check. Is there any more DB efficient way of doing this, kind of like a have_posts( 'post_type=vacancy' ) ? | I wouldn't worry about doing a second query (e.g. using `get_posts()`). If you want to check if a post type has any published posts - you're going to have to query the database. But reading a database is really quick - any noticable delay in your page load is more likely to come from extra HTTP requests (images, javascript, css etc).
In any case, if you are worried about speed, you presumably have some sort cache plug-in enabled, in which case, most of your visitors won't notice a difference. In fact, you entire page will only be generated if the cache has expired. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, database"
} |
Related posts by searching post tags of single post as terms
I want to have a related loop of posts on single post pages and to do this I want to search the tags of the post. My first question is can you use the search in query posts for multiple terms and what is correct way to do this. This is what I've been trying that is not working.
global $post;
$tags = wp_get_post_tags($post->ID);
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args = array('cat' => '8', 'posts_per_page' => 8, 's' => $tag_ids,);
$my_search = new WP_Query($args);
if ($my_search->have_posts()) : while ($my_search->have_posts()) : $my_search- >the_post(); ?> | If you are inside the loop, on the single page, than you have all tags and can search for releated posts with the same tags. You find many solutions via google; an example:
//for use in the loop, list 5 post titles related to first tag on current post
$tags = wp_get_post_tags( get_the_ID() );
if ( $tags ) {
echo 'Related Posts';
$first_tag = $tags[0]->term_id;
$args = array(
'tag__in' => array( $first_tag ),
'post__not_in' => array( get_the_ID() ),
'showposts' => 5,
'caller_get_posts' => 1
);
$my_query = new WP_Query( $args );
if ( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
<?php
endwhile;
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, loop, search, tags"
} |
Add tags to pages
I'd like to be able to add tags to my pages just like I can with posts.
What would I need to do to enable the tag editor/entry for the page editor? | You can use the `register_taxonomy_for_object_type` function.
The following adds the default 'tag' and 'category' taxonomies to pages:
register_taxonomy_for_object_type('post_tag', 'page');
register_taxonomy_for_object_type('category', 'page'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "theme development, tags"
} |
Custom GD Star Ratings Stars
I have some custom stars that I would like to use for GD Star Ratings.. how do I load my custom star image? | The plugin supports this feature by default. Searching for "gd star ratings custom images" finds lots of information including this guide on the official site. Apparently the GD Stars User Guide contains full instructions on creating new image sets as well as some pre-built ones you can use. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -3,
"tags": "plugins, theme development, plugin gd star rating"
} |
Plugin for users to create their own ads like Google Adsence
Does any one know of a plugin to allow users to create ads on a format like Google Adsense (title, some text and a link). ?
Something that may require some customization may do the job.
Thanks in advance. | When you say "Users" do you mean registered users or visitor to yoour site? For the first one I use wordpress-multiple-user-ad-management, with some customized code since there a few options that I don't use. Also the text links options that the plugin have only allow users to create a title and the link for the ads (no other text or description for the ads).
The plugin offers the option for text ads, image ads(but images are hosted externally, user place the source link for the image) and a Paypal option for users to place a Donate button | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, customization, ads"
} |
Guidelines / restrictions about advertising /donate begging unside wordpress plugins or themes
I remember to have read about this, but I can't find it anymore.
Basically we are not allowed to advertise without the users consent inside plugin, its a good rule I think. I just want to see the official text to quote it. | <
You are probably thinking about #5 and #10 on that page. There are other possibly relevant ones as well, like #7 about phoning home.
Basically, you cannot broadcast your plugin on the front side of the website without the ability to turn it off (user consent). Nor can your plugin be "trialware". Its OK to advertise, but not OK to be annoying or forceful about it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, themes, ads"
} |
Add Class to Specific Paragraph of the_content()
Let's say I want to give the first paragraph bold text by adding a body class to the first paragraph. Is there a way to filter the output of
the_content();
or any other paragraph? First paragraph? Last paragraph?
I know I can do this using Javascript or CSS (:firstchild), but is there a native WordPress way?
Thanks.
J | The following bit of code adds a class to the first paragraph output by `the_content`:
function first_paragraph($content){
return preg_replace('/<p([^>]+)?>/', '<p$1 class="intro">', $content, 1);
}
add_filter('the_content', 'first_paragraph');
Add the above to your theme's functions.php file.
Then in your CSS add something like:
p.intro { font-weight:bold; }
I can't claim credit for this solution (see this thread in the WP forums) but I tested it and it worked great for me in WordPress 3.3.2. You should be able to modify it as needed to target whichever paragraph your heart desires. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "filters, the content"
} |
uploaded images not going to /uploads folder
having a huge problem with a site. i updated the theme to use post thumbnails (that's how old it is) and then when trying to upload an image to use as featured thumbnail: the images process/crunch but then the URLs result in 404s.
!enter image description here
there isn't anything abnormal in the site's .htaccess. there actually wasn't a wp-content/uploads directory so i made one and the chmod permissions are 0755, so that shouldn't be the issue. i reset the media settings folder to be the default but no images are ending up in that folder.
edit: changing the uploads folder to 0777 permissions seems to resolve this. is it safe to leave the permissions this way? | If I remember it right, this happened to me once. I deleted my `/uploads` directory (to delete all the images) and went back to posting thinking that WordPress will automatically create an `/uploads` directory and any necessary sub-directories for me.
And yes, that's how it works. But here's the catch -- WordPress doesn't set proper permissions for the `/uploads` directory and the directories within, this time. The new chmod permissions were like `0700`.
**SOLUTION:** What I did was, I set back the permissions for `/uploads` directory at `0755`, and selected the option in my FTP client to set the permission recursively to all sub-directories in the `/uploads` directory.
As in your case, I would also check the permissions on `/wp-content` directory.
!chmod | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "uploads"
} |
Compare the_excerpt() to the_content()
Is there a way to compare the_excerpt() to the_content() to know if the_excerpt() is actually showing the entire post content? for instance, if a post were particularly short.
ultimately i'd like to have a "Read more" link at the end of excerpts. but i want it to say 1 thing for posts and another for posts of the video format (ie... 'watch the video' instead of 'read the rest'). but at the same time i don't want to manually tack this on after the excerpt, but i have plenty of posts that are short enough they don't need a 'read more' link, since the_excerpt displays the full post.
but adding the permalink to the excerpt_more filter isn't quite right since it won't add a link to the video posts that have no other content.
so i'm stuck between the two. i hope that made sense. if it didn't it's late and i will try to re-explain in the morning. | What you're trying to do with the video is exactly what Post Formats were created to handle.
Add this to functions:
add_theme_support( 'post-formats', array( 'video' ) );
And then this to handle your Read More link:
if( !has_post_format( 'video' ) ) {
echo '<a href="' . get_permalink() . '">Read More…</a>';
} else {
echo '<a href="' . get_permalink() . '">Watch the Video…</a>';
} | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 9,
"tags": "excerpt"
} |
Secure Validation of wp_editor in Theme Options
So I just found this great WPSE thread about security for themes/plugins. It answered most of my questions but it was created before the new `wp_editor()` function was built.
I have two TinyMCE editors on my Theme Options and I'm wondering whether I need to use `esc_html()` or `esc_textarea()` in a validation callback before saving the theme option. It seems to me that TinyMCE takes care of a lot of that stuff (as well as the Settings API security that's taken care of), but there's still not a lot of documentation out there about `wp_editor()`.
Any resources and answers appreciated. | `esc_html()` and `esc_textarea()` are, appropriate to their names, escaping functions and really meant for display rather than sanitizing or validating. I would use `wp_kses()` or `wp_kses_post()` (which is just `wp_kses()` with the global `$allowedposttags`) to sanitize input from a `wp_editor()` field before saving. | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 3,
"tags": "tinymce, security, theme options, wp editor"
} |
Will it break my site if I delete all transient records in wp_options table?
My site currently has an outrageous 500k+ transient records in the wp_options table. This causes the table to be crashed frequently and so be my site.
I thought transient records will all expired after some time. I'm not sure which plugins are responsible and what went wrong yet. However, I don't want my site to crash frequently like this. The number of records in `wp_options` table has grossly increased to 200k+ a few weeks ago and now 500k+.
Should I only delete the `%transient_timeout%` records - 200k+ of them at the moment?
Any help would be greatly appreciated.
**Updates on 16th July 2012**
I actually took risk (I backed up my site first) by deleting all the transient records and my site's database hasnt' crashed ever since :)
Thanks again, everyone! | This is a fairly definitive set of responses about transients
WPSE: Are transients garbage collected? | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 17,
"tags": "database, mysql, options, transient"
} |
Does "Custom Post Type" can have page hierarhy option?
I want create "Custom Post Type" that will have next structure:
Post (hierarhy level)-(some-post-id)
> Post 1-1 =>
>
>
> Post 2-2
> Post 2-3
> Post 2-4 =>
> Post 3-5
> Post 3-6
> Post 3-7
> Post 2-8
> Post 2-9
> Post 2-10
>
I need something like "Page attributes":
< | You can set a post type to hierarchical when you register it with `register_post_type`. Simply set the 'hierarchical' argument to _true_.
$args = array(
'public' => true,
'publicly_queryable' => true,
'has_archive' => true,
'rewrite' => true,
...
'hierarchical' => true,
...
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments','page-attributes' )
);
register_post_type('my-cpt',$args); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, posts, pages, hierarchical"
} |
Need a Plugin to create a registration form for my website?
I need a custom registration page from for my site. I want to take some details from my regular visitor and then finally want these details in a csv or excel file. Is there is a plugin which can do this for me just like we have Contact Form 7 for Contact Page??? This question may seems common but please consider me as i am very new to wordpress. | If I understand you correclty, you are essentially asking two questions.
For one, you are looking for a solution for a customized registration- (login- / profile-) page. Also, you want to export data to .csv or .xls
As for the first issue, I'd recommend taking a look at Jeff Farthing's excellent Theme-My-Login plugin.
As for the second, I know of one discontinued plugin that might be of help. I have no experience with it though. Check out ALO Export XLS. A dirty solution would be to export directly from the DB via phpMyAdmin or the like. You might have to write your own plugin for this issue. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "plugins, plugin recommendation, user registration"
} |
What filters are applied to the_content function?
How does WordPress convert raw data from the database to a readable format in the_content function?
I've noticed that it applies the_content filter, but what does the_content filter do? | the default filters are set in /wp-includes/default-filters.php;
for 'the_content' this is from line 135:
add_filter( 'the_content', 'wptexturize' );
add_filter( 'the_content', 'convert_smilies' );
add_filter( 'the_content', 'convert_chars' );
add_filter( 'the_content', 'wpautop' );
add_filter( 'the_content', 'shortcode_unautop' );
add_filter( 'the_content', 'prepend_attachment' );
to trace the individual functions, you could try and use < then follow the links...
# Edit
Missed one (`wp-includes/default-filters.php`, line 102):
// Format WordPress
foreach ( array( 'the_content', 'the_title' ) as $filter )
add_filter( $filter, 'capital_P_dangit', 11 ); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 7,
"tags": "theme development, filters"
} |
Optimizing Jetpack for Wordpress
Yslow reports following issues with Jetpack:
1) Compress < using gzip
2) Configure etags for <
Modified the format so that it is easier to understand. How can I take action against these items. I am already using latest version of W3 Total cache plugin.
Pls advise. | You can't "optimize" Jetpack. Look at the URL; it's served from wordpress.com. You get what they offer from their servers. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "cache, performance, plugin jetpack"
} |
Filter For Featured Image
Is there a filter for when a Featured Image is set/unset or changed.
I need to delete transient data when the above occurs. | The post featured image ID is stored as post metadata, so I would recommend hooking into the `update_post_meta` or `update_post_metadata` hooks, and then query the post meta for `'_thumbnail_id'` being set.
See this related answer from Jan Fabry. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "post thumbnails"
} |
New rewrite rules for custom taxonomy and reuse default
I have a taxonomy `location`. All terms except one are to be treated differently. That's why I have two php files
1. taxonomy-location.php
2. taxonomy-location-national.php
Now, I want to make the URLs SEO friendly.
If URL = example.com/localdeals/national, I want to redirect it to taxonomy-location-national.php
If URL = example.com/localdeals/%any-other-term%, I want to redirect it to taxonomy-location.php
Basically I do not want to write the name of above files in .htaccess. I want to, somehow, reuse the default WordPress rules.
i.e. WordPress already directs example.com/?location=national and example.com/?location=boston correctly. I want to add new rules on top of these and want to reuse them.
Is it possible? | Note that the url-rewriting doesn't directly determine the template used. A pretty url is interpreted as a query and then that query determines what template is used based on the template hierarchy.
So only need _one_ rule:
example.com/localdeals/myterm => example.com/?location=myterm
WordPress will look for the template `taxonomy-location-myterm.php` and use that (if it exists) or otherwise fallback to `taxonomy-location.php`
To add the above rule, when you register your taxonomy:
register_taxonomy('location','post',array(
'hierarchical' => false,
...
'query_var' => true,
'rewrite' => array( 'slug' => 'localdeals' ),
...
));
(you will need to flush these rules _once_ after changing these - if this is for a plug-in/theme, only flush on activation/de-activation). Otherwise, just visit Settings > Permlinks page, and they'll be flushed :). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, rewrite rules"
} |
Get post content from outside the loop
Is there a way to get the content from another outside the loop? The ID is 302 and I need to display the content of that on another page. | ### You can use `get_page()` to return the `$post` object of a static page:
$page_id = 302;
$page_object = get_page( $page_id );
echo $page_object->post_content;
### Edit
Similarly, you can use `get_post()` to return the `$post` object of a post:
$post_id = 302;
$post_object = get_post( $post_id );
echo $post_object->post_content; | stackexchange-wordpress | {
"answer_score": 45,
"question_score": 26,
"tags": "loop, post content"
} |
Creating custom function in wordpress to return data from database
I have created a custom image uploader for my wordpress admin panel and need to retrieve the data from the wp_options table. I have wrritne the below function:
//function to get all slider images
function getSliderImages(){
global $wpdb, $theme_shortname;
$query = "SELECT * FROM $wpdb->options AS o1
WHERE o1.option_name LIKE '%".$theme_shortname."_header_image%'";
$imgs = $wpdb->get_results($query);
$images = array();
//loop through images and remove unusable results
foreach($imgs as $i){
$id = substr($i['option_name'],0,-1);
if(is_numeric($id)){
$images[] = $i['option_value'];
}
}
return($images);
}
How do I access the returned array in header.php on the front end? this function is currently in themes/themename/functions.php | In your header.php
$images = getSliderImages();
foreach ( $images as $img ) {
echo '<img src="' .$img. '" />';
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "theme development, functions"
} |
How to add a list of all galleries to my sidebar?
I'm using Wordpress 3.3.1 and trying to figure out how I can modify my sidebar to include a list of all the galleries. I see wp_get_posts and the like...but nothing for galleries? | Search the posts by content for the string `'[gallery'`. You get an array of posts which you can list then in a widget or in plain PHP code. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "gallery, sidebar"
} |
empty dashboard for custom role
I setup a custom post type `employee` with an `agent` role that mimics an `author` role for this particular post type, and so far everything is working fine, except that when I created a `test` user and granted it an `agent` role, the dashboard that `test` sees is empty as in:
!enter image description here
I was hoping it would be something like what an `author` user would see, like:
!enter image description here
Could anyone please help me on this? Thanks in advance. | This support forum thread has both an explanation and a code snippet that you might be able to work up into a solution.
The "Right Now" widget is tied to the `edit_posts` capability. I don't know about the incoming links widget or quick post widget, but I'd guess it's the same issue of either requiring `edit_posts` or another similar post-specific capability. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, widgets, dashboard, user roles"
} |
What are these undocumented arguments for register_taxonomy?
The Wordpress codex has an example of the `register_taxonomy()` function at < that shows arguments that are not documented in <
In particular `args['sort']` and `args['args'][order_by]`.
What's the story with these? | I suspect the Taxonomies Codex entry is simply out of date.
Per source, there are no `'sort'` or `'orderby'` args for `register_taxonomy()`.
Given the purpose of the `register_taxonomy()` function, it doesn't even really make _sense_ for this function to include sort/orderby parameters. Such parameters would be relevant to _listing_ taxonomy terms, not to _registering_ the taxonomy itself. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "taxonomy, codex, register taxonomy"
} |
Links do not open from click, only in new tab
I'm fairly new to Wordpress, but I'm encountering a strange issue. I have a menu set up, and I've put links to some of my pages inside of it. But, when I try to click on any of the menu items, nothing happens. I can see the URL in the bottom left of my screen when I hover over the links, but when I click on them, I'm not redirected. The weird thing is that, when I open the links in a new tab (using either middle-mouse click or right click -> open in new tab), all of the links work. Does anyone have any idea what this might be? I'm completely lost. | I would guess that some javascript is running on that page (in your theme) and preventing the default action of click event.
Disable all plugins you have and then theme to narrow down the cause. If disabling a plugin or reverting the theme fixes it, then you have found your culprit.
Also look for javascript errors in console. `Browser > Right click > Inspect Element > Console tab` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "menus, redirect, links, navigation"
} |
Get post attachment images dimension and use in embed code
I am trying to make things work like where any post attachment image will generate embed code automatically.
Example: If I upload and add two images 1. 250x150 2. 600 x 160 and insert into post. Now that image information I want to auto put into embed code like below.
<div>
<a href="link url" title="title text" target="_blank"><img src="$image_url" width="$image_width" height="$image_height" alt="$image_name" /></a>
</div>
where $variable is the data of the attached image/s.
So above code our team member can use the embed code to display image. | WordPress has a predefined function, `wp_get_attachment_image_src` that returns the following information as an array:
[0] => url
[1] => width
[2] => height
But, the function requires that you know the attachment's ID, not the post's ID. In order to get that, you'll need to use `get_post_thumbnail_id`.
Here's the two functions together in action:
$image_id = get_post_thumbnail_id($post->ID);
$image = wp_get_attachment_image_src($image_id);
After that, you can easily do what you're talking about in your question.
<img src="$image[0]" width="$image[1]" height="$image[2]" />
If you want more information about the wp_get_attachment_image_src, you can read more about it here: < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "attachments, embed, images"
} |
Exclude posts with custom taxonomy
I need to show a list of custom posts but exclude any that have the custom taxonomy 51, is it possible to do it with the loop below?
$pages = get_children(array('orderby' => 'post_date', 'post_type' => 'news', 'numberposts' => "3"));
$counter = 1;
foreach($pages as $post) {
setup_postdata($post);
$fields = get_fields();
}
UPDATE:
The custom taxonomy is called opportunity and has the term id 51 in the custom taxonomy. If this helps - this is how I'm grabbing all the custom post's with the custom taxonomy opportunity:
$pages = get_children(array(
'orderby' => 'post_date',
'post_type' => 'news',
'post_status' => 'future',
'numberposts' => "3",
'tax_query' => array(
array(
'taxonomy' => 'news',
'field' => 'id',
'terms' => 51,
),
),)); | Make sure to reread the `tax_query` documentation. If you change it to this, I think it should work:
'tax_query' => array(
array(
'taxonomy' => 'news',
'field' => 'id',
'terms' => 51,
operator => 'NOT IN'
)
)
Depending on your setup, you may also want to specify the `include_children` argument. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, custom taxonomy"
} |
Filtering out the #more anchor link that gets produced by <!--more-->
Back in my naive days of theming, I had to make it so the link inserted by `<!--more-->` wouldn't dump the viewer at the anchor it produces.
I made a dinky plugin that consisted of:
function No_More_Link($buffer) {
$inHTML[0] = '/#more-\d+/';
$outHTML[0] = '';
return preg_replace($inHTML, $outHTML, $buffer);
}
ob_start("No_More_Link");
Years later, I thought I could do much better, by using a filter in the theme's `functions.php` file:
function no_more_link ( $input ) {
return preg_replace( '/#more-\d+/', '', $input );
}
add_filter( 'get_permalink', 'no_more_link' );
This doesn't work. I've tried bumping up the priority to ridiculous levels.
Am I applying the filter to the wrong thing? What am I missing here? | You can filter `the_content_more_link` hook and remove `#more-POST_ID` from the link:
function wpse_51806_strip_more_link( $more_link ) {
global $id;
return str_replace( "#more-$id", '', $more_link );
}
add_filter( 'the_content_more_link', 'wpse_51806_strip_more_link' );
It has even been made into a plugin, if you're more comfortable with plugins then code snippets. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, filters"
} |
How Can I Centralize Content Usage and Approval in a WordPress Multi-Site installation
I am working with a non-profit client that runs several charities under one umbrella. A good metaphor would be to think of the United Way (but it's not the United Way).
Can a WordPress multi-site installation do the following:
Share content between sites. E.g., if site A has a section called "Advocacy", can that same content also be shown in site B? This would need to include text, photos, etc.
How centralized can administration be made? For example, can draft posts from all websites be approved in one location?
I'm sure there are other things I need to ask, but I'm still in the investigation phase. | I believe that ThreeWP Broadcast is the plugin you should use. I've been using this plugin in WPMS to share (and link) content between blogs, and it works well.
Basically, this plugin allows you to:
* duplicate a post from a blog to other blogs in the network
* options to create a link to those blogs, which means when the original post is changed, other copies are changed, too
* options to copy taxonomies, custom fields
Finally, the codebase of this plugin is good, so in case you want to change something, you can go through the code, change it like you want (this is what I'm doing). | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 7,
"tags": "multisite, admin"
} |
Plugin that will output submitted form data for user?
I have a standard HTML form that the visitor will fill out. It consists of mostly checkboxes. What I would like, is after the form is submitted, a page is then presented to the user showing what they checked. For example, if the visitor checked off Checkbox A, B, and D (but not C), then upon submission they would see the following:
You submitted:
Checkbox Value A
Checkbox Value B
Checkbox Value D
Obviously I can do this with just PHP, but my client would like to be able to modify the form options.
Is there a plugin or user friendly way that this can be created? | Gravity Forms is by far the best form plugin available for WordPress and it will allow you to easily do what you are looking for.
<
Here is an example of how to do it:
Set the confirmation to show which checkboxes were checked using the merge tags: !Set the confirmation to show which checkboxes were checked using the merge tags !enter image description here
!enter image description here
This form can be placed anywhere in a page and the confirmation function loads right after the form submittal. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, forms"
} |
Can't edit custom post type
I'm using the following code to create two custom post types:
Pastebin Link
The Spotlight custom post type is giving me the edit/permalink to edit the post. However, the cooking video isn't. I've just copied the code from the Spotlights, changed the pertinent info for Cooking Videos so I don't get why it isn't working. | As I told SickHippie in the comment, this was a matter of the naming convention while registering the custom post type in the functions.php file. I used camel-case and the DB didn't like that. Once it was changed to all lower-case, it worked fine. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, functions"
} |
How to view all posts (on site, not admin) that are uncategorized?
I had a horrible problem a long time ago that had me end up importing a backup of most of my posts.
I'm now using WordPress 3.3.2 and I would like to view all of the uncategorized posts from the site view, not in the admin.
I have attempted to use
<
<
Both with capitalized and not.
But those come up as bad pages. Is there any way to view just these posts? | They're not 'bad pages' (404), they're empty archives. Make sure you have published posts in the 'uncategorized' category, since I don't actually see any in the sidebar list. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, categories, archives"
} |
Google Map is not working on the second tab of Tab Plugins
I am using a postTabs plugin and Comprehensive Google Map Plugin, my problem was when I have my Google map on the second tab, the map is not loading as expected. But if I move it on the 1st tab it works really great.. Is there any way to make the map work on the second tab? Actually, whichever Tab plugin I use the map is not loading properly on the second tab.. Any suggestion is appreciated. Thanks :) | i was tested with Google Maps Embed plugin with PostTabs plugin. You can Insert the map in editor also.This is really works.
Please Check the screenshot for both tabs. :)
!Tab 1 here !Tab 2 here Admin Page: !Admin page | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "google maps, tabs"
} |
contextual_help, change the "Help" tab label
Is there any way to change the "Help" tabs label? I speak about the top right tab to toggle the contextual help.
I'm looking to change "Help" label by "Documentation".
I work on WordPress 3.3 and 3.4 beta
Thanks for your advices | Look at the source, there is no filter to alter the 'Help'. But it does translate the text so you can hook onto the `gettext` filter. Not the nicest of solutions (an alternative would be to use javascript) :
add_filter( 'gettext', 'wpse51861_change_help_text', 10, 2 );
function wpse51861_change_help_text( $translation, $text ) {
if ( $text == 'Help' )
return __('Documentation','my-plug-text-domain');
return $translation;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "contextual help"
} |
Removing widget without using unregister_widget
I want to remove some plugin widget showing from wp-admin/widgets.php but i dont want to use unregister_widget because i am using this widget automatically from php files..
Basically i dont want clients see this widget as option in wp-admin/widgets.php but i want to use this widget from php files. I thought css display:none as solution but widget div IDs are not static seems
Any idea? | Check the following answer, adapt the code and it will do what you want.
<
Use Firebug for Firefox, or Chrome/Safari inspector to discover the widget ID.
Note the use of CSS3 attribute selector, that allows targeting an element using a partial ID or Class.
For example, this will hide the Calendar widget:
`div.widget[id*=_calendar-] { display:none; }` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets"
} |
Automatic excerpts
How to display excerpts in the homepage instead of full post automatically, without the need to insert `<!--more-->` in every post ?
I tried this plugin < which or doesn't work or I can't use it.
Here's how I configure it <
This is my website.
**I solved the problem using Michael's answer, which made my plugin work.** < | general:
locate the template for the home page - often index.php - if not see <
find `the_content()` (possibly with some parameters in the brackets) and change that to `the_excerpt()` \- <
specific for Twenty Eleven:
index.php points to the template part content.php; in content.php edit this line:
`<?php if ( is_search() ) : // Only display Excerpts for Search ?>`
change it to:
`<?php if ( is_search() || is_home() ) : // Only display Excerpts for Search and posts page ?>`
< | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "excerpt"
} |
How to programatically set the post title of a CPT on wp-admin
I've been playing with custom post types & custom fields, using a combination of the `types` plugin and the `advanced custom fields` plugin, also having done the same manually.
Occasionally I want to create a CPT where a `title` would be inappropriate - for example, an FAQ where I want two fields labelled `Question` and `Answer`. This does work without a title, however they all get saved as `(No Title)`.
What I'd like to do is either set the `title` to the value of the `Question` custom field, or somehow define my own `title` field that I can label as I like.
Does anyone have any pointers on how to acheive this? | You can use the `enter_title_here` filter:
add_filter('enter_title_here','wpse51871_alter_title_label',10,2);
function wpse51871_alter_title_label($label, $post){
if( 'question' == get_post_type($post) )
$label = __('enter question here', 'my-plugin-text-domain');
return $label;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, custom field, wp admin"
} |
Hook for feed creation?
I'm looking to create a function which would be called when the blog's `/feed/?args...` URL is requested. I've been looking at `the_content_feed`, would that be correct?
Also, how would I get the `args` in the URL into my function as an array? | It depends what you want to do as for when you want to hook into the process. `the_content_feed` is fired for each item in your feed, so this probably isn't the one you are after.
You could use `pre_get_posts` which fires just before WordPress queries the database:
add_action('pre_get_posts', 'catch_the_feed');
function catch_the_feed($query){
if($query->is_main_query() && $query->is_feed()){
//It's a feed!
$variables = $query->query_vars;
}
}
_untested_ but `$variables` should be an array of registered query varibles and their value (usually populated from what was recieved in the url).
...or you could use `template_redirect` which is when WordPress has retrieved the posts and is ready to display them (or redirect the user to a feed template) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "urls, feed"
} |
How reduce wordpress login session timeout time?
I want to logout user autometically when user is idle for more than 10 minutes.That mean suppose user is logged in to a site and user didn't browse any pages for more than 10 mins.when he browse any page after 10mins, it will logout user and redirect to login page.Any Solution? Advance Thanks. | You just need to add your filter hook like this:
function myplugin_cookie_expiration( $expiration, $user_id, $remember ) {
return $remember ? $expiration : 600;
}
add_filter( 'auth_cookie_expiration', 'myplugin_cookie_expiration', 99, 3 );
You can add it to your theme’s functions.php file. | stackexchange-wordpress | {
"answer_score": 23,
"question_score": 12,
"tags": "login, logout, session"
} |
Genesis menu position change
Sorry for silly question, I'm pretty new in WordPress and Genesis. I want to move Genesis menu above header. How can I do that? | Just add the snippets in Genesis Theme function, in functions.php
remove_action('genesis_after_header','genesis_do_nav');
add_action('genesis_before_header','genesis_do_nav'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "genesis theme framework"
} |
Add comments from the admin panel?
I'm using WordPress as an Authoring tool. Hence I do not use the front end.
Now I wanna add the functionality making internal comments. As it is now, you are only allowed to read comments from the Edit Post page, not to write them.
Got any hints or good ideas on how to make this possible? | This will be possible in the upcoming version WordPress 3.4. Try the Beta or just wait.
Here is a screen shot (incomplete translation to German):
!enter image description here | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "comments, post editor"
} |
Using WP Multisite for multi language site? A good option?
I´m going to develop a site for a client which requires multiple languages. I have no experience with this from beforehand so I´m researching what might be the best way to do this.
The webpage will be in swedish, english and norwegian. I must have the ability to have separate content in each language, like separate news posts for each language, or separate products etc.
Would using WP multisite be a good way to achieve this? I´m thinking I can do like this: Start a network with three sites: www.domain.se /en and /no. Develop for the first language version (swedish) and fill it with the correct content. Export the content, and import it from the other installations. Then replace the contents with the same content in the other languages.
Would this be a good way to achieve what I want, or would you suggest some other way?
Regards | There is the plugin Multilingual Press for exact this setup: It helps to synchronize multiple sub sites in a multi-site installation.
Running an import and an export each time you publish or update a page is not necessary. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "multisite, multi language"
} |
Displaying Custom Taxonomy List Posts By Slug?
Is it possible to list the posts from a custom taxonomy by slug along?
This link kind of does it but i want to target the slugs rather than just the whole taxonomy itself
<
So i have Custom Taxonomy 'Books' within that i have Book 1 and Book 2.
I want to list all the posts attached to Book 1 and then separately all the posts attached to Book 2 ideally.
Possible?
Thanks for any help. | As long as you have registered your custom taxonomy to with `'rewrite' => true`, then WordPress should automatically build taxonomy archives for you at yousite.com/{taxonomy base}/{term slug}.
There are a lot of caveats and problems that can arise, but for simple setups, this works like a charm. To find the right URL, go to (I'm guessing a little here) Posts > Books and then click "View" beneath the "Book 1" taxonomy. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, categories"
} |
How do you remove plugin edit option?
I would like to remove the edit option for all plugins on a wordpress site. Is there a hook/filter for doing this? It would be preferred to do it from the theme's functions file, rather than try to disable it within each plugin. Ideally, it could be removed for users without admin privileges, but that is a secondary concern.
!enter image description here | Add the following line to your WordPress installs _wp-config.php_
define('DISALLOW_FILE_EDIT',true); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "plugins, php, theme development, editor"
} |
Which file do I need to edit the All Posts page in the admin area?
I've never edited admin files before, but I need to edit the table used to list my posts in the admin area (on the All Posts page). Can someone please point me to the right file to edit? I've looked in the wp-admin directory but I haven't found a file with this table in it, so far. | You do not need to and absolutely should not be editing a core WordPress file to achieve this. There are almost certainly hooks for whatever it is you are looking to accomplish. You can take a look at questions regarding custom columns (such as Add column to pages table) or, if you'll excuse my linking to something from myself, I have some slides regarding that same topic: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, wp admin"
} |
Custom Portfolio Page
I've a page (at /portfolio) & nav item created called Portfolio. What I'd like is for this page to either contain all the portfolio category's post in chronologically order or else all of the portfolio posts organized by portfolio subcategories (and then chronologically within).
What's the easiest way to achieve this? | You say you have a page for your portfolio, then go on to say you want posts displayed; confusing.
Assume you have a category for posting items into named portfolio. New portfolio items will be posted in the portfolio category. You can take your categories.php page, copy and re-name it categories-portfolio.php, then customize it as needed for your desired display of post content for posts in the portfolio category. WP will pick it up for the url /category/portfolio/ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, pages, customization"
} |
How do I find if a page has a template?
So I'm doing a query like this:
$the_query = new WP_Query( array( 'meta_key' => 'homepage', 'meta_value' => 'yes',
'post_type' => 'page', 'orderby' => 'modified', 'posts_per_page' => 1 ) );
To get a single page with a specific key value, how do I get the page template from a query like this, if it has one?
Thank you! | This should do the trick for you. This shows what template file is stored in `post_meta`, if one has been selected in the admin panel:
`$template_name = get_post_meta( $the_query->post->ID, '_wp_page_template', true );`
If you want to see if the page is the homepage, use `is_home()` or `is_front_page()`.
If you want to see what files are generating the page, use this in your functions.php:
// Returns a list of files used to generate the page. Best called in footer.php before </body>
function _dump_files()
{
# @todo Aufrufende Datei kann im Array manchmal fehlen!
add_action( 'all', create_function( '', "echo '<pre>'; print_r( get_included_files() ); echo '</pre>'; return;" ) );
}
I use it in `footer.php` like this:
if (is_user_logged_in()) {
_dump_files() ;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "query, page template, meta query"
} |
Categories or Custom Post Type to Organize Content
Let's say I'm starting a martial arts website and I want to categorize content into themes:
1. philosophy
2. fitness
3. training
4. techniques
5. diet
Etc.
I keep going back and forth between using custom loops to display the content or making each a custom post type.
Is there advantages to either? And is it worth the trouble of creating the custom post types?
I know this is sort of a philosophical question, but was wondering if there are any solid reasons I can't think of to go either way.
Thanks so much. | Try to stay as close as possible to the built-in functions and behavior. I would just use tags or categories in your case. You can make both more special and rename them to _type_ (for tutorials, link lists, rants etc.) and _topic_ :
!enter image description here
Questions to ask before you decide about implementation:
* What kind of relationship will I need?
* 1:1 or 1:n (one to many) – post meta data
* n:m (many to many) – taxonomy
* maybe both: custom post type
* How should my permalinks look like?
* Will I need a custom edit screen?
* Will I need a separate search function?
The more extra functionality you add the harder may it be for your visitors to predict the location of your content. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, categories"
} |
How to get data from an array using get_user_meta()
I have created a custom user profile field
<?php $basics = get_the_author_meta( 'fbasics', $user->ID ); ?>
<ul>
<li><input value="lesson1" name="fbasics[]" <?php if (is_array($basics)) { if (in_array("lesson1", $basics)) { ?>checked="checked"<?php } }?> type="checkbox" /> <?php _e('Lesson 1', 'gprofile'); ?></li>
<li><input value="lesson2" name="fbasics[]" <?php if (is_array($basics)) { if (in_array("lesson2", $basics)) { ?>checked="checked"<?php } }?> type="checkbox" /> <?php _e('Lesson 2', 'gprofile'); ?></li>
</ul>
I now need to use the data on the front end of wordpress to display information. I think I need to use the `get_user_meta()` function but I do not understand how to use is to get the value of an array.
How to get data from an array using `get_user_meta()`? | The function is `<?php get_user_meta($user_id, $key, $single); ?>`
The `$single` is a _boolean_ that returns a single value for true or an array if set to false, in your case you would set it to false.
$user_output = get_user_meta($user_id, 'fbasics', false);
var_dump($user_output); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "functions, user meta"
} |
qTranslate get content by language
How do you get the content by id and by specific language?
I need to display two specific language content in a page, regardless of the session's language. So far, this is my progress: this works fine for getting the content by id of the active language:
<?php $id=47; $post = get_page($id); $content = apply_filters('the_content', $post->post_content); echo $content; ?>
How to apply a specific language to the filter?
Thanks for the help. Sziro | You must use the qTranslate native functions to do your job. Use `qtrans_use`, that is the function that do all the job in qTranslate. It's defined in qtranslate_core.php, line 747
function qtrans_use($lang, $text, $show_available=false)
Use it on the raw content of the post!
Try this code:
<?php
$id=47; $post = get_page($id);
$content = qtrans_use('en', $post->post_content,false);
echo $content;
?>
In this example, it will return the _English_ version of your text! Substitute it with the desired language identifier to translate into another language! | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 9,
"tags": "multi language, plugin qtranslate"
} |
How to show total view count across all posts for an author
I'm using wp-postviews to track views for posts by authors on my site. It stores the view count in the post meta field `$views`. I'd want to show on their profile a total count of views for all their posts combined. How to do that? | A list of posts in the format:
> ### Post views by Author: Author Name
>
> * Post Title (15)
> * Post Title (67)
> * Post Title (4)
>
>
> * * *
>
> Total Number of views: **86**
$author_id = ''; // do stuff to get user ID
$author_posts = get_posts( array(
'author' => $author_id
) );
$counter = 0; // needed to collect the total sum of views
echo '<h3>Post views by Author:</h3><ul>'; // do stuff to get author name
foreach ( $author_posts as $post )
{
$views = absint( get_post_meta( $post->ID, 'views', true ) );
$counter += $views;
echo "<li>{$post->post_title} ({$views})</li>";
}
echo "</ul><hr /><p>Total Number of views: <strong>{$counter}</strong></p>"; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "posts, author, views"
} |
How to change the post form from plugin?
I am starting making some wordpress plugin, so I am a beginer. I just wonder how can I change the post form of the pages. For example for adding some other input (of type file or text)? I am trying to use
add_filter('comments_template', 'add_new_fields');
but nothings happens. | If you want to change/add something to post form, you have to deal with meta boxes. I would recommend you to read through these articles:
* Reusable Custom Meta Boxes Part 1: Intro and Basic Fields
* Reusable Custom Meta Boxes Part 2: Advanced Fields
* Reusable Custom Meta Boxes Part 3: Extra Fields
* Reusable Custom Meta Boxes Part 4: Using the Data | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, posts, post editor"
} |
No option "I would like my site to be private, visible only to users I choose" in Privacy Settings
I am running WordPress 3.3.2 self-hosted. I used to see the option "I would like my site to be private, visible only to users I choose" under Privacy Settings but I no longer see this option. Instead, now I only see the options to make the blog visible or not visible to search engines, but no way to make it private.
I have already tried deactivating all plugins and setting to a basic theme (Twenty Eleven 1.3) to see if my plugins or theme were causing a problem, but still do not see the old option.
Any tips much appreciated! | It sounds like you were on WordPress.com previously, which has options that are not built in to the core of WordPress. There are various plugins out there to accomplish a similar end result, such as Restricted Site Access. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "security, options, privacy"
} |
Disable the post save process completely
I need a way to disable the save process completely using an `action/filter`. Something that works (for e.g.:) in the `query`, `posts_clauses` or `wp_insert_post/save_post/update_post` hooks.
So far I only tried to `return '';`, which gives me tons of errors for missing values for post object parts in the admin UI.
This should happen "silently", so no errors get thrown when `php_error/WP_DEBUG` and such are set to `TRUE/On`.
Btw: I'm _not_ asking for how to disable the autosave feature. | function disable_save( $maybe_empty, $postarr ) {
$maybe_empty = true;
return $maybe_empty;
}
add_filter( 'wp_insert_post_empty_content', 'disable_save', 999999, 2 );
Because `wp_insert_post_empty_content` is set to true, WordPress thinks there is no title and no content and stops updating the post.
**EDIT:** An even shorter variant would be:
add_filter( 'wp_insert_post_empty_content', '__return_true', PHP_INT_MAX -1, 2 ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "admin, save post"
} |
Photo Gallery Plugin and Touch Devices
I am looking for a decent plugin that will display a slide show of images that are hosted on Flickr. I have tried `Slickr Flickr` and and `Flickr+Highslide` (but that one seems to be missing from the WP plugins directory right now). The issue I have with those two is they do not display the galleries properly on a mobile device. I am using `WP Touch` to handle displaying the site on smartphones.
Is there an image plugin available that plays nice with both desktop and mobile browsers, and still has the same functioanlity of the above?
p.s. This just for a hobby site, so the less coding the better (I'm not really a JS ninja anyway). | fotoramajs.com
Switch to English version in the right top corner | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, images, mobile, slideshow"
} |
How to have syntax highlighting in wordpress.com blogs?
Is there a way I could install some plugin or have syntax highlighting for my wordpress.com blog or do I need to install WP on my own server to be able to install a plugin to do that? | WordPress.com uses Alex Gorbatchev’s SyntaxHighlighter so all you need to do is use the right shortcode ex:
[code language="css"]
#button {
font-weight: bold;
border: 2px solid #fff;
}
[/code]
which gives you something like this:
!enter image description here
it has more features and you can see a list of supported languages at < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "syntax highlighting"
} |
Upload file to remote storage
I am looking to overwrite the existing upload functionality to save the file on a remote storage service. The remote storage has an HTTP interface that allow me to post file and return an addressable URL back. The reason for doing this is that the remote storage service has large amount of space and is automatically replicated for high-availability.
I have already figured out how to send files across. However, I am not sure which hook/function I should use to overwrite the existing behavior. | Two options:
1. Hook into `'wp_handle_upload'`, a filter provided by the function `wp_handle_upload()` in `wp-admin/includes/file.php`:
apply_filters(
'wp_handle_upload',
array( 'file' => $new_file, 'url' => $url, 'type' => $type ), 'upload'
)
Replace the new file URI with your remote URI.
2. The function `wp_insert_attachment()` in `wp-includes/post.php` offers two actions:
do_action('edit_attachment', $post_ID);
do_action('add_attachment', $post_ID);
You can get the attachment data by `$post_ID` and change any value here. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "plugin development, uploads"
} |
How to write sql query to get the posts from a custom taxonomy term name
I hope someone will help me.............
I have a
* Post Type ----> Dealers
* Taxonomy ----> State
how to write a sql query in this format
$catinfo1 = $wpdb->get_results("select t.*,(select count(tr.object_id) from $wpdb->term_relationships tr join $wpdb->posts p on p.ID=tr.object_id where tt.term_taxonomy_id=tr.term_taxonomy_id and p.post_status='publish') pcount from $wpdb->terms t join $wpdb->term_taxonomy tt on tt.term_id=t.term_id where tt.taxonomy=\"fueltype\" and tt.parent=0 order by t.name"); | @Sisir linked you to the appropriate place, if you had read the question/answer and the linked Codex documentation you'd have seen that you could do something like the following:
$args = array(
'post_type' => 'dealers'
'tax_query' => array(
array(
'taxonomy' => 'state',
'field' => 'slug',
'terms' => array('bob','angela','john','smith','jan','doe','etc...')
)
)
);
$query = new WP_Query( $args );
Note the multiple state terms being queried, not the single specific one. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom taxonomy, query posts, terms"
} |
Is It A Good Idea To Change Author Slug (user_nicename field) Directly In MySQL DB?
Searching for a how-to on changing author slug, I found two methods:
1. Change the `user_nicename` field in the MySQL database of your WordPress site to whatever you want the slug to be.
2. Changing the Author Slug from Username to Nickname
The (2) is out of question because I want the slug to be something custom, but not the nickname/nicename.
As for (1) I wanted to know if this is okay -- to change the value of `user_nicename` field in the database for the user? | Providing you know what you're doing that shouldn't be a problem. You will however have to check that any author/user pages you may have are linked by id rather than name in the code:
$data = get_userdata( $userid );
As opposed to
$data = get_userdata('Admin');
Because the ID will never change (unless you delete the row and re-insert) but if you change `Admin` to `Supreme Overlord, Master of this Domain` the second reference will not work but the first will.
NOTE, this will not break the usage of `current_user_can($capability)` but will break `user_can('Admin',$capability)` but I don't see why you would be using `user_can()` over `current_user_can()` anyways. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 4,
"tags": "permalinks, slug"
} |
"HTTP error" randomly on image uploads
I have been getting "HTTP error." messages seemingly randomly when I upload images. The frustrating part is that if I get the error on an image, then try the same image again a few minutes later, it works. It's hard to debug when it's not consistent.
Has anyone else had this problem? | Pretty sure this is being caused by the Smush.it Plugin. Apparently their servers can't handle the traffic lately. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "uploads"
} |
Wrong url in sortable column headers & pagination in the admin, when behind a proxy
Recently I changed the url of my site from atlas.site.com to site.com, one thing I just came across in the admin area for posts, custom post types, pages, where there are more than one page of posts, the arrows for next, previous, first & last page, are all pointing at atlas.site.com/wp-admin/...
I've done a find and replace for atlas in the db, but perhaps I'm not looking in the right place, and it returned 0 results, and WP_SITEURL & WP_HOME in wp-config are both set to <
The same applies for Title, Author, Date at the top of the columns for sorting.
Thanks | Ok so apparently this site is behind a firewall or proxy.
On lines 491 and 658 in wp-admin/includes/class-wp-list-table.php, replace this line `$current_url = ( is_ssl() ? ' : ' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];`
with
`if(!empty($_SERVER['HTTP_X_FORWARDED_HOST'])){ $hostname = $_SERVER['HTTP_X_FORWARDED_HOST']; } else { $hostname = $_SERVER['HTTP_HOST']; } $current_url = ( is_ssl() ? ' : ' ) . $hostname . $_SERVER['REQUEST_URI'];`
Thanks goes to < for posting this fix.
Now the question is there any way to do this without editing core files? If anyone can post that I'll mark that as the accepted answer, I haven't had to modify my core yet, and I'd prefer to keep it that way. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "admin, urls"
} |
Media Library, hook on delete user action
I need to run my function when a user deletes a media file from the media library. Is there a hook I can use?
Would appreciate it if someone could please point me to the right direction.
Thanks! | A more appropriate hook may be `delete_attachment($post_id)`. You may also need to hook `edit_attachment`. Note that the `post_id` is that of the attachment type post, not the page/blog post to which the media is attached (if any).
In case you want to know when media is added, hook `add_attachment($post_id)`. Note that `add_attachment` is called before intermediate size files are generated but after the media has been placed in the upload directory. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "media library"
} |
Custom post type post in custom menu
I created **Custom post type** named **Regular pages**. In that custom post type I created two pages **About us** and **Services**.
Is there any way to add that posts into my custom menu I created in Appearance->Menus?
Perfect for my if all posts created in **Regular pages** automatically appears in menu.
Can't add them like Custom link. | Go to Screen Options and you should see a "Regular Pages" checkbox that will add a box from which you can add "Regular Pages" to the menu. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, menus"
} |
Using the_excerpt() on a page
I've been trying to utilize the PHP excerpt function to call from her recent blog post to post on a main landing page without avail. Any thoughts?
<div id="home_news" class="prefix_9 grid_3">
<div id="newsbox" style="display: block;">
<div id="news">
<h2>Welcome</h2>
<div id="news_content">Welcome to the... .check back shortly for a new selection of oil paintings, latest prints and greeting cards</a>.
<?php
$my_query = new WP_Query('category_name=blog&posts_per_page=1');
while ($my_query->have_posts()) : $my_query->the_post();
$do_not_duplicate = $post->505;
the_excerpt();
endwhile; ?>
</div>
</div>
</div>
</div> | While this was far from clear in the OP at first, I think this might be a good solution. Just make a shortcode to place the excerpt in the body. (This is a bad idea if you want this on _every page_. This is a good idea if you want it once in a while on some pages in the body.)
Here's code to put in your functions.php:
function the_excerpt_shortcode() {
return get_the_excerpt();
}
add_shortcode( 'the_excerpt', 'the_excerpt_shortcode' );
Once you have the, just put this in your page body:
[the_excerpt]
And you're good to go.
If you're using Twenty Ten, Twenty Eleven, or some other theme that hooks to the excerpt_more filter, you may have to modify that short code to strip an auto-generated "Continue Reading..." link, but for many themes that's unnecessary. Consider this a starting point. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, pages, excerpt"
} |
WordPress network: set themes and plugins for new blog
How can I enable specific themes and plugins for new blogs that have been created with `wpmu_create_blog`? I'd like to set the themes and plugins in code rather than having a person manually set them in the network administration section (i.e. not in `
Thanks!
Update: Actually I think I may have figured **part** of this out. `wpmu_create_blog` has a `$meta` property. This property can be set to an associative array with a key of 'allowedthemes'. That key's value should be set to an associative array with keys:values = 'theme-name-or-id':true. I still need to set the starting theme for this blog and set plugins, which must be similar. Is this even a good approach? | This WPSE answer led me to the $meta argument for `wpmu_create_blog`. That led me to this Support thread showing that $meta can include `template` and `stylesheet` arguments which seem to contain the folder name for the theme you want (just like the "Template" field in a child theme's style.css head section).
I'm having a hard time finding good documentation on `wpmu_create_blog`, but hopefully this is enough to work on. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, plugin development, multisite, customization, network admin"
} |
Localized Date Format for Custom Field
I'm using a custom field, formatted with "dd-mm-yyyy". I would like to use it with the Date Format defined in the Dashboard settings.
It seems alright in English with
get_option('date_format');
Or manually in French with
setlocale(LC_ALL, 'fr_FR');
$date_local = strftime("%d-%m-%Y",$date->format('U'));
But is there a way to use the localized date format of wordpress? I can't find how to give the date as an argument to
the_date() | actually I found the answer right after posting:
date_i18n(get_option('date_format') ,$timestamp);
it was in an example here | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom field, date, localization"
} |
What WordPress API function lists active/inactive plugins?
After seeing thousands of useful API functions in the WordPress core, I'm surprised to discover today that there ain't a function that would list the active plug-ins. I don't know you but I'm quite surprised at that.
I was wondering if there is a reason for missing that? If so, I'd like to know about it.
And, if there is a quick PHP snippet you know of that could give you a list of active plugins, ( the same way that a `get_post_types('','names');` does for CPT's or `get_taxonomies('','names');` does for CTs ), I'd appreciate it if you provide the code. | `wp_get_active_and_valid_plugins()`
`get_plugins()`
and `get_option('active_plugins')` | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 6,
"tags": "plugins, api"
} |
plugin to upload to youtube via wordpress
before you say it, i know that in most situations it's _easier_ to do this the other way around (i.e. upload via yt site then embed) but i _need_ a plugin to upload/manage yt videos via the wordpress admin interface.
ive scanned through the plugin directory but cant see any good options.
can anyone suggest anything worthy?
hopefully something that uses the youtube api: <
thank you! | You can try the following plugin for uploading video to YouTube from your WordPress site.
YouTube Uploader
The plugin description says:
> This plugin allows you to upload your videos on youtube without leaving wordpress. Useful especially for video blogging sites.
Though you need to enter your developer key and choose the method of authentication in YouTube uploader settings page of the plugin in order to upload video into YouTube. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin, plugin recommendation, wp admin, youtube"
} |
Adding guestbook to my wordpress site
I´m trying to add something like a guestbook, where the user can write about our services, something like comments with few more content like country, facebook page... should i do this with a single page extending the default comments using with wordpress or i have to add a new content type? How can i give the user permission tu publish without register? | The easiest way by far would be as you suggested to use a page coupled with comments. Restyle it so that it looks more like a guestbook.
I'm sure there are plugins out there that do this but I don't see the point as you'll need to restyle them anyway and it just slows down your site. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, user access, comment form"
} |
Wordpress pre-build slider
Does wordpress 3+ brings a default images slider feature? Or is it just the template I downloaded?
If it brings a pre-build slider, how should I customize, add more features to it? I want to modify it to allow some content sliding features (like on: < and not only images. | No, WordPress does not have a slider feature built in. It will be either a plugin or your theme that has added the slider.
For modifying or adjusting your slider, please go to the support area for the plugin/theme you used.
If you wish to develop your own, there are many, many tutorials out there you can use, ( I personally recommend NivoSlider ), but how to add a slider to a WordPress site is beyond the scope of this question. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -3,
"tags": "plugin development, slideshow"
} |
Highlight parent menu item when child is not in menu
I want to highlight the parent of a child page in the menu when the child page itself is not in the menu.
I know this would work if you add the child as a sub page but that isn't the case.
Any ideas? | Alrdy got it:
<?php //in functions.php
add_filter('nav_menu_css_class', 'highlight_portfolio', 12, 2);
function highlight_portfolio($classes, $item) {
$parent = get_post_ancestors();
$parent_ID = $parent[0];
if ($parent_ID == $item->object_id) {
array_push($classes, 'current-menu-ancestor');
}
return $classes;
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "menus"
} |
Need to do blank search.
When there is no value for parameter "s" , it redirects automatically to homepage. Instead of this , I want to show all the information from my custom sql query. how can i do this?? | You can pass `s=%20` as your search string, but thats kinda hackish.
If what you are trying to achieve is to use your search.php template but with "controled" search results, consider using this:
<?php
global $query_string; // fetch query string being used
query_posts($query_string . '&posts_per_page=20') // add your terms to it.
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "search"
} |
When we register a custom taxonomy or post type, does the WP database modified at all?
When you use the `register post type` and `register taxonomy` functions in your functions.php, where do all that setting info get stored in regards to the CT's and CPT's you are registering?
I'm talking about the settings such as whether the CPT is public or not, which custom post types work with which registered taxonomies, whether custom taxonomy is hierarchical or not etc.
Is that all on the server memory? If so, what's the reason of not saving it on the database -for example in wp_options table?
Isn't the `wp_options` table specifically deal with stuff like this? | When you register post type it is stored in a global var name `$wp_post_types` and the taxonomies are stored in a global var named `$wp_taxonomies`
Its all in the memory since you need it all and if it was stored in the database you would need to pull it from the database and then it would still be in the memory. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "custom post types, custom taxonomy, init"
} |
Add custom option to Standard Page Attributes Meta Box
I'd like to add a simple checkbox option to the exsisting standard Page Attributes Meta Box.
Is there an obvious/intended way to do that using the WordPress API, rather than registering a new metabox for my one new option? | Unfortunately not. The only way is to deregister the metabox, and then re-register it, supplying your own callback function which mimics the original metabox, but with your alterations (making sure the names of the inputs do not change).
This method is outlined in these posts:
* custom post type taxonomies UI radiobuttons not checkboxes
* Custom-Taxonomy as categories: Remove "most-used" tab?
Alternatively you can insert the options with javascript as outlined in:
* How to Add Reminders/Notes to New Post Meta Boxes | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "custom field, metabox"
} |
Adding wp_editor to custom metabox
I am adding fields to a custom post type. How can I have editing options in my meta data just as they are in the editor box?
add_action('add_meta_boxes', 'add_property');
function add_property(){
add_meta_box("description-meta", "Property Description", "desc_options", "property", "normal");
}
function desc_options(){
global $post;
$values = get_post_custom($post->ID);
$description = isset( $values['description'] ) ? esc_attr( $values['description'][0] ) : '';
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>
<p>
<label>Description:</label><br/><textarea name="description" cols="100" rows="20"><?php echo $description; ?></textarea>
</p> | Unfortunately you can't yet...
see this trac ticket: <
In particular it seems that:
> The problem is that TinyMCE, once initialized cannot be moved in the DOM, or rather the browsers cannot handle it being moved. That's why the errors are so inconsistent in different browsers. Moving the postbox triggers this. Some browsers/versions handle that better than others as @ocean90 mentions above but generally the editor textarea and iframe shouldn't be moved. - **azaozz** | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, wp editor"
} |
Want to exclude slider from page.php in header
I know this is a dumb question, but for the love of my life, I can't get the code to work. I have three page templates: home, page and another page-by category. I have a slider that I want to excluded from the default page.php file but to show everywhere else. I have tried to do this with `is_page_template` , but that isn't working. any help will be much appreciated. I'm not sure if you need my header code. If you do then leave a comment please and I'll paste in in pastebin. Thanks a lot in advance. | Did you consult the `is_page_template()` Codex entry?
If you want to query for the `page.php` page template, then you need to pass that filename to `is_page_template()`; i.e.:
<?php
if ( ! is_page_template( 'page.php' ) ) {
// The current page template is NOT page.php;
// do something
}
?>
Sidenote: if you want to query for being a static page AND not a specific page template:
<?php
if ( is_page() && ! is_page_template( 'page.php' ) ) {
// Current page is a static page AND
// The current page template is NOT page.php;
// do something
}
?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "page template, exclude"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.