INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
DB access blocked when initializing WP externally
I have an odd problem I'm hoping the group can help with. The problem is this:
* I have a few situations where I load the Wordpress environment without the overhead of the GUI (details)
* I am able to do this in most environments without a problem but a few (two laptops to be precise) refuse to load Wordpress and instead give me the following error:
!enter image description here
What's so very strange is that:
1. The db connection attributes are correct. This has been validated both by logging in manually from the command-line (using the credentials in the wp-config file); not to mention that this same `wp-config.php` has no problem loading the database when it is loaded normally by Wordpress.
2. The files, OS, PHP version, even the DB connection parameters are all exactly the same on computers that work versus those that don't.
I'm not sure were else to look. Any help would be greatly appreciated. | I accidentally stumbled into the answer today when I forgot to turn on my MAMP managed mysql server. At this juncture it pointed me to the critical difference. This answer is phrased for anyone running MAMP but potentially has broader applicability (certainly LAMP, WAMP, etc.); if you're experiencing the same problem in an non-MAMP environment than these steps may still apply but the explicit directories would not:
* When Wordpress loads normally it looks in `/Applications/MAMP/tmp/mysql/mysql.sock` but when run from the command line it instead looks for the socket file in `/var/mysql/mysql.sock`.
* In order to allow for both execution environments (aka, normal WP and my command-line "include") you just need to create a symbolic link:
ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock
* You may need superuser privileges, in which case just add `sudo`:
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock
Hope that helps. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database, wp config"
} |
Upload PDF and other files from the Front-End
I am trying to create a medical website, where logged-in doctors can actually upload pdfs and other files (such as jpg) from the front-end in posts. Then, after reloading the page, the uploaded files should be retrieved within the same post, so other users can easily find the info, without any access to the back-end whatsoever.
Can this be done in WP?
Thanks in advance!
Miguel | Yes, this can be done in WordPress. Check out < for some code examples.
You will have to modify the logic to suit your needs of course, but the above link should get you pointed in the right direction. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "uploads, front end, user access, pdf, wp filesystem"
} |
How to remove CSS file in the header using Wordpress functions?
I want to remove a CSS from loading in the header, this is the code that appears:
<link rel='stylesheet' id='my-css' href=' type='text/css' media='all' />
I tried using these functions but it didn't work:
wp_dequeue_style('my-css');
wp_deregister_style('my-css');
Is there other ways that the above CSS line can be removed without manually editing it in the template?
Thanks. | If your stylesheet is registered and enqueued correctly then...
function dequeue_my_css() {
wp_dequeue_style('my-css');
wp_deregister_style('my-css');
}
add_action('wp_enqueue_scripts','dequeue_my_css');
// add a priority if you need it
// add_action('wp_enqueue_scripts','dequeue_my_css',100);
... should remove it. That only works if the stylesheet was registered and/or enqueued with `wp_register_style` and `wp_enqueue_style`.
If it is not registered correctly then you will have to figure out what your theme did and undo that. It may require editing the template, depending on how the theme is written.
<
< | stackexchange-wordpress | {
"answer_score": 13,
"question_score": 4,
"tags": "css"
} |
How to disable Multisite sign-up page?
If we try to access a non-existant Multisite site, e.g., ` or ` we are redirected to `
How to block this and redirect the browser to another page? | ### [Update]
An alternative (maybe better) is to use the following constant in `wp-config.php`:
define( 'NOBLOGREDIRECT', ' );
* * *
At the very beginning of `wp-signup.php` file there is this code:
function do_signup_header() {
do_action( 'signup_header' );
}
add_action( 'wp_head', 'do_signup_header' );
So, it's just a matter of adding the `signup_header` action hook to break any further execution and redirect the browser to other URL.
Here, wrapped as a Must Use Plugin:
<?php
/*
Plugin Name: Multisite - Prevent Sign-up Page
Plugin Url:
Version: 1.0
Author: Rodolfo Buaiz
*/
add_action( 'signup_header', 'rbz_prevent_multisite_signup' );
function rbz_prevent_multisite_signup()
{
wp_redirect( site_url() );
die();
} | stackexchange-wordpress | {
"answer_score": 18,
"question_score": 6,
"tags": "multisite, redirect"
} |
Strings including html for localisation
How to localise this string (including html) ?
echo "<div class='updated'><p>All options are restored successfully.</p></div>" ;
Is this correct?
echo '<div class="updated"><p>' . __( 'All options are restored successfully.', 'mytextdomain' ) . '</p></div>';
And how to go about this one?
<p><?php _e( 'On the <a href="' . get_admin_url() . 'import.php">Import</a> page, choose the previously created file and click the <strong>Upload file and import</strong> button.', 'mytextdomain' ); ?></p> | Your example is correct, simply because it works. There are hundreds of ways to localize strings wich are displayed including html, all good and elegant in their own way.
I like to do this as follows:
printf( '<div class="updated">
<p>%1$s</p>
</div>',
__( 'All options are restored successfully.', 'mytextdomain' )
);
You also could do this like:
$str = __( 'All options are restored successfully.', 'mytextdomain' );
echo "<div class='updated'><p>$str</p></div>";
The most important thing is to maintain readability I guess. There isn't a "correct" way to display localized strings in combination with html.
For your second one, I would use:
_e( sprintf( 'On the <a href="%1$s">Import</a> page, choose the previously created file and click the <strong>Upload file and import</strong> button.', get_admin_url() . 'import.php' ), 'mytextdomain' );
In this case, the URL doesn't have to be translated. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "localization"
} |
Redirect a password protected page?
I'm looking for the simplest way to redirect a password protected page, to another page after entering the password.
E.g.
<?php if ( is_page('name-of-page') && ! post_password_required() ) {
wp_redirect( home_url() ); exit;
} ?>
Using wp_redirect is triggering a 'headers already sent error'.
I've seen some solutions using output buffering to avoid this but, I'm not sure if it is the best solution.
Thanks! | Tom J Nowell confirmed what was happening. Inserting `wp_redirect` in a template causes the page either to partially load or not load at all.
It needed to be placed before the opening `<html>` to work as it would load everything before `</head>` then stop. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "password, wp redirect"
} |
Delete all one-word comments
I'm trying to delete all wordpress comments with only one word. I found this mysql query to delete all comments at once, but that's not what I want to achieve:
DELETE FROM wp_comments WHERE comment_approved = '0' | DISCLAIMER : Not a WordPress Developer, Just a MySQL DBA
If you have privileges to login to MySQL and query data you could collect all the `comment_ID` values that have one word.
SELECT comment_ID FROM wp_comments WHERE
REPLACE(TRIM(comment_content),' ','')=TRIM(comment_content);
You can test this by also seeing the comment_content
SELECT comment_ID,comment_content FROM wp_comments WHERE
REPLACE(TRIM(comment_content),' ','')=TRIM(comment_content);
Using the WordPress API, retrieve those `comment_ID` values and delete them.
Give it a Try !!!
# CAVEAT
Other posts have been given for bulk deleting of comments (none of these are my posts):
* How do I delete all comments from a specific old blog post?
* How to Delete Old Comments by Date?
* SQL query to delete comments older than 90 days? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments, mysql, hacks, phpmyadmin"
} |
Multiple while loops not functioning
I have this `while` loop in my product page with Wordpress e-commerce plugin. It is looping through custom post meta.
<?php if (wpsc_have_custom_meta()) : ?>
<?php $count = 2; ?>
<?php while ( wpsc_have_custom_meta() ) : wpsc_the_custom_meta(); ?>
<?php if (stripos(wpsc_custom_meta_name(),'g:') !== FALSE) continue; ?>
<li>
<a href="#tab<?php echo $count; ?>"><?php echo wpsc_custom_meta_name(); ?></a>
</li>
<?php $count ++; ?>
<?php endwhile; ?>
<?php endif; ?>
I repeat this twice. Once to iterate through tab titles and once through the tab body. But for some reason the second instance of the `while loop` won't work. If I delete the first instance then the second one works as expected but as soon as I have to examples of it then it no longer works. Thanks for the help. | It doesn't appear possible to loop over the values multiple times without directly manipulating the `current_custom_meta` class var so that `wpsc_have_custom_meta()` will return `true` again. Give this a try before the second while loop:
global $wpsc_custom_meta;
$wpsc_custom_meta->rewind_custom_meta();
$wpsc_custom_meta->current_custom_meta = -1; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, plugin wp e commerce"
} |
Enqueue ONLY Plugin Styles and Scripts
Is there a way to enqueue only plugin styles and scripts without wp_head? I have a plugin I'm working on which overrides the page template, but I still want to include all other plugins without including the theme style. Since theme developers don't always enqueue their styles and often hardcode the link, what's the best way around this? | > Since theme developers don't always enqueue their styles and often hardcode the link, what's the best way around this?
There is _no_ way _around_ this. Simply said: Let them burn. They're doing it wrong and as a 3rd party code developer you don't have to take wannabe developers into account. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, wp enqueue script, wp enqueue style"
} |
Do I need to include a textdomain if my theme doesn't support translation?
According to the codex
> Themes are required to use theme-slug (or a reasonable facsimile) as textdomain for translation
Does this mean that my theme needs to include a textdomain even if my theme doesn't support translation? ... and also is there any harm in including a textdomain in `style.css` if there are no translation options. | If your code, be it a theme or a plugin, does not support translation, then don’t use the translation functions. And if you don’t use these functions, you _cannot_ use a text domain. :)
There is a very common error that looks like this:
echo __( 'Portfolio' );
_Portfolio_ is not part of WordPress’ core strings, so this code will waste an expensive look-up in the list of translated words without result.
Another side effect is a _partial translation_ when some of these function calls without text domain _match_ core strings. Imagine a navigation where the link to the previous page is in Japanese and the link to the next page in English. This is worse than no translation at all.
So text domains are not your problem, the use of translation functions is important. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development, localization, codex, repository, theme review"
} |
wp_list_pages - Using a Walker to customize output order
I'm using wp_list_pages to create a navigation menu. I've run into a challenge with the menu order, though, and I am trying to figure out a way to take more control over the order of the menu.
Is it possible to customize the order of the wp_list_pages output using a Walker?
For example, I'd like to check if a given page in wp_list_pages results has a `post_meta` value of `page_x` and output that _first_ , then do the same for another page, then, if none of the rules match, continue as normal. | `wp_list_pages( $args )` calls `get_pages( $args )`. You can filter the `get_pages()` output with a filter on `get_pages`.
Let’s say you call `wp_list_pages()` like this:
wp_list_pages(
array(
'please_filter_me' => TRUE
)
);
You can sort the pages now with code like this (not tested):
add_filter( 'get_pages', function( $pages, $args ) {
// not our query
if ( empty ( $args['please_filter_me'] ) )
return $pages;
$out = $top = array();
foreach ( $pages as $page )
{
if ( get_post_meta( $page->ID, 'my_key', TRUE ) )
$top[] = $page;
else
$out[] = $page;
}
return $top + $out;
}, 10, 2 ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp list pages"
} |
WP_Query pulling an extra post per page
I'm querying to get a list of all posts, 20 posts_per_page, but the result shows all posts, but with 21 posts per page. If I change posts_per_page to 19, then 20 show. One post is sticky and shows up twice; not sure if that is causing the problem.
Code:
$allposts = array(
'post_type' => 'post',
'posts_per_page' => 20
);
$wp_query = new WP_Query($allposts); ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<li><?php the_title(); ?></li>
<?php foo_pagination(); ?>
<?php endwhile; ?> | Sticky posts do add to the post count rather than being included in it. You can alter your query to ignore sticky posts though.
$allposts = array(
'post_type' => 'post',
'posts_per_page' => 20,
'ignore_sticky_posts' => true
);
But you are also missing pagination parameters.
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$allposts = array(
'post_type' => 'post',
'posts_per_page' => 20,
'ignore_sticky_posts' => true,
'paged' => $paged
); | stackexchange-wordpress | {
"answer_score": 17,
"question_score": 3,
"tags": "wp query"
} |
Using esc_html with HTML purifier and CSSTidy: Overkill?
Currently my text area input (which accepts custom CSS input from a user) in the Wordpress theme options panel are sanitized by esc_html function in Wordpress <
However I am thinking a secure approach, so I would like to add HTML purifier and CSSTidy like it's illustrated here: <
Is this necessary? Or Wordpress core function like esc_html already uses HTML purifier so this is not anymore needed. Please advise. Thanks. | If you worry only about the admin panel then esc_html will be enough as it will convert every "<" into < eliminating the possibility of having a valid HTML tags inserted.
But if you add the CSS to the generated HTML you might need to strip any HTML tag it may contain by using the wp_kses function
$css = wp_kses($css,array(),array());
should strip all possible HTML from the CSS.
But stripping is not needed at all if the user has unfiltered_html capability, usually the admin of a stand alone site. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "security"
} |
Custom Background: Can't Set Color Default
I'm using the standard WP Custom Backgrounds feature, however, the color is defaulting to #166b4c and I'm unsure why. #166b4c does not appear in my stylesheet. Below is my code.
add_theme_support( 'custom-background' );
$defaults = array(
'default-color' => '000',
'default-image' => '',
'wp-head-callback' => '_custom_background_cb',
'admin-head-callback' => '',
'admin-preview-callback' => ''
);
add_theme_support( 'custom-background', $defaults);
Live example: < | You have to pass the `$defaults` as the second parameter to `add_theme_support()` per the Codex
$defaults = array(
'default-color' => '000000',
'default-image' => '',
'wp-head-callback' => '_custom_background_cb',
'admin-head-callback' => '',
'admin-preview-callback' => ''
);
add_theme_support( 'custom-background', $defaults); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom background"
} |
How can a 'scripts' directory be hooked into wp_head();?
So I'm trying to get my head round `<?php wp_head(); ?>`.
I understand that it loads in the stuff needed for plugins etc., but I'm using a theme that seems to be using it to load in scripts for theme elements as well.
There's a folder within my theme called 'scripts' that appears to have all of the javascript needed for the theme. In the outputted code is all of the javascript files etc.
So my question is: How do I hook in a javascript file (or anything for that matter) into `<?php wp_head(); ?>`? | You use `wp_enqueue_script` for Javascript files in your theme `functions.php` files. I suggest wrapping up all the requests in a function and hook it like so
add_action( 'wp_enqueue_scripts', 'script_enqueuer' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "php, theme development, wp head"
} |
Hook to main query with filters based on custom fields
I would like to do a filter that will hook to the main query and filter all the posts by some given taxonomy terms or custom fields. For now I have made the custom filters for the $query to only select the posts that have a custom value for certain taxonomy as follows:
foreach($data as $taxonomy => $terms):
$query->set($taxonomy,$terms);
endforeach;
and this solves it. But for example, I am having the following issue: I don't see how to provide instead of a taxonomy field, a custom field that has the value in a range; For example price is between 500-1000; where price is a custom field.
I have tried anything I could and searched a lot on the codex but I can't figure it out. | Have a look at the format of a `meta_query` in `WP_Query`.
$meta_query = array(
array(
'key' => 'price',
'value' => array( 500, 1000 ),
'type' => 'numeric',
'compare' => 'BETWEEN'
)
);
$query->set( 'meta_query', $meta_query ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop"
} |
Stop WordPress Entirely and Run My Own Code
I have a site that must be deployed in a WP Multisite environment but none of the code in the site uses WordPress at all. How can I intercept WordPress, perhaps at 'init', and tell it to stop doing anything and let me take over?
I tried just putting everything in my `index.php` file and include everything manually from there. However, this results in the `<head>` of my page being loaded within the body. So it's obvious that I need to interrupt WordPress before it can run `wp_head()`, but don't know how this might be done. | You could hook `init` and check the current blog ID
function wpa85780_my_app_init(){
$my_blog_id = 99;
if( $my_blog_id == get_current_blog_id() ):
include 'somefile';
exit;
endif;
}
add_action( 'init', 'wpa85780_my_app_init' );
This will exit before WordPress does the main query and loads the template.
**EDIT**
a slightly earlier action you could hook is `after_setup_theme`, that seems to be the earliest that `get_current_blog_id` will work. See the action reference page for the order of actions. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "multisite, init"
} |
render html no formatting
How can I get WordPress to render a page without it adding any addtional html? I'm trying to build a dialog that will work on mobile devices and I only want to show that dialog and not have any of the standard wordpress content around it. | You have to implement your own hook for `template_redirect` action:
add_action( 'template_redirect', 'wpse8170_template_redirect', 1 );
function wpse8170_template_redirect() {
global $wp_query;
// check if it is not a page or if it is front page, then exit from the hook
if ( !$wp_query->is_page() || $wp_query->is_front_page() ) {
return;
}
// check queried object, if it is not a specific page, then exit from the hook
$page = get_queried_object();
if ( $page->ID != 777 ) { // your page ID
return;
}
// render header
get_header();
// ... render your content here ....
// render footer
get_footer();
exit;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "html"
} |
Paginate WordPress Category Pages
I am using the following `query` on my `category.php` template:
<?php
$paged = (get_query_var("paged")) ? get_query_var("paged") : 1;
query_posts("posts_per_page=2&paged=".$paged);
?>
The one thing that I've noticed is that this breaks my pagination...with this code the pagination returns "paged" in the url: fortunately or unfortunately it's a simple issue with the url...instead of returning "paged" in the url, it should return "page" or
I have tried altering my code (as explained: < for pages):
<?php
$page = (get_query_var("page")) ? get_query_var("page") : 1;
query_posts("posts_per_page=2&page=".$page);
?>
But that doesn't work either...any ideas?
Thanks,
Josh | `paged` is correct unless you're using pretty permalinks, however, if you're just trying to alter posts per page for categories, you should be using the `pre_get_posts` action, there's no reason to use `query_posts` in the template:
function wpa85791_category_posts_per_page( $query ) {
if ( $query->is_category() && $query->is_main_query() )
$query->set( 'posts_per_page', 2 );
}
add_action( 'pre_get_posts', 'wpa85791_category_posts_per_page' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, query posts, pagination, page template"
} |
How to add a body class to all interior pages except the homepage
I want to add a class to the body tag to all pages EXCEPT the homepage. Right now I have.
`<?php body_class('interior'); ?>`
But it adds 'interior' to ALL pages including the home page.
What is the best standard way of adding a class to the body tag? | Try it:
<?php
$class = ! is_home() ? "interior" : "";
body_class( $class );
?>
Or this:
<?php
body_class( ! is_home() ? "interior" : "" );
?> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "css, homepage"
} |
No Thumbnails Generated
I setup WordPress on my own server and it's up and running...one thing that I have noticed is that WordPress doesn't generate any images I upload. Usually when I upload an image through WordPress it will generate a thumbnail, medium, and large sized image. WordPress installed without error and everything else is working fine. I have tried to rebuild the thumbnails, but that doesn't work :-(
Any ideas?
Thanks,
Josh | I figured it out!
In my php.ini file I had to uncomment `extension=php_gd2.dll`, then it started working after I rebuilt the images I uploaded :)
Thanks,
Josh | stackexchange-wordpress | {
"answer_score": 19,
"question_score": 20,
"tags": "uploads, post thumbnails, server, images"
} |
Is it possible to set a option, and then redirect to another page directly from a admin notice link?
I like to execute a update_options() and stuff and then redirect to another plugins page? Directly after the user clicks a link in a Admin notice.
How would i do that? Ajax? Is that even possible? | You could use `/wp-admin/admin-post.php`.
Link:
$url = admin_url( 'admin-post.php?action=somethingunique' );
print "<a href='$url'>Update and redirect</a>";
Then you should register a callback for that action:
add_action( 'admin_post_somethingunique', 'wpse_85825_callback' );
And in that callback you can do what you want:
function wpse_85825_callback()
{
if ( current_user_can( 'manage_options' ) )
update_option( 'my_option', 'some_value' );
wp_redirect( admin_url( 'users.php' ) );
exit;
}
Note this is just some untested code, take it as a direction, not as final solution. :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp admin, notices, plugin options"
} |
How To Grab All Type Of Attachments, But Images?
I need to get all file attachments which is not an image,
'post_mime_type' only accepts "any" or specific mime types,
How to grab all type of attachments, but images? | WordPress has a function, `get_allowed_mime_types`, which will return all allowed types. We can filter this list and exclude any types containing `image`, then query for all remaining types by passing them as a comma separated list to `post_mime_type`. This may not be the most efficient way to do it, you may be better off filtering `posts_where`, but it'll work.
$filtered_mime_types = array();
foreach( get_allowed_mime_types() as $key => $type ):
if( false === strpos( $type, 'image' ) )
$filtered_mime_types[] = $type;
endforeach;
$args = array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'any',
'post_mime_type' => implode( ',', $filtered_mime_types )
);
$results = new WP_Query( $args ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "attachments"
} |
How to check if commenter is the_author?
What's the best way of checking if my commenter is also the author of the post that he post comment on?
I know there's a css way (`.byauthor`), but how about PHP? How to compare post author with comment author? I was trying with is_author(), the_author() and comment_author() but it just doesn't look right (what if somebody uses the same nickname as author?).
Here's my code for now:
<?php if(get_the_author() == get_comment_author()) _e( 'Author', 'theme' ) ?> | Not sure what you are meaning to do but, if you take a look at the `get_comment_class()` function that is responsible for generating the `.bypostauthor` class you can see how it determines if the commenter is the author
if ( $post = get_post($post_id) ) {
if ( $comment->user_id === $post->post_author )
$classes[] = 'bypostauthor';
}
You should be able to use this to do something similar. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "comments, author"
} |
How to show custom field and parent post id in wordpress attachment page (image.php)
I'm trying to use code to show custom field outside the loop in wordpress attachment page (image.php) it's returns nothing.
this is the code i'm used to show the custom field:
<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'my-custom-field', true);
?>
and i'm trying to show parent post id in attachment page too with `get_the_id` and use this code
<?php global $wp_query;
$this_page_id = $wp_query->post_parent;
$post_id = get_the_id($post->ID);
echo $post_id ;?>
but the code above just shown the attachment ID not the parent post ID. anyone can help, please ? | You already have `$post` object on `image.php`. Don't complicate and use following:
<?php
echo get_post_meta($post->ID, 'my-custom-field', true);
echo $post->post_parent; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field"
} |
Display Today's date outside the loop?
Is there any way to display the Today's date outside any loop/post using WordPress date/time function instead of using the PHP `date()` function? I'm using the PHP `date()` function but it does not translate the date (month/day names) in the local languages, so it is not possible to translate it without changing the PHP code and setting the locale etc. | Use `date_i18n()` from `wp-includes/functions.php`.
/**
* Retrieve the date in localized format, based on timestamp.
*
* If the locale specifies the locale month and weekday, then the locale will
* take over the format for the date. If it isn't, then the date format string
* will be used instead.
*
* @since 0.71
*
* @param string $dateformatstring Format to display the date.
* @param int $unixtimestamp Optional. Unix timestamp.
* @param bool $gmt Optional, default is false. Whether to convert to GMT for time.
* @return string The date, translated if locale specifies it.
*/
function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, themes, date, translation, localization"
} |
Theme Checker Text Domain
`$output .= '<li class="recentcomments">' . sprintf(_x('%1$s %2$s - %3$s %4$s', 'thst'), get_avatar( $comment, 48 ), (...);`
This is my line of code and Wordpress Theme Checker tells me "Text domain problems. You have not included a text domain!" I have included one though, as you can see. What could be the problem here? | `_x()` is for string with a context. So your second argument is just the context, and there is no text domain.
Suggestion:
$string = _x(
'%1$s %2$s - %3$s %4$s', # string to translate
'recent comments 1 = gravatar, 2 = … ', # context for translators
'thst' # text domain
);
$visible = sprintf( $string, get_avatar( $comment, 48 ), … );
$output .= '<li class="recentcomments">' . $visible . '</li>';
Explain all numbers in your context parameter. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, themes, textdomain"
} |
Setting get_queried_object
I know that `get_queried_object` contains the object that was queried for the current page. My question is, what methods of querying affect the contents of this?
For instance:
* `query_posts`
* `get_posts`
* `get_post`
* `new WP_Query`
* etc. | As per its laconic source:
function get_queried_object() {
global $wp_query;
return $wp_query->get_queried_object();
}
This function retrieves object from main query. As such it is affected by anything that changes main query. From your list that would be `query_posts()` (reason number umpteen it should not be used). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp query, query"
} |
Check If posts exist in custom post type category, outside of loop
I'm building a navigation, outside of the main loop, that includes drop downs. I have a custom post type called 'Events', that has its own categories. I would like there to be a drop down if there are posts within that custom post type and category, but I'm not sure what functions I should be using to determine this...
I have...
$hasposts = get_posts('post_type=Events&category=40');
if($hasposts) {
..// show the drop down menu
}
Should I even be using `get_posts()`? Everything I am getting returned has an empty array, but I know that some of those categories include posts...
Many thanks, WA. | It all boils down to WP_Query in the end even if you use get_posts, here's my modified version:
$hasposts = get_posts('post_type=sc-events&category=40');
if( !empty ( $hasposts ) ) {
..// show the drop down menu
}
or
$query = new WP_Query(array(
'post_type' => 'sc-events',
'category' => 40
));
if( $query->have_posts() ){
echo 'we have posts';
} else {
echo 'no posts found';
}
While this will work, there's an alternative inspired by your own answer that uses the category slug rather than its ID:
$term = get_term_by('name', 'whatever category 40 is called', 'category');
if($term != false ){
if($term->count > 0 ){
// we have posts
}
} | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "get posts"
} |
How to publish page that can't be detected by search engines?
I like to publish drafts in my 'Uncategorized' category. This category is not linked anywhere on my site. It's great for allowing contributors to an article to read the draft before it is made public. The problem is that after just 2 or 3 days, search engines begin picking up the draft and people start posting comments.
I don't want to password protect the draft. Is there some way to hide it from search engines while it is in the 'Uncategorized' category? | How about something like this on your `functions.php`:
add_action('wp_head', 'no_robots_on_uncategorized_posts');
function no_robots_on_uncategorized_posts() {
if(in_category('uncategorized')) {
wp_no_robots();
}
}
This will output the following line of code on the header of your 'uncategorized' posts:
<meta name='robots' content='noindex,nofollow' />
What this means is that even though search engines will see the page, they will be told to ignore it and don't show it on their results. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "admin, google search, search engines"
} |
Add a css class to a taxonomy permalink
I need to add a css class to every `<a>` element retrieved by `the_terms()` (or similar function) in order to open the taxonomy permalink in a fancybox modal window. I've been searching this whole afternoon for a Filter that could handle it, with no success.
Anyway, I got into this (poor) solution below:
$cities = get_the_terms($post->ID, 'cities');
foreach ($cities as $city) {
echo '<a class="fancybox" href="'. get_term_link( $city->slug, 'cities' ).'">'.$city->name. '</a>' ;
}
But it's too 'ugly' to put in a template file.
Is there any wordpress filter that deals with this question of permalink html generation?
Thanks a lot! | The filter you are looking for is `term_links-$taxonomy`, where `$taxonomy` is the taxonomy name. This will filter the `$term_links` links array before outputting by `the_terms()`:
add_filter('term_links-cities', 'ad_filter_links');
function ad_filter_links($term_links) {
foreach ($term_links as $term_link) {
$term_link = str_replace('<a ', '<a class="fancybox"', $term_link);
}
return $term_links;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "permalinks, taxonomy, html"
} |
How to: Simple Nested Shortcode
Im trying to wrap a shortcode inside of a "user loggeed in" shortcode. Here are the two shortcodes and my setup in WYSIWYG
function wpfc_logged_in( $atts, $content = null ) {
if (is_user_logged_in() )
{
return do_shortcode($content);
}
}
add_shortcode('loggedin', 'wpfc_logged_in');
function info_box( $atts, $content = null ) {
extract( shortcode_atts( array(
'type' => 'tip',
'icon' => ''
), $atts ) );
$return = '<div id="info-box"><div class="info-box '.$type.'"><p>'.$content.'</p><a href="#" class="info-close-icon"></a></div></div>';
return $return;
}
add_shortcode('info_box', 'info_box');
WYSIWYG:
[loggedin]
[ info_box type='setting' ]content text[ /info_box]
[/loggedin] | it looks like you have extra spaces in your shortcodes.
Try
[loggedin]
[info_box type='setting']content text[/info_box]
[/loggedin]
instead of
[loggedin]
[ info_box type='setting' ]content text[ /info_box]
[/loggedin] | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode"
} |
How to: get_user_meta - BuddyPress
What is the proper way to display User Meta in the BP Loop using this line from codex?
<?php get_user_meta($user_id, $key, $single); ?>
I added that line to the profile loop and switched those values with ones from my DB and nothing happened. What am I doing wrong?
<?php
$user_id = 9;
$key = 'last_name';
$single = true;
$user_last = get_user_meta( $user_id, $key, $single );
echo '<p>The '. $key . ' value for user id ' . $user_id . ' is: ' . $user_last . '</p>';
?> | Inside the loop, you can get the currently iterated user id using `bp_get_member_user_id()`.
Also, it's best practice to use `bp_get_user_meta()`, because it works better with certain kinds of BP plugins (multi-network, etc).
Thus:
if ( bp_has_members() ) {
while ( bp_members() ) {
bp_the_member();
$user_last = bp_get_user_meta( bp_get_member_user_id(), 'last_name', true );
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "buddypress, meta query, user meta"
} |
Redirection based on location but without affecting search bots
A client has a successful UK site based powered by Wordpress and is launching a US arm. While the US sub-sites are built, he has a holding page that is visible to US visitors, who are redirected to it from the usual home page by the Geo Redirect plugin.
I've just realised that Geo Redirect is also redirecting Google's (and other search engines') bots, which is not at all good; does anyone have a relatively easy solution that would do what Geo Redirect does so well but would not affect visits by search engine bots? | **Search**
Help Google to determine the site language and to serve the right page for the users in different countries. Mark up language attributes correctly. Use `<html lang="en_UK">` and `<html lang="en_US">`. Use `<link rel="alternate" hreflang="x" />` in page `<head>`. It's also important to specify site targeting in Google Webmaster Tools.
**Referrers**
I believe people residing in UK will link to your UK-targeted site, not US-targeted. And inversely.
**User Experience**
It's always a good practice to leave the user the ability to choose preferred site himself.
**Advice**
Don't use any redirection plugins. Google advise sounds the same:
> Avoid automatic redirection based on the user’s perceived language (Multi-regional and multilingual sites). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, redirect, geo data"
} |
remove_action in a theme
I'm using a theme that gets updated pretty frequently. For this, it has added a custom.php file to include modifications. Now, in this theme, under the functions.php, the developer has included his own meta section which is added using the following function:
add_action('wp_head', 'theme_metas');
I want to let my SEO plugin manage this, so I tried adding this into the custom.php:
remove_action('wp_head', 'theme_metas', 15);
I even tried altering the priority higher and lower than 10 (which is default) but the metas are still showing. Can someone shed some light please? | Your `remove_action` has to have a priority matching the priority used in `add_action`.
> Important: To remove a hook, the $function_to_remove and $priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.
>
> <
In you case, it looks like `remove_action('wp_head', 'theme_metas');` should work, but you may be having trouble because of how and when your `custom.php` file loads. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 6,
"tags": "actions"
} |
wp_get_attachment_link() add rel attribute if the link points to direct image
I'm using filter like this to add `rel` attribute in `wp_get_attachment_link()`
add_filter( 'wp_get_attachment_link', 'sant_prettyadd');
function sant_prettyadd ($content) {
$content = preg_replace("/<a/","<a rel=\"prettyPhoto[slides]\"",$content,1);
return $content;
}
The above filter working fine except it adds the attribute even if the `href` points to attachment page.
I mean I want to add `rel` attribute only if the link points to direct image and not attachment page.
Can someone help me with this? | add_filter( 'wp_get_attachment_link', 'sant_prettyadd', 10, 6);
function sant_prettyadd ($content, $id, $size, $permalink, $icon, $text) {
if ($permalink) {
return $content;
}
$content = preg_replace("/<a/","<a rel=\"prettyPhoto[slides]\"",$content,1);
return $content;
}
## Update:
function sant_prettyadd checks permalink argument.
if the `permalink = true` then it returns the content as it is.
if the `permalink = false` then it skips to the next line and replace the `<a` with `<a rel="prettyPhoto[slides]"` and then returns the content. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, attachments, gallery"
} |
Organizing the Navigation Menu
I have a problem with menu organization. I have a Pages with url "pressroom" and have a Category with the same name. I want to make it a one menu item.
**Pressroom** `(sitename.com/pressroom/)`
* **page 1** `(sitename.com/pressroom/page1/)`
* **page 2** `(sitename.com/pressroom/page2/)`
* **category with posts** `(sitename.com/category/pressroom/news/)`
When I am in Category - nav_menu parent item have a correct css selector `current-menu-ancestor current-menu-parent`, but when I am go to post of this category (url changed to `sitename.com/pressroom/news/postid/`) - css selector of parent menu item disappear.
How can I correct this? | Check nav menu target URL for '/pressroom/', then check if it's a post. If it fits, add custom class to that menu item.
<?php
function my_add_posts_page_ancestor_class( $classes, $item ) {
if( false !== strpos($item->url, '/pressroom/')
&& is_single($item->ID)
&& !is_page($item->ID) ) {
$classes[] = 'my-ancestor-class';
}
return $classes;
}
add_filter('nav_menu_css_class', 'my_add_posts_page_ancestor_class', 10, 2);
The code is untested and can be improved. It's a direction to think about.
**Update**
See what I've found: Add a class to wp_nav_menu() items with URLs included in the current URL | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "urls, navigation"
} |
How can I autopopulate titles in the media library?
I have hundreds of images in my media library, most have which have no titles. In the media library, the "(no title)" message is displayed along these images.
Since I generally have one image per post, I would like to auto-populate the library titles, by grabbing the associated post name. I don't mind if I overwrite some existing titles.
Does anyone know of a hack that will do this?
I found some plugins, like 'Media Rename' and 'Rename Media' and 'SEO friendly images' but they are usually for renaming the actual image files, or for creating HTML title tags directly in the HTML (on the fly).
I want to create titles within the Wordpress media library, so that I don't see the (no title) message. This title data will also help me to search for images in the library -- although, for anyone with the same issue, I did find a plugin called 'Media Search' that enables searching images by associated posts: < | If you can do SQL manually then try:
UPDATE wp_posts p INNER JOIN wp_posts q ON p.post_type = 'attachment' AND p.post_mime_type LIKE 'image/%' AND (p.post_title IS NULL OR LENGTH(p.post_title) = 0) AND p.post_parent = q.ID SET p.post_title = q.post_title;
If you need a PHP function then try:
function set_image_without_title_to_post_title() {
global $wpdb;
$sql = sprintf( "UPDATE %s p INNER JOIN %s q "
. "ON p.post_type = 'attachment' AND p.post_mime_type LIKE 'image/%%' "
. "AND (p.post_title IS NULL OR LENGTH(p.post_title) = 0) "
. "AND p.post_parent = q.ID "
. "SET p.post_title = q.post_title",
$wpdb->posts, $wpdb->posts );
$wpdb->get_results( $sql, ARRAY_A );
}
WARNING: As this will make massive changes to your database I would do a backup first! I did run a small test and it appears to be correct but USE AT YOUR OWN RISK! | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "images, media library, hacks"
} |
Content filter won't work
I'm trying to filter my content and on matches on flow I would like to change my html structure, but my rule doesn't really apply. I have the following filter which searches the first image of posts and on rule match attaching a css container. The `preg_match_all` is working but the `str_replace` doesn't
function imageFooter($content){
global $post, $posts;
preg_match_all('/<a.href="(.*?)"><img.*?src="(.*?)".*?><\/a>/', $post->post_content, $matches);
$to_search = $matches[0][0];
$replacement = '<div class="image_footer">'.$matches[0][0].'<span class="logo"></span></div>';
str_replace($to_search , $replacement, $post->post_content);
return $content;
}
add_filter('the_content', 'imageFooter'); | Change,
str_replace($to_search , $replacement, $post->post_content);
to..
$content = str_replace($to_search , $replacement, $post->post_content); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, filters"
} |
Favicon does not showup
I activated the All in one Favicon and then uploaded my Favicon in the settings but it does not show up in any browser (my under construction site: <
Any help will be highly appreciated. | You have to delete de cache of your browser | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "favicon"
} |
Website Address Keep redirect to website after migration attempt
I have a loclhost site that I heard I can migrate the site by just copy and paste the whole site from local to host if I changed WordPress Address (URL) and Site Address (URL) to my current hosted site address and then upload it to the host (which I am doing now)
Problem is that now when I try to login my local site it will always redirect to my actual website.
How can I fix my loclhost site setup so it back to its original loclhost address?
============UPDATE==================================== Added below files into the wp-config of the Wordpress:
define('WP_SITEURL', '
define('WP_HOME', '
Result: When try to login, the page will still be directed to the actual website not my local site....
Help plz | It sounds like you change the configuration on the local server. You need to put it back. that local configuration information needs to remain unchanged if you intend to continue working on the local copy, which you should. Breaking a local development version of the site is a lot less painful than breaking the live version. :)
The easiest way to sort this out is to add the following two lines to your `wp-config.php` file on your local server.
define('WP_SITEURL', '
define('WP_HOME', '
Obviously, the domain needs to be changed-- probably to `localhost` but if the local server has a static (internal) IP using the xxx.xxx.xxx.xxx IP is better.
I don't know what else you did so there may be more steps but I hope that fixes it.
For reference:
1. <
2. < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "urls, migration"
} |
is_home() returns TRUE on page template
I'm wondering why my link: ` returns TRUE on `is_home()` usage:
if(is_home()){
var_dump(is_home());
die('test');
}
It clearly has template-mycustomtemplate.php set under Pages > This Page in Admin Panel. Can anyone shed some light on that?
UPDATE: it returns TRUE in the loop but FALSE outside the loop. So, I can use workaround but nonetheless, it looks like a bug to me if it returns TRUE in the loop that is present in that template file. | I discovered that it isn't actually a bug. In the loop `is_home()` will refer to the currently looped object and not to the page that you accessed. In fact that's handy! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "pages, templates, homepage, template hierarchy"
} |
WPML icl_register_string() throws fatal error but works
I'm helping someone with a custom plugin and they need it to be WPML compatible. Using the method from WPML I was able to register a string in WPML and output it on the other end. However, when the plugin was initially activated I got a **Call to undefined function icl_register_string()** error. It worked, but threw a fatal error. Any idea why this could be? Source: <
Here's my code:
//Register Settings with WPML
icl_register_string( 'Match Previous Order' , 'match_order', 'Do you want these items to match a previous order from Direct Linen? If yes, use "Additional Notes" to explain.' ); | You should always use the wpml functions as following: (the HowTo linked by you actually suggests this :-)
if( function_exists('icl_register_string') ) { icl_register_string( 'Match Previous Order' , 'match_order', 'Do you want these items to match a previous order from Direct Linen? If yes, use "Additional Notes" to explain.' ); }
This will ensure that you won't get any errors in case WPML doesn't exist in a Wordpress Installation or WPML wasn't fully loaded before your code is run (this is the case when your plugin is activated). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "translation, plugin wpml"
} |
Loading bbPress CSS file only on forum directory
I added bbpress forum pluggin in my site to handle discussions, forum or comments. The bbPress CSS file is added to every page of my blog. Now, I want to load it only on forum directory to consider page speed. Is there any way to do this? | The styles are enqueued in the function `enqueue_styles()` inside the file `/wp-content/plugins/bbpress/templates/default/bbpress-functions.php`.
It's a matter of using `is_bbpress()` and `wp_dequeue_style`. Only one of the styles is enqueued, but here we're removing all 3 possibilities.
add_action( 'wp_enqueue_scripts', 'bbpress_enqueue_wpse_87081', 15 );
function bbpress_enqueue_wpse_87081()
{
// Check if bbpress exists
if( !function_exists( 'is_bbpress' ) )
return;
if( !is_bbpress() )
{
wp_dequeue_style('bbp-child-bbpress');
wp_dequeue_style('bbp-parent-bbpress');
wp_dequeue_style('bbp-default-bbpress');
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, bbpress"
} |
Custom title, Bones theme
I'm a total wordpress noob and ran into my first problem. I downloaded this theme.
My question is how do I change how the `p#logo.h1` is shown. I would like to put a `<br />` in the middle of my title, and half in a custom .
So the html of the title should be something like:
<p id="logo><h1>This is a<br /><span id="customtitle">Big title</span></h1></p>
How can I change that? | In your header.php file, replace this line:
<p id="logo" class="h1"><a href="<?php echo home_url(); ?>" rel="nofollow"><?php bloginfo('name'); ?></a></p>
with your custom line:
<p id="logo><h1>This is a<br /><span id="customtitle">Big title</span></h1></p> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "customization, title"
} |
Echo custom taxonomy term name
I would like to echo out the term name from a custom taxonomy `'recipes'` but all I get is the word "recipe" when it should say eg "pizza recipe". Is `name` the right argument here or I am mistaking it for `slug`?
<?php
$term = get_terms( 'recipes' );
echo '<div class="title">' . $term->name . 'recipe</div>'; | I managed to solve this and I will post the answer:
<?php
$args = array('number' => '1',);
$terms = get_terms('recipes', $args );
foreach( $terms as $term ){
echo '<div class="title">' . $term->name . 'recipe</div>';
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "custom taxonomy, terms"
} |
Why is this function crashing my wordpress installation?
I'm new to wordpress and programming in general. For my first site there is a custom template in which I want to load a javascript library. After registering and enqueueing it in functions.php my site no longer loads properly. I'm sure what it is simple mistake and would really appreciate a little help. For the record, I'm using a child theme of twentytwelve.
Here is the code:
<?php
function load_wforms() {
if (is_page(45)) {
wp_register_script('wforms', get_stylesheet_directory_uri().'/js/wforms.js'), false, '2.0');
wp_enqueue_script('wforms');
}
}
add_action('init', 'wforms');
?>
Thanks! | First, be sure to enable `WP_DEBUG` in your `wp-config.php` file, so that you can see fatal error messages.
In this case, the problem is that you've named your function `load_wforms()`, but you reference the callback `wforms` in your `add_action()` call:
function load_wforms() {}
...vs...
add_action('init', 'wforms');
The second parameter, `wforms`, refers to a function named `wforms()` \- but your function is named `load_wforms()`. Change your add_action to this:
add_action( 'init', 'load_wforms' );
(Side note: you should enqueue scripts at `wp_enqueue_scripts`, rather than `init`.)
## Edit
Also: fix the syntax error as noted by @milo in his comment:
wp_register_script('wforms', get_stylesheet_directory_uri().'/js/wforms.js'), false, '2.0');
You have an extra parenthesis:
'/js/wforms.js')
...should be:
'/js/wforms.js' | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, wp enqueue script"
} |
Change Category Slug Redirection
Hi if I change the category slug of one of my categories, does WordPress automatically handle redirects from the old category slug to the new one? | No, WordPress only handles changes of individual post slugs, by saving old slugs in post meta.
You could try a plugin, like Redirection, to handle old category slug 301 redirects. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "redirect"
} |
Destination directory for file streaming does not exist or is not writable
I am trying to upgrade my version of Wordpress but I get this error:
_Destination directory for file streaming does not exist or is not writable._ | This is a read-write permission error. Fix this by changing the "wp-content" folder's permissions to **755**.
If this doesn't work checked the wp-config.php file and if it's not already defined, add
`define('WP_TEMP_DIR', ABSPATH . 'wp-content/');` | stackexchange-wordpress | {
"answer_score": 42,
"question_score": 19,
"tags": "permissions, upgrade"
} |
Should I ask a theme developer to use locate_template rather than require_once
I was creating a child theme today and needed to overwrite a php file which was included using this code in the themes functions.php file
`require_once( get_template_directory() . '/function-includes/theme-functions.php' );`
I tried using `require_once( get_stylesheet_directory(). '/function-includes/theme-functions.php' );` in my child themes functions file but it caused an error and didn't load the site at all.
So I ended up using `locate_template( '/function-includes/theme-functions.php', true );` in the parent themes functions.php file
Is `locate_template` a better method for theme developers to use to allow child theme development?
Is there an alternative way for me to use only my child themes functions.php to overwrite that theme-functions.php file? | Generally speaking, Child Themes were originally intended to be able to do two things:
1. Override parent Theme CSS
2. Override parent Theme _template_ files
I doubt that the Theme developer intends for the `/function-includes/theme-functions.php` file to be overridden by a Child Theme. Functional files are usually a core component of the Theme, and allowing a Child Theme to override them wholesale would introduce serious development complexity into the Theme.
Rather than ask for a functional file to be able to be overridden by a Child Theme, I would instead ask the developer to make custom function output _filterable_ , or (where appropriate), to make some custom functions _pluggable_ (by far, I prefer filterable function output to pluggable functions). | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "functions, child theme, parent theme"
} |
WordPress Theme activation hook?
I know the many tricks to see if said theme is activated, I have scoured the internet. I am not looking for re-pasting of that code. What I am looking for though is weather or not 3.3-3.5 released a new function that does something upon theme_init, I saw some sort of hook, but I can't remember where, in the codex, dealing with doing things after a theme has been initialized..
Any one know? | You might be looking for the `after_setup_theme` hook:
< | stackexchange-wordpress | {
"answer_score": -3,
"question_score": 13,
"tags": "themes, init"
} |
How would I use a media query to make my entire theme responsive or fluid?
I've settled on a theme for one of my blogs. Is it possible to just wrap your stylesheet (style.css on most themes) in @media queries, and make your entire theme **responsive** , or **fluid** , so it **works well on all browsers and screen resolutions**?
If so, does anybody know how I can accomplish this? Or is there a better, easier way to accomplish this?
I mean, can I just put this at the top of my style.css?
@media screen and (max-height: 700px) {
// style.css rules
and of course at the very bottom, just:
}
Will this make my entire theme fluid or responsive, or is it much more in-depth than that? Any guidance in this regard would be greatly appreciated! | You can use media queries to change the styling per element depending upon specifications. You would have to add these to the bottom of your stylesheet, so that it overwrites your default styles depending upon the screensize
This following media-queries template from bootstrap is only based on screen size. You can use more complex media-queries to target specific device as well.
To Support older browsers (IE), you'd have to use conditional statements to include respond.js or media-queries.js . Media queries will only work with device specifications such as screen, handheld etc...
A great place to start is: <
Eg: Bootstrap Media queries. /* Large desktop */ @media (min-width: 1200px) { ... }
/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }
/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }
/* Landscape phones and down */
@media (max-width: 480px) { ... } | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "css, responsive"
} |
Add_image_size not cropping
I want to make a crop on the images of my blog page that have more than 443px adjust it to 645x443 size, exactly.
I used this code:
add_theme_support ('post-thumbnails');
add_image_size ('blog-page', 645, 445, true);
However, the image is resized instead of making the crop.
Exemples:
Original image: <
How is: <
How i want: <
How do I do this? | From this comment:
> Sry, i forgot it, but i want size of 645x445, exactly, and that image dont have it. The width of it is 588px. Look: img201.imageshack.us/img201/4728/40405258.png Wordpress need make a zoom on it.
WordPress does not zoom. It only crops. If you want an image to have a custom intermediate size, then you must upload an image with dimensions greater than or equal to the dimensions specified in your `add_image_size()` call.
Also: if you have uploaded images prior to adding your `add_image_size()` call, then you will need to regenerate your intermediate image files in order for WordPress to create images using your custom size. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "thumbnails, images, cropping"
} |
Thumbnail with different sizes
I want make all my blog thumbs the size of 227x133. I need images width have 100% (for responsive design). Some images have width greater than the other and vice versa.
I'm using this code to show the thumbs of my blog:
/ / Post thumbnails sizes
add_theme_support ('post-thumbnails');
add_image_size ('blog-page', 9999, 545, true);
The problem is that the images are not the same size as each other:
How is: <
How I want: <
What's wrong? | Intermediate image sizes are discrete, not variable. When you define an image size, with specific dimensions (whether hard-cropped or box-resized), WordPress will create a discrete image, with the specified dimensions.
Otherwise, if width could be defined dynamically, WordPress would have to create a prohibitively large number of images, just to account for responsiveness.
To account for responsive design, you'll have to use CSS. The easiest way to do so is using a rule similar to the following:
#content img {
max-width: 100%;
height: auto;
}
That way, if the #content div is resized, your post images will be resized along with it, while maintaining their aspect ratio. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, post thumbnails, images"
} |
Prevent creating multiple image resizes in twentytwelve template
I am using wordpress twentytweleve template and I notice every time I upload an image it creates 3 different thumbnail sizes. In my media settings I have already set medium & large size to 0. It seems like when I use this theme it will create the 3 different thumbnail sizes but if I use my own custom theme it doesn't create those 3 different sizes. How can I fix this in twentytweleve template? | Create child theme for Twenty Twelve and add code in How to disable multiple thumbnail generation? to functions.php | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, templates, images"
} |
Using Add from Server to upload by post ID
I am using Add From Server plugin < basically it imports/upload image from the server. Currently the plugin copies the images into month/year folder format but I want to change it by making it copy by the Post ID folder format instead of month/year.
I have already tried using the Custom Upload Dir plugin but it doesn't work with Add From Server plugin together. Can anyone tweak Add From Server plugin to make it upload by Post ID? | You can try to add this into your `functions.php` file:
add_filter( 'upload_dir','wpse87234_upload_dir');
function wpse87234_upload_dir($uploads){
// check if we are in the "Add From Server" media tab
if (isset($_REQUEST['post_id']) && isset($_GET['tab']) && $_GET['tab']=="server") {
$prefix="post_";
$post_id=(int)$_REQUEST['post_id'];
// change the uploads info to our needs:
$uploads['subdir']="/".$prefix.$post_id;
$uploads['path']=$uploads['basedir'].$uploads['subdir'];
$uploads['url']=$uploads['baseurl'].$uploads['subdir'];
}
return $uploads;
}
This should give directory like `/wp-content/uploads/post_1234/` with `post_id` 1234. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "uploads"
} |
Genesis Child Theme Modifying Comments display
I'm using a theme which works with Genesis Framework. The theme is called pinsomo & I'm wondering how to "move" comments count div to the bottom of the post.
Here is the demo: [[link has expired]]
You see the comment icon next to the title. I want to move it to the heart icon. | You can use the genesis_post_info and genesis_post_meta filters in your child theme rather than modify the parent theme frameworks files which will be lost when you update Genesis.
Remove comments link from post info
add_filter( 'genesis_post_info', 'remove_post_info_comments_link' );
function remove_post_info_comments_link($post_info) {
$post_info = '[post_date] by [post_author_posts_link] [post_edit]';
return $post_info;
}
Add comments link to post meta
add_filter( 'genesis_post_meta', 'add_comments_post_meta' );
function add_comments_post_meta($post_meta) {
$post_meta = '[post_categories] [post_tags] [post_comments]';
return $post_meta;
}
**Note:** This code only works with themes running HTML 5 markup. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments, genesis theme framework"
} |
Do I need to use The Loop on pages?
I'm writing my first WordPress theme and have a question about the use of The Loop in page templates. The page templates I've looked at all follow basically the same pattern (example from Twenty Twelve):
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php comments_template( '', true ); ?>
<?php endwhile; // end of the loop. ?>
But a page will only have one post associated with it so iterating through the posts seems unnecessary. My page template is more readable and seems to work fine:
<?php
the_post();
the_title('<h1>', '</h1>');
the_content();
?>
Is this a good practice? Are there any downsides? | According to the Theme Guide, full loops should be used, even on single templates.
> Full loops must be used in all templates. Just calling `the_post()` in a template like `single.php` or `page.php` is not enough.
So yes, it's a best practice to use full loops. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 8,
"tags": "loop, page template"
} |
order by meta_value serialized array
Hi I'm trying to pull posts using the wp query. Just one problem--I am trying to sort the posts alphabetically by a certain meta_value. Thing is that this meta_value is a serialized array. Is there an easy way to do this without having to unserialize it? Thanks!
a:1:{i:0;a:1:{s:7:"people";s:16:"Tanya Garca";}}
Btw, I cannot change the way the meta_value is being saved because I am using this plugin which automatically saves it serialized. | > Is there an easy way to do this without having to unserialize it?
Not in any reliable way. You can certainly `ORDER BY` that value but the sorting will use the whole serialized string, which will give you technically accurate results but not the results you want. You can't extract part of the string for sorting within the query itself. Even if you wrote raw SQL, which would give you access to database functions like `SUBSTRING`, I can't think of a dependable way to do it. You'd need a MySQL function that would unserialize the value-- you'd have to write it yourself.
Basically, if you need to sort on a `meta_value` you can't store it serialized. Sorry.
If you can't change how the value is stored you will need to pull your posts, loop through them to sort them, then loop through them again to display the sorted results. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom post types, custom field, query posts, meta query"
} |
All in one calendar custom post type query doesnt work as expected
I did a custom post query for AIO Events Calendar, as described here: All in One Calendar Plugin Custom Post Type Query
But it doesnt work.
<?php echo esc_html( $event->cost ) ?>
returns the cost, but
<?php echo $contact ?>
and any other variable without $event-> returns nothing. | Anything that comes out of this query-- `$event = Ai1ec_Events_Helper::get_event($post->ID);`\-- will need the `$event->` part. That is how you access data from an object. That is just pure PHP.
I don't know why some of the values in that answer, like `$contact`, are not prefixed with `$event->` but I am assuming those variables do not come from from that query.
Add `var_dump($event);` immediately after `$event = Ai1ec_Events_Helper::get_event($post->ID);` and you can see what information is in that object. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, query, calendar"
} |
wordpress loop and template files
I am curious how WordPress know that if I have a category.php and do the basic loop inside there that when I click on category A I get all of A's posts. The reason I ask, is because I have seen themes that just have an index.php and when you click on Category A in those themes you get all of A's posts, and they do not have a category.php file.
Is there a trick to achieve this?
because if you do:
category.php and inside that do:
if(have_posts()){
while(have_posts()){
the_post();
}
}
You will get all posts for any category link you click on. How ever, as stated some people only have index.php in their theme and when you click on a category link you get all posts for that category, regardless of category clicked on.
Much like global post_id is there a global category_id to query against? | If you look at the template hierarchy for categories you will see it follows:
1. category-{slug}.php
2. category-{id}.php
3. category.php
4. archive.php
5. index.php
As Milo says these templates are just using the loop to display what is already queried, so there template itself does not matter outside load order of the hierarchy. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "loop"
} |
How can I style an IFRAME element that has a constantly changing class name?
On my blog, the Pinterest button creates a small gap underneath the footer. Looking at the code, the cause is the iFrame that the Pinterest javascript embeds in the page. It looks like this:
<iframe src="//assets.pinterest.com/pidget.html?r=862117.4577227819#via=http%3A%2F%2Flocalhost%3A8888%2Finternet-security%2F&type=pidget" height="0" width="0" frameborder="0" class="PIN_1361148986939_log"></iframe>
I can use Chrome's dev tools to apply display: none; to it, but here's the problem: The class changes every time you load the page.
Is there a way to targe this specific iFrame in CSS without using the class name? | You can select every iframe, just by writing:
iframe{display:none}
If you have multiple iframes, and this is the only one you want to apply this styling to, you can write something like this:
iframe[src^="//assets.pinterest.com/pidget.html"]{display:none}
Note: Not really a WordPress question, but pure CSS related. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, embed"
} |
Redirect certain pages if user logged in
how would one go about redirect certain pages if the user viewing them is logged into the WordPress CMS? For example, we have 2 registration pages that when logged in should direct to some other page / category archive.
Thanks. | $location = The absolute URI to which the user will be redirected. No default. $status = The status code to use. For example, 301, 302, etc. The default is 302. You can use template tags for the $location parameter, for example:
<?php // redirect to the home page
wp_redirect(home_url()); exit; ?>
<?php wp_redirect(' 301); exit; ?>
If user is logged in
<?php if (is_user_logged_in() ) {
wp_redirect ( home_url("/pagename") );
exit;
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "redirect, login"
} |
Disable registration on certain condition
I have a certain condition in my code (if the user is visiting the page from a network range) and I can ask for this condition easily, let's say:
if ( $user_in_allowed_range)
What I want is to offer the registration button only to users who fulfill this condition, and other users should still be able to login.
Is there any way to do this in WordPress without hacking the core? An additional custom login form is not a solution as the original one is still available.
I found some hooks (`login_form`, `login_head`, `user_register` …) and the theme function `wp_login_form()` but they do not offer my needed feature. | Since `get_option('users_can_register')` will return the setting value for the "Anyone can register" setting used for displaying the registration link, you could probably add a `get_option` filter overriding the value for the `users_can_register` key. In this case i even think the `pre_option_%s` filter is your best bet, since the actual value of the settings is irrelevant. Something like this might work:
add_filter('pre_option_users_can_register', 'wpse_87341_users_can_register');
function wpse_87341_users_can_register() {
// Obviously here you'd populate $user_in_allowed_range
// ...
return intval($user_in_allowed_range); // We need to return an int since get_option does not like false return values
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "login, user registration"
} |
Wordpress Media Manager 3.5 - default link to
Media Manager once again. This time I'm looking for a simple hack/hook/filter to change default "Attachment Display Settings" from media manager. The option is "Link To" that is default set to "Media File" and I would like to force it for all users to be default set to "none".
!Media Manager Screen
If there is no way to do it with hook/filter (media-template.php lines 282 - 306) - is there a way to attach jQuery file to Media Manager and use it to force change option after Media Manager is loaded? | You can do what you want by overriding appropriate Backbone view, which is responsible for rendering attachments display settings form.
**plugin.php**
add_action( 'load-post.php', 'wpse8170_media_popup_init' );
add_action( 'load-post-new.php', 'wpse8170_media_popup_init' );
function wpse8170_media_popup_init() {
wp_enqueue_script( 'wpse8170-media-manager', plugins_url( '/js/media.js', __FILE__ ), array( 'media-editor' ) );
}
**media.js**
(function() {
var _AttachmentDisplay = wp.media.view.Settings.AttachmentDisplay;
wp.media.view.Settings.AttachmentDisplay = _AttachmentDisplay.extend({
render: function() {
_AttachmentDisplay.prototype.render.apply(this, arguments);
this.$el.find('select.link-to').val('none');
this.model.set('link', 'none');
this.updateLinkTo();
}
});
})(); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 7,
"tags": "media, media library"
} |
Different functions file for each site in multisite installation?
I'm trying to create two (for now) sites in multisite WP installation that use same theme, but require somewhat different functionality i.e homepage has a bit different layout and there will be some CSS changes.
Is there a way that I could use to override functions.php and other theme files for each site? | I would recommend a Parent/Child theme for this. Read the section linked below for a good example of making functions within your theme pluggable.
< | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "functions, multisite"
} |
Order post by date with ACF
I implemented a custom post type for a class post. Now every post has a additional date picker called "date_event", my question is: Any have ideas how can i order the post for the last date of the label date_event?
Thank you for your help. | This comes directly from the ACF documentation:
/*
* Order Posts based on Date Picker value
* this example expects the value to be saved in the format: yymmdd (JS) = Ymd (PHP)
*/
$posts = get_posts(array(
'meta_key' => 'custom_order', // name of custom field
'orderby' => 'meta_value_num',
'order' => 'ASC'
));
if( $posts )
{
foreach( $posts as $post )
{
setup_postdata( $post );
// ...
}
wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, date, advanced custom fields"
} |
WP_Query: Fetch posts that are in (category1 and not in category2), OR posts that are not in cagegory1
I have two categories that will always stay the same. They are called "Events" and "Show on frontpage". The latter is a child category to Events.
What i want to do is, when fetching posts (using WP_Query), check if the post is in the Events category. If it is, and it is NOT in the "Show on frontpage" category, don't fetch the post at all.
Scenarios:
- post is in Events but NOT in Show on frontpage: Don't fetch post
- post is in Events AND in Show on frontpage: Fetch post
- post is NOT in Events: Fetch post
The goal is to achieve the functionality only using WP_Query. Maybe it's possible using some special `category__in` or `category__not_in` queries or something. The trick is to kind of have an `if` statement inside the query, because there are three possible scenarios.
Ideas? | Here we go, try a tax_query instead <
...
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'event','show_on_front' ),
'operator' => 'AND',
),
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'event' ),
'operator' => 'NOT IN'
)
) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, categories, wp query"
} |
Import media to online WordPress from local development
I have a site being developed locally and I want to import the contents to an online installation. I used wordpress "import" but it cant get the media files. Is there any "wordpress" was of doing this or will I have to get access to my LDE from outside or upload the entire installation which I would rather avoid? | When I use WordPress Import in this cases, this is what I do:
* Export the XML in localhost.
* Open the exported file in a text editor.
* Search and replace ` for `
* Upload the `uploads` folder via FTP to the `custom-temporary-folder`.
* Perform the Import in `example.com` using the modified XML file. | stackexchange-wordpress | {
"answer_score": 21,
"question_score": 7,
"tags": "theme development, media library, import"
} |
Adding short codes from a page's content on header and hiding the same from page's content
I have created a page and added the following shortcode from wp-orbit-slider
[orbit-slider category="test"]
I want the contents of
[orbit-slider category="test"]
be displayed on the header part, instead of on the content area part, which the wordpress usually does . I tried adding the the short code on header.php and it works, but the same content will be duplicated on the content area also. I need to avoid this. How can this be achieved ? | This might work for you, trying to hook early to `the_content` filter to strip the shortcode tag from it:
add_filter('the_content', 'ad_filter_the_content',1,1);
function ad_filter_the_content($content) {
// specify page id or array of page ids to include
if (is_page(5)) {
return str_replace('[orbit-slider category="test"]', '', $content);
}
return $content;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "shortcode, templates, content"
} |
What happened to the media manger?
Since WP 3.5 (right?), the media manager has been "streamlined" and images are no longer, as I can see it, ordered by year / month in the media manager, although they are still saved as before.
Is there any way I can use a hook (or something) to display folders in media manager? | The answer is obvious: no, you can't. Why? Because there is no folders in database for media attachments, all media files are stored as single row in `wp_posts` table.
I suppose it does not really matter where your media files are stored, it could be your hosting or CDN network, somebody else hosting, etc :) So there is no logical folders. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "images, media library"
} |
Can I simulate a user being logged in from a WP_UnitTestCase?
I have some logic in my code that's based on whether or not the user is logged in. How do I test it from my WP_UnitTestCase? | Call wp_set_current_user($id) to make a user ID the currently logged in user. | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 6,
"tags": "unit tests"
} |
How to carry over existing wp users to a new buddypress installation
I had made a community with a different plugin (I think it was mingle. I recently installed buddypress, removed mingle and changed the site to suite. Now the problem is the existing users are not listed as members in the members page, only me, the admin. I have looked for, but not found, a solution. i am know how to use Wordpress but this one has stumped me. This may be an easy question for all those experienced buddypress users out there, but I am just starting, so keep that in mind before you say how completely dumb I am :)
Thanks for taking the time to read this. | The following plugin will make all WordPress users to appear on BuddyPress members directory. It doesn't provide full migration of users, but it will update the `last_activity` user meta field that is used by BP to display users.
This is a plugin code, so you need to create a new php file (eg. `bp-add-users.php`) and upload it to plugins directory of your WP installation `wp-content/plugins`. When you _activate_ the plugin it will update all users, after that you can deactivate and delete:
/*
Plugin Name: BP User Updater
Description: Update `last_activity` user meta for all users.
Author: Ahmad M
*/
register_activation_hook(__FILE__, 'add_users_to_bp');
function add_users_to_bp() {
$users = get_users();
foreach ($users as $user) {
update_user_meta($user->ID, 'last_activity', date("Y-m-d H:i:s"));
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "buddypress"
} |
Getting taxonomies specific to categories
I have categories set up for car manufacturers.
I have 4 custom taxonomies that are also set up: color, starburst, offer_type, and logo_count.
Each post I upload to my wordpress has values for all 4 of those taxonomies and is assigned a category. I have a custom page template setup to display all posts that have the same category as the current page's slug.
query_posts:
<?php query_posts('category_name='.get_the_title().'&post_status=publish,future&posts_per_page=-1');?>
My end goal is to display the taxonomies in the sidebar and allow users to visit a manufacturer's page, and filter the content they want to see based on their selections in the sidebar.
I know how to display the taxonomies in the sidebar, I'm just not sure how I would have the content filtered. | Found an answer to my own question. Still not sure how to implement it myself, but a plugin does this perfectly. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "custom taxonomy, query posts, taxonomy, sidebar"
} |
Bloginfo hook - can it be more precise?
From the codex, regarding filter hooks:
bloginfo_url
applied to the the output of bloginfo("url"), bloginfo("directory") and bloginfo("home") before returning the information.
Is there a way I can specify that a bit more precise? So that I can hook something only to `bloginfo("url")` for example? | You can access that, using the additional variable in the Filter Functions.
The Filter `bloginfo_url` uses the `$show` parameter (the parameter you use when calling `bloginfo`) and passes it to `apply_filters`.
So hooking into `bloginfo_url` should be no problem, you just have to make a switch inside the function, and it only applies to e.g. `url` .
This would be the Code for you:
add_filter('bloginfo_url', 'f711_bloginfo_url_filter', 10, 2 );
It tells you where you hook into, the callback function, the priority in which it is applied compared to other filters, and the number of arguments that can be passed to the function. This is your important part, as 1 is the standard value.
In the Callback Function:
function f711_bloginfo_url_filter( $output, $show ) {
if ( $show == 'url' ) {
$output = "this";//whatever you want to do with it
}
return $output;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "hooks, bloginfo"
} |
How do i get a specific user metadata using custom metavalue outside of wordpress?
I need help. I need to get a user ID or email (email is can do but ID is better) based on their phone number, outside of WordPress. I already have their phone number in a variable and billing_phone is custom metadata in the wp_users table. This is what I am using to load wp
`$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] ); require_once( $parse_uri[0] . 'wp-load.php' );`
and how I am fetching the email.
`$email = $wpdb->get_var("SELECT user_email FROM wp_users WHERE billing_phone = $phone_number ");`
Thank you all in advance. Any help is appreciated. | If you have `billing_phone` as user meta, which is the preferred way, that query would be incorrect. The advantage of utilizing custom user meta and adding a field for `billing_phone` would allow you to use `get_users()`.
$user = get_users('meta_key' => 'billing_phone', 'meta_value' => $phone_number, 'fields' => 'ID');
The above would give you an array of User IDs that have the matching `billing_phone` meta value. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, user meta, outside wordpress"
} |
Posts being viewed
I am looking for a way to list posts being viewed but I can't find anything online.
Is it even possible? I've seen some websites that have these loops, "What other readers are currently reading".
I'm using the following loop to list random set of videos
<?php
if ( is_home() ){
$cat = get_query_var( 'cat' );
query_posts(array('orderby' => 'rand', 'showposts' => 10, 'cat'=>$cat));
}
while (have_posts()) : the_post();
?>
How can I show posts being viewed? anyone | I would suggest a way to implement this to be in the post template have a call that updates post meta with the current timestamp. Then you can show posts that have been viewed recently by querying meta data for all values within a certain time range ordered by that timestamp. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "query posts, get posts, views"
} |
How to Display Frontend CSS for Administrator only
I've been asked to restyle the css of a WordPress website frontend. The website can't be in maintenance mode while working on it as it must stay up and running all the time. I assume that if I can add a small and unobtrusive condition in the header allowing the administrator to see a different css file than the users, I could edit the css and test the result while the users still see the original version of the website. This way I could work on the design without anyone noticing.
Can anyone tell me which WordPress function I should call on the header to switch the css file if and only if the user is an administrator?
The best would be not to edit the "functions.php" file or activate any plugin as I really don't want to mess with the website as it is (few chances but chances anyway). I would rather edit the "header.php" file in the theme folder in order to be sure nothing bad happens.
Thank you. | You should be able to simply check the capabilities of the currently logged in user. If they're an administrator the following example should do what you want it to. Just add this into your theme's functions.php file.
Please note this code is untested, but it should get you where you want to be. If the level_10 capability doesn't work you can check out the documentation for other user levels and capabilities here.
add_action( 'wp_enqueue_scripts', 'admin_only_stylesheet' );
function admin_only_stylesheet() {
if ( current_user_can('level_10') {
wp_register_style( 'admin-only-style', get_template_directory_uri() . '/css/admin-frontend-style.css', array(), '12345678', 'all' );
wp_enqueue_style( 'admin-only-style' );
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, admin, css, maintenance, switch"
} |
Outputting content from page
I'm trying to display a title, featured image, and content from a page into a new template (that will contain content from several pages). I tried to just echo the variables as shown below, but right now it's only display the content and title+"array". Any ideas?
Here is my current array:
<?php
$id = 2131;
$post = get_page($id);
$content = apply_filters('the_content', $post->post_content);
$title = $post->post_title;
$image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'single-post-
thumbnail' );
echo $content;
echo $title;
echo $image;
?> | **wp_get_attachment_image_src returns an array** , not a single value. Please refer to this article for more info: wordpress.org/Function_Reference/wp_get_attachment_image_src
**Default Usage**
<?php
$attachment_id = 8; // attachment ID
$image_attributes = wp_get_attachment_image_src( $attachment_id ); // returns an array
?>
<img src="<?php echo $image_attributes[0]; ?>" width="<?php echo $image_attributes[1]; ?>" height="<?php echo $image_attributes[2]; ?>"> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, post thumbnails, page template"
} |
Removing Submenu from Menu
Thesis appears to automatically add the sub-menus (sub-menu ul) to menu parents if childs exists. I have a specific need to remove this html from a particular menu.
The menu name is: second_level
Not sure if there a hook to do this.
I'm trying to remove these from the menu name above.
<ul class="sub-menu">...</ul>
I'm not trying to remove the class but the UL's. | You can change nav menu args via the `wp_nav_menu_args` filter.
So let's say you have a theme that does something like this...
<?php
wp_nav_menu(array(
'theme_location' => 'second_level',
'depth' => 2, // how many levels to show
// prolly some other stuff here
));
You can hook into `wp_nav_menu_args`, check for the theme location, and set depth to be 1 and remove submenus.
<?php
add_filter('wp_nav_menu_args', 'wpse87565_change_depth');
function wpse87565_change_depth($args)
{
if (!empty($args['theme_location']) && 'second_level' === $args['theme_location']) {
$args['depth'] = 1;
}
return $args;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, themes, hooks, sub menu, theme thesis"
} |
Get all posts containing a shortcode
I'm writing a WP plugin that involves using shortcode. One of the missions is to display all (publish) posts that contain my shortcode regardless of their post type. Is there a built-in function for this?
Thanks in advance. | WordPress isn't aware of your shortcode until it's rendered on the front end. So when WP sees it in the content and replaces it, that's when it's aware that your shortcode exists. It also promptly forgets about it afterward, of course.
So there's no built in function to do what you're asking. The best you can do is probably write a `LIKE` query which may or may not be a good idea.
<?php
function wpse87582_find_shortcode_posts()
{
global $wpdb;
return $wpdb->get_results("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%[your_shortcode_here%'", ARRAY_N);
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "shortcode"
} |
Saving into post_excerpt or post_content
When importing a feed into a custom post type does it make any difference if I store the feed description in the post_excerpt field versus the post_content field? Is there some processing that gets applied via WordPress when I save content to any of those two fields? | There is no difference in storing data into the `post_excerpt` field versus the `post_content` field.
If you look at the source code (line 2700) you will notice both `post_excerpt` and `post_content` won't be filtered. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "database"
} |
Most Wordpress sites causing realpath errors
recently installed some debugging software on our server and realised that most errors are coming from realpath() in Wordpress sites.
realpath() [<a href='function. realpath'>function. realpath</a>]: open_basedir restriction in effect. File(/var/www/vhosts/ xxx. com) is not within the allowed path(s): (/var/www/vhosts/ xxx. com/httpdocs/:/tmp/)
The sites are working OK but these are bugging me. Mostly because its hard to see any serious errors coming up!
Would errors like this also affect performance? | Looks like you are using one of the hacks to have the same wp-config.php file in development and deployment environments. AS it is noted at the end of that page, the hack were not tested in restricted environments like your. If you are not in development phase anymore then you should change your code in wp-config.php and manually set the constants instead of relying on location detection. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "internal server error"
} |
Autosort uploads in galleries by filename
A client of mine wishes to not have to sort images uploaded into a post gallery, but instead rely on its filename for sorting (e.g. "01_sample.jpg", "02_sample.jpg"). This would save a lot of time for the client, and I'm wondering if this is possible to achieve using WP 3.5+ and the recent changes to Add Media? | When you or the client add the gallery shortcode, you can add an "orderyby" option to specify the order of the images. Per the Codex page on the gallery shortcode:
[gallery ids="729,732,731,720" orderby="title"]
... will do what you're wanting. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "images, uploads, gallery, sort"
} |
Gravity forms - Can I have multiple custom spinners?
I wish to change the default ajax loader for gravity forms. I have done this using the following code (link found here):
add_filter( 'gform_ajax_spinner_url', 'cwwp_custom_gforms_spinner' );
/**
* Changes the default Gravity Forms AJAX spinner.
*
* @since 1.0.0
*
* @param string $src The default spinner URL
* @return string $src The new spinner URL
*/
function cwwp_custom_gforms_spinner( $src ) {
return get_stylesheet_directory_uri() . '/assets/img/css/newsletter-loader.gif';
}
This seems to work fine. What I would like todo is set **another** custom ajax spinner for a different form on a different page. The design of the page is different and I would like to set a different spinner. Any ideas how I do this? | Without testing, this should work (still use the add_filter bit):
function cwwp_custom_gforms_spinner( $src ) {
global $post;
if( $post->ID == $id ): // use whatever page identifier/conditional you like here: ID, template used, slug etc.
// other identifiers would probably be better and won't rely on global $post
// for example is_front_page(), is_archive(), etc
return get_stylesheet_directory_uri() . 'path/to/spinner/1.gif';
else:
return get_stylesheet_directory_uri() . 'path/to/spinner/2.gif';
endif;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugin gravity forms"
} |
WP_Query: query posts by ids from array?
I did quite a bit of research but can't figure why this wouldn't work for me?
echo print_r($rel); // Array ( [0] => 63 [1] => 87 )
$args = array(
'post_type' => array( 'post' ),
'orderby' => 'ASC',
'post_in' => $rel
);
$loop = new WP_Query( $args );
I don't get any posts returned? Any ideas how to only get the posts with the ids in the array? | You have to use `post__in` (double underscore) argument, instead of `post_in`:
echo print_r($rel); // Array ( [0] => 63 [1] => 87 )
$args = array(
'post_type' => array( 'post' ),
'orderby' => 'ASC',
'post__in' => $rel
);
$loop = new WP_Query( $args );
If you are unsure why an argument is not working, copy it's key name from manual and past it into you snippet. | stackexchange-wordpress | {
"answer_score": 13,
"question_score": 5,
"tags": "wp query, loop, query"
} |
get_the_excerpt() with fallback like the_excerpt()
You know when using `the_excerpt()` and no "excerpt" is set on a post it automatically uses the first 50 words or so.
Is the same also possible when using `get_the_excerpt()`
For instance I'm using `get_the_excerpt()` like this …
$return .= sprintf('
<li>
<div class="title"><a href="%1$s">%2$s</a><span class="goto">a</span></div>
<div class="project-description">%3$s</div>
</li>',
get_permalink( get_the_ID() ),
get_the_title(),
get_the_excerpt()
);
However if no excerpt is set, the `get_the_excerpt()` function doesn't show a fallback (the first 50 or so words). Any idea how to make that work? | The function `the_excerpt()` is only a echo of the function `get_the_excerpt()`:
function the_excerpt() {
echo apply_filters('the_excerpt', get_the_excerpt());
}
If you like a fall back for no input the excerpt meta box, then create a text from the content - `get_the_content()`. You can use the core function `wp_trim_words()` for set the counter for words and easy to set a text from all content. A example:
$excerpt = get_the_content();
$excerpt = esc_attr( strip_tags( stripslashes( $excerpt ) ) );
$excerpt = wp_trim_words( $excerpt, $num_words = 55, $more = NULL ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "filters, excerpt"
} |
Problem uploading files, after changing domain name
I just changed my WordPress website domain name (on the same server). Everything works fine, and the paths are correct. I can install plugins and updates without any problem.
However, I can only upload media when the `wp-content` directory's permissions is set to 777. When I get it back to 755 I get an error that the file couldn't be copied to the folder.
What could cause this problem? | Well' for anyone that faces this problem. look here: plesk-permissions-wordpress | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads, media library, permissions"
} |
using 1 form shortcode (si or cf7) for all multisite sites
I have a network with more than 50 sites. I want to create one contact form (which means one shortcode) using contact form 7 or fast secure contact form. Then, I want to use that shortcode on all the 50+ sites so all sites use the same form.
The problem is that when I try to use a shortcode of site A over site B, it's not working.
Do you know how can I use a contact form shortcode globaly on all sites at once?
Thanks! | A Must Use plugin could do the work.
This is just an outline and has to be fully tested:
add_shortcode( 'global_form', 'shortcode_wpse_87634' );
function shortcode_wpse_87634()
{
// Main site, ID=1, that has the form
switch_to_blog( 1 );
// Do your stuff
$my_stuff = something(); // maybe do_shortcode
// Back to original site
restore_current_blog();
// Return shortcode content
return $my_stuff;
}
Also, maybe the contact form plugin must be Network activated for this to work.
Having the shortcode available Network-wide will work with the `mu-plugin`, but to have the form really working globally, that's another issue. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "multisite, shortcode, plugin contact form 7, contact, globals"
} |
who to limit number of li in wp_nav_menu
need help regarding wordpress navigation
i am using
if ( has_nav_menu( 'main_nav' ) ) {
wp_nav_menu( array('menu' => 'guest menu' ));
}
from back end if i keep the menu empty(do not any page/category to menu) it displays all the pages in menu on front end.
i want it it to display nothing or by default only one menu item (only one `<li`>) if the menu in back end is empty.
can i limit `wp_nav_menu()` to display only one `<li>` | See Function Reference/wp nav menu
if ( has_nav_menu( 'main_nav' ) ) {
wp_nav_menu( array('menu' => 'guest menu', 'fallback_cb' => false ));
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus"
} |
WP_Query orderby taxonomy term value (numeric)
I have this query...
<?php
$press = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'individual',
'post_status' => 'private'
));
if ($press->have_posts()) : while ($press->have_posts()) : $press->the_post();
?>
But my custom post-types are using custom taxonomy with a numeric term value.
My question is there anyway in ordering this query by the term value?
The taxonomy is called 'individual-group'
Any help would be hugely appreciated thanks.
Josh | No, there is no way to do this with default WP Core. @heathenJesus talks about meta data not taxonomies. See < for a proper solution.
And a more thorough explanation of why this is not something built into Core: Using wp_query is it possible to orderby taxonomy? | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "wp query"
} |
Dynamic href link to Contact Page
I need a `<a href="Something Like <?get_contact_page>">Contact Page</a>` Code that always links to the Contact page, no matter what is it's ID
There's a page template for contact page.
Is it possible to do this?
I'll gladly provide any further information you need :)
Thanks!! | If the contact page is identified solely by the associated template, you can query for a page with the template name in meta key `_wp_page_template`:
$args = array(
'post_type' => 'page',
'posts_per_page' => 1,
'meta_query' => array(
array(
'key' => '_wp_page_template',
'value' => 'contact_template.php'
)
)
);
$contact_page = new WP_Query( $args );
if( ! empty( $contact_page->posts ) )
echo get_permalink( $contact_page->post->ID ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, page template, contact"
} |
Caching of SQL queries
Within one plugin file I have several calls to the same option in the database via get_option(). Does WordPress do a database query every time I use get_option()? Would it be better to get the option once and store it in a global variable? | Wordpress will only do a database lookup the first time if the option hasn't been auto-loaded or already accessed prior. The performance hit is negligible, however if you're loading multiple separate options with a bunch of get_options instead of using the serialised option functionality, then the initial lookup * X number of separate option rows could potentially cause performance issues.
In your other question which is a duplicate of this one, I answer the question with an example of best practice code if you're concerned with get_option performance here. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "options"
} |
Where does Wordpress store the users customization in the theme
Good Day
When you are inside the wordpress ctrl panel, and you edit/create posts, do theme changes etc, where does Wordpress store all that content? In which files?
Thank you | That information is stored in the MySQL database, not in files like you may be thinking of. They aren't stored in `.php` or `.html` files.
If you want to "see" how and where that data is stored the easiest way is to browse the database using a tool like PhpMyAdmin.
NOTE: Technically, there are files associated with the MySQL database but they aren't easy to get to and you can't read them except through the interface provided by the MySQL engine. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 7,
"tags": "posts, customization"
} |
Any plans for a non backwords compatible WP release?
Imagine all the old_functions_that_do_the_same_thing_as_new_functions() being ripped out. Think of the consistency and improved work flow while working with different themes and plugins.
Is there already a branch like this or is there something in the pipeline? | There are no such plans. WordPress intentionally maintains backward compatibility. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wordpress version"
} |
Can I install plugins manually on WP.com?
If I have a paid blog at wordpress.com, can I install plugins manually on it?
Or must I have my own wordpress installation?
Thanks! | Short answer - no, not really. Though there are already a lot pre-installed and you can suggest new ones if you'd like. Check this article out: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "plugins, installation"
} |
Why is my footer missing
Hi for some reason my footer is missing on my site, and i don't know why. I have deactivated all plugins and it's still not there, I have checked the css and all, but the footer is still missing can someone tell me whats wrong.
When I view the Source Code the Footer is there but It's not showing up.
The Site is EricaVain.com
Here are the files on gist --> < | Your iframe tag that supplies your Facebook information isn't closed. So the code stops rendering from that tag on. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -2,
"tags": "php, footer"
} |
sort by vote with GD STAR RATING plugin
Does anyone have any suggestions as to how I can get the sort by vote count to work with the GD STAR RATING plugin? I have added sorting parameters to a category list on my site but it still isn't ordering the posts by the number of thumbs up votes.
Does anyone have suggestions of what I should check? Are there options I need to set in the GD STAR RATING admin panel? | I solved my problem. I needed to change the parameter "votes" to "thumbs". I also found it worked better to show the results in a descending order. Here is the working URL:
| stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "plugin gd star rating"
} |
How to number the posts (ie #1, #2, #3) in a wp_query?
What is the best way to display the appearance number of a post in a query?
For example, if a post is the first listed print #1. If it is third, print #3.
Any direction is appreciated! | $the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) :
$the_query->the_post();
echo('#' . $the_query->current_post + 1); // $the_query->current_post has the index
endwhile; | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "wp query"
} |
How to retrieve text only from wp_content() not from wp_excerpt()?
I'm currently developing a website with WordPress 3.5 and I need to retrieve **Post Text (Only text, not include images)** at **Archive Page**. I can retrieve it with `wp_excerpt()` method without any problems. But the main problem for me is that I can't get the exact text layout. `wp_excerpt()` method returns text which ignores all extra spaces and line breaks. What should I do? I think I will get **Only Post Text with Exact Layout** if I can retrieve from `wp_content()` method. Thanks in advance for your help! | Or even simpler:
echo wp_strip_all_tags( get_the_content() );
By using:
* `get_the_content()`
> Retrieve the post content. (Must be used in a Loop)
>
> An important difference from `the_content()` is that `get_the_content()` does not pass the content through the '`the_content`'. This means that `get_the_content()` will not auto-embed videos or expand shortcodes, among other things.
* `wp_strip_all_tags()`
> Properly strip all HTML tags including script and style. | stackexchange-wordpress | {
"answer_score": 22,
"question_score": 13,
"tags": "posts, text"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.