INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Disable wordpress comments API
We're using the disqus plugin on our wordpress site, so anyone commenting should have a login through disqus. Yet, I'm still seeing spammers trying to post through the regular comments API. They're not getting through to the post, but they're clogging my inbox as admin.
How do I disable this API - I only want to accept comments that come from a logged in Disqus user? | There is much easier way to close standard WordPress comments. Just add
add_filter( 'comments_open', '__return_false' );
to your `functions.php` file and comments will be closed. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "comments"
} |
Get search.php results in header.php?
I want one image in header.php to change for different pages.
The function in header.php looks like that:
if(is_archive()):
//change image to "Archives"
endif;
if(is_404()):
//change image to "404"
endif;
Now, is it possible to check if page is the search page AND what's the search string AND how many posts were found?
So what I want to do is basically:
if(is_search()):
//change image to "Search" AND echo %s
endif;
if(is_search_empty()): //yes I made this up
//change image to "Nothing found" AND echo $
endif;
Is it even possible outside the search.php page loop? | > Now, is it possible to check if page is the search page
is_search()
> AND what's the search string
is_search() AND print get_query_var( 's' )
> AND how many posts were found?
is_search() AND print $GLOBALS['wp_query']->number_posts()
… or if you got a custom query…
$my_query = new WP_Query( array( /* whatever args */ ) );
is_search() AND print $my_query->number_posts() | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "loop, templates, search, headers"
} |
Run function on settings save
I am using the Settings API for a plugin's settings page. One of the settings allows the user to change the cron job interval for the cron job created by this plugin.
Therefore I'd like to run a function on saving of the settings page, which checks the value in the database and compares it to the value the existing cron job has. If they are different, the cron job should be recreated.
Is my logic right, and if so how can I run such a function after the plugin settings have been saved? | I'm not familiar with wordpress settings api but I know those options generated by settings api are handled/saved in wp-admin/options.php
Unfortunately,
if ( isset( $_POST[ $option ] ) ) {
$value = $_POST[ $option ];
if ( ! is_array( $value ) )
$value = trim( $value );
$value = stripslashes_deep( $value );
}
update_option( $option, $value );
as you can see, no hook before update_option.
But there is a workaround:
add_settings_field('..','..','callback');
function callback(){
if($_GET['settings-updated']=='true'){
//do your cron update stuff here.
}
echo 'output <input or something';
}
Not very elegant though. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "options"
} |
How to use the 'comments_number' filter?
I'm not sure how to use this filter. Could someone show me an example? I'm trying to change `('0', '1', '%')` to `('0 Comments', '1 Comment', '% Comments')`.
I'm using this function to get the comments number.
function lpe_get_comments_number( $anchor='#comments' ) {
$return = '<a class="comments-number-link" href="' . get_permalink() . $anchor . '">';
$return .= get_comments_number(); // '0', '1', '%'
$return .= '</a>';
return $return;
}
I know I could just set the arguments here and call it a day, but I was hoping to store my custom functions away in a different file and handle their settings from the themes functions.php. | The filter you mention is used by the end of `get_comments_number_text`. As you can see from the source the number of comments is passed through the filter, allowing you to completely change the default text. Like this:
add_filter ('comments_number', 'wpse89257_comments_number', 10, 2);
function wpse89257_comments_number ($output, $number) {
if ($number == 0) $output = '0 Comments';
elseif ($number == 1) $output = '1 Comment';
else $output = $number . ' Comments';
return $output;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "comments, filters, hooks"
} |
How to combine multiple body classes
My theme already has a specific body class filter for the colorscheme it uses. How can I also add a body class filter for the page name? Basically I want to combine these statements:
<body <?php body_class(); ?>>
<body class="<?php echo get_stencil(); ?>">
I've been trying but I just keep getting error messages with variations like this:
<body class="<?php echo get_stencil(); ?> <?php body_class(); ?>"> | directly in the body tag line:
<body <?php body_class( get_stencil() ); ?>>
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters"
} |
How do I use a custom theme for the WP Maintenance Mode plugin?
How do I use a custom theme, rather than the themes included with this plugin?
Here is the link to the plugin: <
I see that under the plugin's settings there is a way to choose "own style" theme and a way to link to custom stylesheet, but I want to use my own html as well. | How to do this is on the front of the plugins wordpress.org page.
<
> You can add your own html and stylesheet and add the url of this style to the options of the plugin. Write your style to this markup and upload to the webspace; after add the url include http:// to the settings of this plugin and change th theme to "Own Theme":
Which while it is ambiguous, the settings page does offer an alternative. If you upload a dedicated maintenance html page, then use the redirect feature to redirect to it, you would have full control over the page.
It may be that this plugins themes are purely CSS based. You may be able to use the hooks and filters provided to remove and add items of content and markup, but redirects are the simplest method.
**edit:** After some talk with the plugin author, I've gotten the readme for the plugin and terminology changed, it seems if you put a `wp-maintenance.php` in wp-content it will use that instead of the default html. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Turning off trackbacks & comments
We have a few different websites running various versions of Wordpress that have comments and trackbacks turned off, yet I still receive emails saying there's some waiting for me!
I've turned them both off in the admin area and also removed the comments box completely yet I still get them, how can I fully turn them off? | To prevent comments receiving add following line to your `functions.php` file:
add_filter( 'comments_open', '__return_false' );
And to prevent trackbacks receiving just add this snippet:
add_filter( 'pings_open', '__return_false' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "comments"
} |
Author Link Not Displaying
I have used this with "echo" as its outside the loop i believe to the author of the post as a link, however its not displaying as a link?
<h2 class="sidebarheaders">Random Posts By You </h2>
<br/>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'date' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
Written by:
<?php echo the_author_link(); ?>
<?php endforeach; ?>
Can someone advise? | You have to use `setup_postdata` function if you want to use `the_author_link` with custom loop. Do it like this:
<h2 class="sidebarheaders">Random Posts By You </h2>
<br/>
<?php
$rand_posts = get_posts( array( 'numberposts' => 5, 'orderby' => 'date' ) );
foreach( $rand_posts as $post ) :
setup_postdata( $post );
?><li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
Written by: <?php echo the_author_link();
endforeach;
wp_reset_postdata();
?>
Don't forget to call `wp_reset_postdata` to restore the $post global to the current post in the main query. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "author, tags"
} |
increase maximum upload file
I want to increase the maximum upload file (media default:32mb). Before posting i search, but i didn't have the result that i want. My host didn't support .htaccess. I create my own `php.ini` with these:
memory_limit = 32M
upload_max_filesize = 120M
upload_max_filesize = 120M
post_max_size = 100M
file_uploads = On
After that i upload in the /wp-admin but i didn't see anything for increase. Also, i edit the `wp-config.php` with this:
define('WP_MEMORY_LIMIT', '120M');,
even after this i didn't see any change to increase. How can do that?
Thanks in advance | Please try to upload the php.ini file to the document root directory or to the same directory as wp-config.php.
You may also want to modify memory_limit to 120M and modify max_execution_time to 300. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads"
} |
Help to enqueue a js functions ( jquery)
I have this js function (the `textualizer.js` is external) but I can't make it works on WordPress. Any help?
I already added
wp_register_script( 'textualizer', WP_THEME_URL . '/assets/js/textualizer.js');
wp_enqueue_script( 'textualizer' );
to theme functions.
What am I doing wrong? I know it's probably simple, but I can't figure it out.
EDIT: i changed the function in functions.php, a user in irc channel told me that i was missing the correct action hook. still doesn't work... < | Using Google with the error message you posted in your comment, Google show me this: The Deferred object, introduced in jQuery **1.5**
Your source code says, that you use jQuery **1.4.4**.
jQuery is bundled with WordPress and it's version is **1.8.3**. Please use the bundled jQuery and not one from an CDN. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp enqueue script"
} |
Contact Form 7 Plugin emails not being received by some accounts
I am using contact form 7 to send an email form. I receive them, but my clients' email addresses - one at the host and one at gmail, never do. They claim that none of the messages end up in their spam folders either. The client did ask the host to take a look and they also claimed that there is no blocking of the form emails and they aren't being sent to spam. Ideas on where things are going wrong and how to fix this? | I have had tons of issues with the plugin Contact Form 7 in the last couple months. Especially with Wordpress 3.5.1. I started using Formidable Pro for all of my clients in the last couple weeks. It costs a bit of money for the developer license, but the peace of mind that it is working and there is plenty support as well as additional plugins available has been priceless!
In the event that it is not Contact Form 7 that is causing the problem of sending mail check/do the following.
* Make sure the IP Address the site resides on is not Blacklisted
* Check to see if the server is set to deal with mail internally or remotely
* If all else fails, you can always configure it to send mail through an actual email account though SMTP. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, forms, email"
} |
changing permalink for custom template in posts of a certain category
I've created a unique single post template to give people the option of reading all posts of a certain category using the awesome "reveal.js" which they access via this link
<a href="?show=presentation/">presentation</a>
The problem is the ugly URLs, which end up looking like
website.com/post-name/?show=presentation
website.com/completely-different-post-name/?show=presentation
I would like them to look like
website.com/post-name/presentation/
website.com/completely-different-post-name/presentation/
I've spent the last 10 or so hours trying to figure this out (I haven't even gone to sleep yet, lol); unfortunately, nothing has worked.
Is there a way to do this?
As a side note, the site I'm trying to do this on is installed in a subdirectory (localhost/wp) but I'm developing this for my actual website which is installed in a top level directory | You can achieve this via the Rewrite API's `add_rewrite_endpoint`:
function wpa89344_add_presentation_endpoint(){
add_rewrite_endpoint( 'presentation', EP_PERMALINK );
}
add_action('init', 'wpa89344_add_presentation_endpoint');
Then in your template or wherever you differentiate a presentation vs normal view, check the global `$wp_query` for the presence of the `presentation` query var:
global $wp_query;
if( isset( $wp_query->query_vars['presentation'] ) ){
include(TEMPLATEPATH . "/single_wide_report.php");
} else {
include(TEMPLATEPATH . "/single_normal_report.php");
}
Note that you need to visit the permalinks settings page after adding the endpoint to flush permalinks and create the new rewrite rules.
EDIT- Output of `$wp_query` in `single.php`:
!enter image description here | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permalinks, single"
} |
Edit / delete custom post types through web page (not admin)
I want it to be possible for the users to edit and delete their own posts, not only through the admin panel as it is by default. I've look around on the net but haven't found any information about it.
How can this be done? | Take a look at <
If you assign users the Contributor role, they'll be able edit their own posts from the frontend. You could use a basic redirect to prevent Contributors from being shown the admin panel on login... look around StackExchange/Google for several solutions to this.
For another solution, which will give you more control over the process (including adding/editing/deleting posts), check out the tutorial at < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types"
} |
Possible to add meta box to edit.php pages?
I've been googling this for a while, and came across this link here: Can I limit this meta box to a particular page?
What I am trying to achieve is adding a custom Meta Boxe I created onto a CPT Posts Screen (`edit.php?post_type=custom`).
What I tried to use is this:
add_action("admin_init", "admin_init");
function admin_init() {
global $pagenow, $page;
if ( 'edit.php' == $pagenow ) {
add_meta_box( $id, $title, $callback, $post_type, $context, $priority, $callback_args );
}
}
When adding and saving this into my `functions.php`, the page turns blank.
Is it even possible to add a meta box to `edit.php` pages?
* * *
**EDIT** OP wants to add the "QuickPress" functionality in this meta box. Screenshots from the comments to an answer.
> !enter image description here | From your comment, it sounds like you don't want a metabox. A metabox is used to add metadata to a particular post, not create a new post from scratch. What it sounds like you want to do is create a widget to do what you want and then invoke it through an action or filter at the top/bottom of the page. You can use the existing Quick Post dashboard widget as your base. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, metabox"
} |
How to get the post content after Wordpress post processing?
I have a plugin that will send tutorial emails to our users. These tutorials are created in wordpress and stored in wp_posts table in the database.
Of course I could simply run a query to get the post and that's it. But is there a special built-in function that I can use to get the post content after Wordpress post processing?
I am thing of using get_post but I'm not sure if this is the best thing to do:
<?php
$my_id = 7;
$post_id_7 = get_post($my_id);
$post_content = $post_id_7->post_content;
?>
Thanks for any tips. | If by "post processing" you mean the autoformatting, the shortcode processing, that sort of thing, then you want to pass the content through the `the_content` filters.
$my_id = 7;
$post_id_7 = get_post($my_id);
$post_content = $post_id_7->post_content;
$post_content = apply_filters('the_content',$post_content);
<
You can see much of what will be applied by default by looking at the source of `wp-includes/default-filters.php`. However, plugins and themes can add filters so you may find that you want to pick and choose what gets applieds. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "plugin development"
} |
Multisite plugin hiding on specific blogs
Is it possible to hide plugins on a per blog basis in WordPress multisite? I would like not to have plugins available on certain blogs. | Super Admin is your friend! If a plugin is not active in the Super Admin (also lamely named Network Admin) Then it won't show up as an option for individual blogs.
**It basically works like this:**
Installed as Super Admin (main site) and "Network Active" will be active on all blogs on the network. Installed on Super Admin, Active but **NOT** "Network Active" only active on Main/Parent site
If you want it only installed on a few sites then just manually install the plugins like you would normally do. Each instance of WordPress on a multisite is treated as its own site so installing a plugin on one site (with the exception of the main site) will not install it on the rest.
**EDIT:**
Based on your comments I would make sure that the user has the correct role to upload/activate plugins. You must create a user in each site individually or add an existing user to the site.
You could also try a plugin like < and see how it goes. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "multisite"
} |
Trouble Making WP_Query paged
I'm using the query below in the index.php file as the main query, whenever I try to go to the 2nd page I get a 404 error, I tried using posts_per_page but to no avail.
<?php
$args = array(
'post_type' => array( 'post', 'videos', 'music' ),
'tax_query' => array(
array(
'taxonomy' => 'content',
'field' => 'slug',
'terms' => 'indy',
'operator' => 'NOT IN'
)
)
);
$products = new WP_Query( $args );
if( $products->have_posts() ) {
while( $products->have_posts() ) {
$products->the_post();
?>
Do stuff here.
<?php }
}
else {
echo 'Oh boy, no posts available';
} ?>
What am I missing? | Pagination in URLs only works for the "main" query. What you've created is a secondary query, so WordPress doesn't "know" about it in such a way that the application would be able to create pagination. If you use a secondary query (like your example) it's up to you to do the pagination stuff manually.
Rather than create a new query, I'd suggest you alter the "main" query with the `pre_get_posts` hook. Example:
<?php
add_action('pre_get_posts', 'wpse89413_pre_posts');
function wpse89413_pre_posts($query)
{
// make sure you're on the blog page and altering the main query
if (is_home() && $q->is_main_query()) {
$query->set('post_type', array('post', 'videos', 'music'));
$query->set('tax_query', array(array(
'taxonomy' => 'content',
'field' => 'slug',
'terms' => 'indy',
'operator' => 'NOT IN'
)));
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query, query posts, pagination"
} |
weekly archive for custom category
<?php $args = array(
'cat' => '2',
); ?>
<?php wp_get_archives($args); ?>
I pull out the custom category with the above codes, it works fine & shows up "February 2013". here, My question is can I display it in "weekly".
I put `(type = weekly)` in `$args`, but it displays weekly posts archive, not the category.
My question is almost same as this question. It seems the questioner didn't get a clear answer yet. I'm also looking for the answer.. | I read the readme.txt file of Archives for a category WordPress plugin.
The plugin author has stated following limitation on it.
# Limitations
This plugin does not work for weekly archives. The list with archive links is correct, but the links themselves do not include the category. So when used, WordPress will not filter the resulting page on the category. The technical reason is that WordPress does not apply filters when the links for weekly archives are generated, so the plugin can't change them. Perhaps this is fixed in a next version of WordPress.
I checked latest version of wordpress(3.5.1) to find out whether this version has added any filter for weekly url but it has not added yet :(
I think you will have to develop custom code and sql query to implement this functionality and should not depend on Archives for a category WordPress plugin and wp_get_archives function to implement this functionality. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "categories, archives"
} |
Meteor Slides as header only for homepage and Use featured image of each page as header for respective pages
I am using meteor-slides plugin to make header as a slideshow. I am using twenty-eleven theme. Now i need to make this slideshow for my homepage only and featured images of other pages as headers for the respective pages. Can anyone help me with this? | I have got answer for it. I have changed the code to add meteor slides plugin in functions.php to show the slideshow just in the homepage.
<?php if ( is_front_page() ) {
if ( function_exists( 'meteor_slideshow' ) ) {
meteor_slideshow();
}
} ?>
After that i used a plug called WP display header to set header image for each page | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "plugins, post thumbnails, headers"
} |
Fatal error: require() [function.require]: Failed opening required in wordpress
My blog has been working fine for months. Today when I tried to open it I got the following errors:
Warning: require(/home/dhabitat/public_html/blog/wp-includes/functions.php) [function.require]: failed to open stream: Permission denied in /home/dhabitat/public_html/blog/wp-settings.php on line 69
Fatal error: require() [function.require]: Failed opening required '/home/dhabitat/public_html/blog/wp-includes/functions.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/dhabitat/public_html/blog/wp-settings.php on line 69
Does anybody know how it can be fixed. thanks | Check the permissions of the `functions.php`.
This page in de Codex about changing file permissions explains a lot about wich permissions you have, or can use.
> On computer filesystems, different files and directories have permissions that specify who and what can read, write, modify and access them. This is important because WordPress may need access to write to files in your `wp-content` directory to enable certain functions. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "blog, fatal error"
} |
How to pass a parameter to this add_filter example
I have a class with this function to provide a user language based on $user_id
function provide_user_language($user_id) {
return apply_filters('get_user_language',$user_id);
}
So in my script, I can simply get the user language by doing this:
$user_language=$this->provide_user_language($user_id);
But I need to associate this $user_language to a "set_current_language". I can do this by doing an add filter hook, but add_filter does not accept parameters. This is the add_filter line with the function itself but I don't know how to pass the $user_id or the $user_language so that set_current_language will be set to $user_language:
add_filter('set_current_language', array(&$this,'provide_user_language'));
I tried following this one but it won't work:
Passing a parameter to filter and action functions
I appreciate any tips. Probably there is an easy way. | Thanks Tom, Unfortunately Toscho concept didn't work for me, so I dig deeper in the add filter documentation here: < and they allow anonymous functions as callback.
This method finally solved my problem. This is how I resolve this one for other users that are experiencing this issue:
add_filter('set_current_language',
function($lang_set) use ($user_language) {
$lang_set=$user_language;
return $lang_set;
});
In this method, I pass the $user_language(which is available) to the add_filter hook. $lang_set is the dummy variable used to return the callback output.
I have finally set the "set_current_language" to the user language using add_filter. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "plugin development"
} |
How to hide sub categories in sidebar
i want to hide subcategories in widget sidebar . just in widget sidebar i was added in style.css this code
.children { display:none;}
but this code do hide to the threaded comments
what is the way to hide just sub categories in sidebar | You didn't give us markup so I can't know if this is correct but
.sidebar .children { display:none;}
EDIT: I think you're looking to hide your .commentlist .children correct? Line 1460-1463 of your file are the .children selector. try making each of them
ol.commentlist li ul.children li.depth-2 { margin:0 0 3px; display:none}
ol.commentlist li ul.children li.depth-3 { margin:0 0 3px; display:none}
ol.commentlist li ul.children li.depth-4 { margin:0 0 3px; display:none}
ol.commentlist li ul.children li.depth-5 { margin:0 0 3px; display:none}
Is this a widget in your sidebar? I can't tell without the markup, you only gave the .css. What is the link to your website? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -5,
"tags": "sidebar"
} |
Wordpress function like is_category for subcategory? is_subcategory?
Is there a function in WordPress that will check if the page you are on is a sub-category archive page?
Like the way is_category checks if it's a category page? | Sub-categories use the regular category archive page by default. There is no function such as is_subcategory. But you can write your own.
Here is an example: This will check if the current page is a sub-category. Or if you pass an ID it will check if the ID is a subcategory.
function is_subcategory( $cat_id = NULL ) {
if ( !$cat_id )
$cat_id = get_query_var( 'cat' );
if ( $cat_id ) {
$cat = get_category( $cat_id );
if ( $cat->category_parent > 0 )
return true;
}
return false;
} | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 6,
"tags": "functions, conditional tags"
} |
How can I restrict php mail() to only send me one email after a db error
I'm in the process of customizing dp-error.php. I'm using the mail() function to alert me when there's a database connection problem on my website. The trouble is, what if 1000 people visit my website when it's down? Wouldn't I get 1000 emails? Here's the code I'm using to send email:
mail("[email protected]", "Database Error", "There is a problem with teh database!", "From: Your WP Installation"); ?>
My other question is then how would mail() know it's okay to send me a notification email in a future db error? After a certain period of time send again, if there's (still) an error?
Thanks! | I'm not sure that this is a good idea, email is just not a good medium for emergency messages (who will see the email when you are a sleep or at the beach?), and if you want to monitor the site it is better done by external service which will probably be able to send you an SMS or make a phone call.
That being said, if you want to still send emails, you need to store the last error time in a separate file, and before sending a mail read the file and check when was the last time a mail was sent. The important detail here is that the file need to be writable by the web server. It is probably a good idea to locate it outside of the web root on your server. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "database, errors, email"
} |
Search form as list item in menu?
What is the best way to do this:
<?php wp_nav_menu( array('menu'=>'Primary',
'container'=>'',
'items_wrap'=>'<ul id="%1$s" class="%2$s">%3$s<li>'.get_search_form().'</li></ul>') ); ?> | You can add any item you want to a menu by filtering `wp_nav_menu_items`. From the tutorial How to Add a Search to Menu, this is how you'd add a search form:
add_filter('wp_nav_menu_items','add_search_box', 10, 2);
function add_search_box($items, $args) {
$searchform = get_search_form( false );
$items .= '<li>' . $searchform . '</li>';
return $items;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, search, list"
} |
wordpress local host web login not working after port configuration
I installed the word press on my vm and configure my port 8000. Now, when I am trying to login into wordpress using
on browser , the link is getting changing into
and displaying "Problem loading page : Unable to connect". I have checked xampp and I am able to access it
| Check the 'siteurl' and 'home' values in your wp_options table, and update those URLs to:
` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "localhost, local installation"
} |
Loop not showing up on page template
I have a page template and on the page I have a loop such as:
query_posts('post_type=post&posts_per_page=5&paged='.get_query_var('paged'));
if(have_posts()){
while(have_posts()){
the_post();
the_title();
}
}
The problem is that no posts are coming back when there should be about 5 or 6. Is there something wrong? | Firstly, use `WP_query` instead of `query_posts`:
Secondly, for (static) pages use the variable 'page' (not 'paged').
$my_query = new WP_query( 'post_type=post&posts_per_page=5&paged=' .get_query_var('page') );
if ( $my_query->have_posts() ) while( $my_query->have_posts() ) :
$my_query->the_post();
the_title();
endwhile; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop, page template"
} |
Built-in Method to Extract Embedded Video from Content
Is there way to extract embedded video without using a regular expression as seen here?
I was hoping that there would be a way to get them using a WordPress function. | It looks like the closest you get is in the WP-Embed class:
autoembed( $content );
It says it extracts urls which are on distinct lines (like you'd put a url in for embedding it), but it then passes it to WP_Embed::shortcode().
Not quite what you want. You could dig into WP_Embed::shortcode() to see if you can figure out how to hack together your own script, but I don't think there's anything ready-made for you :/ | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "content, videos"
} |
KEY and VALUE custom field issue
I have this bit of code for displaying the value of links key of my custom fields.
$links = get_post_meta($post->ID, 'links', false);
foreach($links as $link)
echo '<div class="first-link bottom-dotted"><p><a href="">'.$link.'</p></div></a>';
What I need to do is insert the value of another custom field called say URLs for each a href tag in my foreach statement.
Any idea how to achieve this?
I'm not sure I can do something like this:
$links = get_post_meta($post->ID, 'links', false);
$URLs = get_post_meta($post->ID, 'URLs', false);
foreach($links as $link) || foreach($URLs as $URL) {
echo '<div class="first-link bottom-dotted"><p><a href="'.$URL.'">'.$link.'</p></div></a>';
} | I don't know if you can count on the order of both custom fields to be equal when returned from get_post_meta(), but if you can, you could use:
$links = get_post_meta($post->ID, 'links', false);
$URLs = get_post_meta($post->ID, 'URLs', false);
for ( $i = 0; $i < count( $links ); $i++ ) {
if ( empty( $URLs[$i] ) ) {
$URLs[$i] = '#';
}
echo '<div class="first-link bottom-dotted"><p><a href="'.$URLs[$i].'">'.$links[$i].'</a></p></div>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field"
} |
Possible to add a statement to a core file?
I would like to add one line to a wp core file. Basically on the 'edit.php' page, just right above
<?php
include('./admin-footer.php');
I would like to add an php include statement...
include('./custom-file.php');
The custom-file is located inside a plugin, not a theme... so if I write it inside my plugin function.php, the url will be:
include( plugin_dir_path( __FILE__ ) . '/custom-file.php');
Is there some way I can use to add this one line via a function without having to edit the core file?
Thanks! | There is zero reason to do this.
1. Why would you need your include in `edit.php`? Just include it in your plugin.
2. If for some reason you need to hook into the `edit.php` page (hard to tell what you're doing), you can use,
add_action( 'load-edit.php', 'your_function' );
* * *
!enter image description here | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, core, wp list table"
} |
How to add custom widget above admin_footer
What I am trying to accomplish is placing custom widget on an admin page (edit.php). I tried using these two functions:
Places custom html right below < body > (above all page content)
add_action( 'load-edit.php', 'your_function' );
function your_function() {
include( plugin_dir_path( __FILE__ ) . 'quickpost/quickpost.php');
}
Places custom html below the < footer >
add_action('admin_footer', 'post_add_quickpost');
function post_add_quickpost() {
include( plugin_dir_path( __FILE__ ) . 'quickpost/quickpost.php');
}
Here is were I am trying to place the widget, just above the posts table on the edit.php page.
Is there a way I can specify where to place the code? I would prefer to work with the 'load-edit.php' action, but if that is not possible - it is okay with me. Thanks! | As far as I know you have 2 options.
1. Using `admin_footer` or `load-edit.php` and position with `absolute` or `fixed`, or use JavaScript.
2. If you creating a completely new posts screen (not a default posts, pages, etc), you can extend `WP_List_Table` class, specifically the `extra_tablenav` function.
For example:
class My_Custom_Table extends WP_List_Table {
function extra_tablenav( $which ) {
if ( $which == "top" ){
//The code that goes before the table is here
echo "Hello, I'm before the table";
}
if ( $which == "bottom" ){
//The code that goes after the table is there
echo "Hi, I'm after the table";
}
}
}
As far as I can tell, extending this class can only work on a custom admin page, and not the current existing ones, as there are no hooks available. You can read more about it here: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "widgets"
} |
What are the Best Practises When Using AJAX in Plugin Development?
I am in the middle of creating a plugin and everything works fine with the AJAX calls but one question I can't seem to find the answer to is about best practise.
I route the AJAX calls through `/wp-admin/admin-ajax.php` and have my php functions in the theme `functions.php` script.
However, I've just thought that this doesn't seem such a good idea because what do you do when the user activates your plugin, do you need to create a function to write your code to functions.php on activation?
Similarly, what if the user changes theme?
Therefore, I was just wondering if there are other ways to do it or what is the common approach for this type of thing. | WordPress AJAX best practices are following:
1. Use `wp_localize_script` to declare JavaScript global variables;
2. Use `admin-ajax.php` script to handle all AJAX requests;
3. Use nonces and check for permissions;
4. Use jQuery Form plugin to submit forms.
Read 5 tips for using AJAX in WordPress article for more details.
> What do you do when the user activates your plugin, do you need to create a function to write your code to functions.php on activation? Similarly, what if the user changes theme?
You don't have to care about it. If you write your own plugin and it uses AJAX requests, then it has to be implemented only inside your plugin, don't write code into theme's `functions.php` file. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "plugins, plugin development, ajax"
} |
I want to reset user's post meta after successfully login
I want to reset admin's meta value after login. It can be changed after login by admin via control panel, but I want to reset it after every login.
I used this code but it's not working:
function reset_dismiss_message(){
update_user_meta( get_current_user_id(), 'tgmpa_dismissed_notice', false );
}
add_action('wp_login', 'reset_dismiss_message');
I checked if and found it that the **get_current_user_id()** function is not returning user's ID as there is no data generated when wp_login action processing.
So how can I do this? | `wp_login` action passes 2 arguments `$user_login` and `$user`. The second argument is the object of `WP_User` class, which you can use to get user id from:
function reset_dismiss_message( $user_login, $user ) {
update_user_meta( $user->ID, 'tgmpa_dismissed_notice', false );
}
add_action( 'wp_login', 'reset_dismiss_message', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
Hook into a function without a hook?
I have just got into using hooks and have now understand the beauty of them. I understand that I can hook into the following by using `add_filter('hook_name','my_hook_name', $variable);`
function a_function($variable){
return add_filter('hook_name', $variable);
}
But what if your the function you wanted to hook into simply returned a variable.
function a_function($variable){
return $variable
}
I don't have the `'hook_name'` to hook into anymore. So am I missing something? How can I edit that second function via my functions.php? | You cannot hook in a function without a hook. If it returns a variable, you will have to use it as it is returned. And then, maybe, perform your operations on that. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "functions, hooks"
} |
Custom fields: dropdown values depending on other custom field value
i have custom fields like this:
* "country" - values: "USA", "Russia", "China"
* "city" - values: "Chicago", "Moscow", "Beijing"
I want when user in custom field "country" choose value "USA" after that in custom field "city" show only "chicago". Is it possible? And how can I do this? | This is possible by using AJAX.
The following links are containing more information about AJAX and implementation in WordPress:
* <
> Ajax (Asynchronous JavaScript And XML) is a technology that allows a web page to perform actions or update dynamically, without completely reloading
* <
> This article, aimed at plugin developers, describes how to add Ajax
* <
> When using WordPress as a CMS, situations often arise where you need to display, add or update content on your WP site without turning to plugins. While bolting in some PHP alone can do the job, nothing is more seamless that the magic of jQuery’s AJAX | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, dropdown"
} |
Create a WordPress administrator without access to back-end
My site recently got hacked, and all my admin users lost their administrator level access. But when I access mySQL database, I saw all the users still exist.
How can I create an administrator when I can access the database only? | Run this script in phpMyAdmin or whatever tool you use to access MySQL:
SET @user_login := 'justin_foell';
SET @user_pass := 'Q9xiHgzZ';
SET @user_email := '[email protected]';
INSERT INTO `wp_users`
(`user_login`, `user_pass`, `user_email`, `user_registered`)
VALUES
(@user_login, MD5(@user_pass), @user_email, now());
SELECT @user_id := LAST_INSERT_ID();
INSERT INTO `wp_usermeta`
(`user_id`, `meta_key`, `meta_value`)
VALUES
(@user_id, 'wp_capabilities', 'a:1:{s:13:"administrator";b:1;}');
INSERT INTO `wp_usermeta`
(`user_id`, `meta_key`, `meta_value`)
VALUES
(@user_id, 'wp_user_level', '10');
Replace the set values at the top for `@user_login`, `@user_pass` and `@user_email` with your own settings. Also, if your WordPress installation uses tables that start with a prefix other than `wp_`, you’ll want to replace that in the table names as well.
From: < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "admin, mysql, user access"
} |
Add credit to get_custom_header in alt
Been hunting for a while and I can't figure out how to use `get_custom_header` to get the alt text associated with the media file, so that I can add photo credits to the headers on my site. Am I missing something?
Code to add header image is:
<img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="" />
The `get_custom_header` function doesn't seem to have a way to pull in the alt text. | Use this for the `alt=""` attribute on the custom header `<img>` tag …
alt="<?php
$attachment_id = get_custom_header()->attachment_id;
$alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
if ( count( $alt ) ) echo $alt;
?>" />
… and then just edit the media attachment and add the alt text. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom header, accessibility"
} |
How to restore deleted post related with deleted users
I accidentally deleted post that related to certain users in wordpress because I deleted user. How can I restore those posts?
Thank you! | Go to Pages/Post-->All Pages/Posts-->Click Trash, then restore them.... | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, customization"
} |
How to remove custom background?
I'm using WordPress 3.5.1 and twentyten.
I want to remove the support for custom background. I found this text: <
but i'm a newbie in php, so I dont know what to do whit the information.
I guess I should use this code `<?php remove_custom_background() ?>` but what to do with it? where should I put it?
Thanks! /Frida | Inside the theme folder there should be a file called `functions.php`. Search for the line
add_theme_support( 'custom-background' );
and replace it with
#add_theme_support( 'custom-background' );
which is simply 'deleting' calling the function and thus the possibility to specify a custom background in the admin side. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom background"
} |
Private messaging plugins + custom admin
I have build a simplified version of wordpress admin without all the features and stuff, only posting some specific custom post types and pages. This simplified version addresses a specific role on my normal wordpress operation (since admin is such a fuss to customize), but it lacks some things, such as using the plugin administration from the normal wordpress wp-admin. The wp-admin, still works for administrators only, but they are out of the loop for what I want to implement.
Given the fact that my clients now want to use an internal private messaging system, what are my options here?
Basically I am talking about (backend) pages in the same domain such as wp-admin that have wp-load.php, checks for roles and specific users, custom designed and inside them I want to use, for example, the wp private message plugin or the messaging plugin from wpmu.
Is there any other customizable php class that I could use? | Since the last time, I was able to make my own private messaging system. I do have some other questions which I will post in another "ask question" segment. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": -1,
"tags": "admin"
} |
using shortcodes in theme content
I am using plugin like to read < problem is its using opening and closing shortcodes,when I embed them to my site < only opening short codes displayed,can you please help me? PS:-tried with different themes as well | To put shortcode within a PHP template, use do_shortcode();
<?php
echo do_shortcode( '[like_to_read]The text that is hidden from the user.[/like_to_read]' );
?>
Edit:
<?php
echo do_shortcode( '[like_to_read]' . get_the_content() . '[/like_to_read]' );
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode"
} |
Has parent field in the table wp_term_taxonomy has term_id or term_taxonomy_id
I have created a category "Book" with a sub category "comics", to check how wordpress is maintaining the hierarchy structure. When i check the table "wp_term_taxonomy", I found that such term with a parent has "parent" field populated . As the term id and term_taxonomy_id have the same value for the parent "term name" I am unable to crack whether in the table wp_term_taxonomy do the field, has term_taxonomy_id of the parent term or term_id of the parent | The `parent` column is the `term_id` of a parent term | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 5,
"tags": "database, table"
} |
Get_Posts, only if in both categories
get_posts('numberposts=5&category=93+85')get_posts('numberposts=5&category=9385')
Is there a way to have get_posts grab only posts that are in BOTH categories, as above? | Use `WP_Query`'s `category__and`:
$args = array(
'posts_per_page' => 5,
'category__and' => array( 93, 85 )
);
$my_query = new WP_Query( $args );
while( $my_query->have_posts() ):
$my_query->the_post();
the_title();
endwhile;
wp_reset_postdata(); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "get posts"
} |
Adding a user's ID behind the <a> tag ref link address
Good day, everyone:
I want to make wordpress to add the user's id number behind the ref's link string, so that, for example
<div class="toolsbutton">
<a href=" this page</a>
</div>
above code will be turning in to a link if the user id is 113 who clicked it, the address will become:
<a href=" this page</a>
Or, if you know an alternative to do so, please also let me know.
Generally, the purpose will be that a user will be directed to a page that with unified address but there will be a number equal to his id attached behind. every time, someone click the same link, in same page, will have the same effect on each user. **When a user click it, will be the CURRENT USER, who is a registered user.**
If anyone could tell me if I could create the page at the same time (if not exist), will be terrific!
Thank You | I guess maybe `wp_get_current_user();` is what your looking for.
Something like this...
<?php $current_user = wp_get_current_user(); ?>
<a href=" echo $current_user->ID; ?>">go this page</a>
<
\--
Actually I just re-read the question and maybe your not after the current user? You might want to elaborate the question more so we know the aim better. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, php, functions, links"
} |
How to modify post content?
I still haven't figured this out yet. Is this the right way? I tried `$_POST['content'] = "nothing"` and `$_POST['content'] = 0` neither work for me. I'm using following way
function changeContent() {
$_POST['content'] = "nothing";
}
add_action('publish_post', 'changeContent');
I want to change the content before it's written into the database. | You might check out the `content_edit_pre` filter.
Your example would then look like this:
function wpse89725_pre_edit_content( $content, $post_id ) {
$content = "nothing";
return $content;
}
add_filter( 'content_edit_pre', 'wpse89725_pre_edit_content', 10, 2 );
You can read more about this filter in the Codex:
<
**Edit:**
You can also try the `edit_post_content` filter:
add_filter( 'edit_post_content', 'my_pre_edit_content', 10, 2 );
Since we have in the file `/wp-includes/post.php` these lines:
$value = apply_filters("edit_{$field}", $value, $post_id);
// Old school
$value = apply_filters("{$field_no_prefix}_edit_pre", $value, $post_id);
both of these filters should work, but the filters `*_edit_pre` seems to be on the way out and replaced by `edit_*`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts, database, hooks"
} |
Any way to include custom fields in WP_Query results?
Looking for a way to include custom fields in the output of WP_Query. I am managing a site where nearly every post type has a lot of custom fields defined and it would be much nicer not to have to run get_post_custom in almost every loop. | You may want to hook somewhere in the gazillion hooks available in **`wp-includes/query.php`**.
I would suggest something like this:
function my_always_get_post_custom( $posts ) {
for ( $i = 0; $i < count($posts); $i++ ) {
$custom_fields = get_post_custom( $posts[$i]->ID );
$posts[$i]->custom_fields = $custom_fields;
}
return $posts;
}
add_filter( 'the_posts', 'my_always_get_post_custom' );
In this way you will always have your posts custom fields at hand in your **`$post` object** without having to bother to look for them every time you are setting up a loop. From now on, you can just access them using `$post->custom_fields` as a `multi-dimensional array`. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "custom field, wp query"
} |
Mapping Subdomains in Wordpress to give the appearance of a localised site, best approach?
I am building a classifieds website and am using Wordpress for the functionality of user accounts, Paypal integration, custom taxonomies and of course super flexible custom post types for the listings.
I would like to be able to map a subdomain to a particular sub-site. For example: australia.somesite.com or brisbane.somesite.com and have it localise the site to that particular region.
Is there a clean-cut way of doing this with Wordpress, possible that someone else has surely already done this. | Sort of a vague question, but I think I understand what you're getting at. You'd need to use a Wordpress Multisite installation, which will effectively create localized blogs on a subdomain (brisbane.example.com, perth.example.com).
Using a single site Wordpress installation to do this is possible, using CNAME mapping on the domain, however this would not suit your goal as you won't be able to **post within the localized listing**.
To achieve the subdomain for category "effect", with the least amount of effort, you should use Multisite. I hope that answers your question.
A good rundown of getting Multisite going can be found at WPMUDEV. Hope this helps.
The Wordpress.org version can be found at:
And this is the last bit of info you'd need to look at:
Cheers! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, custom taxonomy, directory, localization, subdomains"
} |
Override default jquery ui library with newer version
The latest version of jquery ui core fixes a bug that's on my site. The problem is that Wordpress comes with an earlier version.
How do I override the default jquery ui core? One solution I've found is to edit the script-loader.php file in wordpress includes folder but I don't want to touch the WordPress core unless I have to.
Below is the core change that worked that I want to avoid.
$scripts->add( 'jquery-ui-core', '/wp-content/themes/themefolder/jquery.ui.core.min.js', array('jquery'), '1.9.2', 1 ); | Add the following code in functions.php file of your theme that will remove default jquery ui core and will add your provided latest jquery ui core file from your theme.
function my_scripts_method() {
if(!is_admin()){
wp_deregister_script( 'jquery-ui-core' );
wp_enqueue_script('jquery-ui-core', get_stylesheet_directory_uri().'/jquery.ui.core.min.js', array('jquery'), '1.9.2', 1 );
}
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
Tell me if it works for you or i provide you another solution... | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "jquery, wp enqueue script, jquery ui"
} |
How we can get "get_post_meta" of specific user who added it
Basically i have front end form which store the notes and tags of post. And every user who logged in can store there own notes and tags. But i want when he view the notes and tags he can only see here own notes and tags not all the notes and tags of every one.
For example there are 100 post there. Every user have an option to save notes and tags of each post and no one other can be able to see there notes and tags. so when user logged in he can able to view there notes and tags which he added. | There are various ways to achieve this you can either generate metakey value for update_post_meta in such a way that it will contain user id.
//Example :
global $user_ID,$post_ID;
// Store the values
update_post_meta($post_ID, 'meta_key'.$user_ID, '$meta_value');
// Get the values
$meta_values = get_post_meta($post_ID, 'meta_key'.$user_ID);
or you can save it in user meta as following
//Example :
global $user_ID,$post_ID;
// Store the values
update_user_meta( $user_ID, 'meta_key'.$post_ID, 'meta_value' );
// Get the values
$meta_values = get_usermeta( $user_ID, 'meta_key'.$post_ID ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post meta"
} |
How to handle a shortcode function directly?
I was wondering how i can handle a shortcode function directly? At the moment i have created a shortcode which works OK. The shortcode function outputs a image.
Now in functions.php i have another function which needs the output image. I am using the do_shortcode and it works.
$image = do_shortcode('[route_thumb id="'.$post_id.'"]') ;
but how can i call the function directly this one didn't work
$image = route_thumb_function($atts['id']=$post_id); | Shortcode handler function receives two arguments array `$attr` and string `$content`. So to pass attributes to shortcode handler function, just pass it as array:
$image = route_thumb_function( array( 'id' => $post_id ) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode"
} |
Including new Javascript only after a comment is made
I am looking to call a new javascript function only after a new comment has been made by a user. Specifically, I want to include new javascript on the resulting page of the page reload after submitting the new comment form on a blog post.
Does anyone know how to do this?
My end goal is that I want to make a call using Mixpanel's (< javascript API call and make an event called "Comment added" for a specific user. I know how to do the mixpanel side of things but am confused by the this specific use case of wordpress.
Thanks in advance! | I am not so clear where exactly you would want to "inject" this JS . `"After a new comment has been made"` , in WP terms and php workflow, can mean several things . (for example when the $POST request is made , when the action is triggered ,when it is getting checked, sanitized , when it is inserted to the DB etc etc ..)
Anyhow ,you will need to search for the right wp actions / filters that you can hook into , like the `comment_post` action ( unfortunately undocumented in codex - GIYBF ) ,or the `comment_post_redirect` filter (Also undocumented in codex) or `wp_insert_comment` action (runs AFTER comment inserted to DB) and use those actions to include the JS ..
for example :
add_action ('comment_post','my_comments_js_function');// runs when comments are POSTED
and then
my_comments_js_function(){
// do your JS stuff.
}
But like I said, it is not really clear to me what exactly you want and WHEN . | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "posts, comments, comment form"
} |
theme path in javascript file
I need to include the path to my theme file within a javascript file. How would I go about this? I have already tried:
var templateUrl = "<?php get_stylesheet_directory_uri(); ?>";
function LightboxOptions() {
this.fileLoadingImage = "'"+templateUrl+"/img/loading.gif'";
this.fileCloseImage = "'"+templateUrl+"/img/close.png'";
this.resizeDuration = 700;
this.fadeDuration = 500;
this.labelImage = "Image";
this.labelOf = "of";
}
This does not give me the path, but just inserts `<?php get_stylesheet_directory_uri(); ?>` instead of the actual path. Any ideas? Thanks in advance! | What you're looking for is wp_localize_script function.
You use it like this when enqueing script
wp_register_script( 'my-script', 'myscript_url' );
wp_enqueue_script( 'my-script' );
$translation_array = array( 'templateUrl' => get_stylesheet_directory_uri() );
//after wp_enqueue_script
wp_localize_script( 'my-script', 'object_name', $translation_array );
In your style.js, there is going to be:
var templateUrl = object_name.templateUrl;
... | stackexchange-wordpress | {
"answer_score": 41,
"question_score": 17,
"tags": "theme development, themes, javascript, paths"
} |
problem with guid, when i change the folder name
I'm new to WordPress. I started the site as good with folder name `wordpress`. After I changed the folder name from `wordpress` to `test`. And also change the **siteurl** from ` to ` in wp_options table. And I modified the **guid** with this refer.
My problem is, still I click any 'post' or 'comment', that goes to ` page only. I want that's goes to `
Anyone can? | After changing siteurl, Go to admin panel and update permalink structure once and check.It will start working with new folder name.
Hope it helps | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "site url, guids"
} |
Show menu on page with all sub-pages and sub-sub-pages of that page
I am trying to create a menu, with sub-pages and sub-sub-pages of a current page.
I want the menu to work as a dropdown, where the sub-sub-pages for a sub-pages are shown when the user clicks the sub-page, and hidden again if the user clicks on the sub-page a second time. So it is important that the sub-pages in the menu are not links.
I need to show the same menu, no matter how deep in the sub pages the user is at.
Can anyone help? :) | You can use `get_page_children` function to retrieve all sub pages
$the_query = new WP_Query( array( 'post_type' => 'page', 'posts_per_page' => -1 ) );
$children = get_page_children( get_the_ID(), $the_query->query() );
if ( !empty( $children ) ) {
foreach ( $children as $child ) {
// render menu
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sub menu, wp list pages"
} |
Fetch the latest post with attachment image
What I want to do seems to be simple but I can't get around it. I'd like to get the latest post that has an image attachment. A little help would be appreciated. Thanks
Lita | This is a tricky one. If you wanted to get the latest image attachment and display the post associated with it, you could use:
$attachments = get_posts('post_type=attachment');
$first_attachment_post = get_post($attachments[0]->post_parent);
To get the latest post, but only if it has an attachment, I think the only way to do it would be with two nested queries. For example:
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();
$attachments = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image') );
if ( $attachments ) {
// Post output here will only be display if attachments are found
echo '<li>' . get_the_title() . '</li>';
}
endwhile; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images"
} |
Theme thumbnail in dashboard
I'm not sure whether this question belongs here but I don't know where else to ask it : do WordPress designers/developers usually create a dashboard theme thumbnail when they completed the WP theme for their client? If so, do they put their own logo on it or a screenshot of the home page? | Thats entirely up to to you.
I generally create a theme thumbnail from the PSD file, or, when the theme changes a lot between designing and developing, I tend to create one from a screenshot.
Look at the Themes Directory, you can see some of the developers actually don't use a screenshot but some other image.
If you want to put your own logo in the theme thumbnail, thats okay. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, themes, thumbnails"
} |
Different thumbnails for index and article page
For my aricles (wp7app.de) I'd like to use two different thumbnails, one which is displayed only on the index page (150x150) and one for the article page (600x400). However, I don't want to use a cropped version of the big image for the index. Is this something that can be done easily without an extra plugin or can you recommend a good / simple one? Cheers | I ended up using the "Multiple Post Thumbnails" plugin which I'm quite happy with: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post thumbnails, thumbnails"
} |
Creating shortcodes with user created forms
I am creating a plugin. That enables users to create forms, & display these with shortcodes on a site. When creating a form (using custom post types), users will be able to add additional form fields with meta boxes.
My question: When a user creates a form (via custom post type), how do I store the field type so the shortcode knows which type to display for the form? | Store each field the user creates as an array in a post meta field, the array would contain the name and a reference to the field type. You could also store additional data within the array, like if it's required and the type of validation to apply. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, shortcode"
} |
Using $wpdb to update current post
I have a function that expires posts on a date, and adds a check to the database. Now, I'd like the ability to "recycle" those posts with new expiration date, but in order to do this, I need to erase the _expiration_date_processed entry. Is the function below the best way to achieve this, especially in the case where there is a status change for multiple posts using quick edit? Thank you for any insights.
add_action('draft_to_published','gcpl_draft_to_published');
function gcpl_draft_to_published($post){
global $post;
global $wpdb;
$current_id = $post->ID;
$processsql = 'select meta_value from '.$wpdb->postmeta.' where meta_key = "_expiration-date-processed" AND post_id = '.$current_id.'';
$processresult = $wpdb->get_col($processsql);
if (!empty($processresult)) foreach ($current_id as $a) {
delete_post_meta($a->post_id, '_expiration-date-processed');
}
} | Nevermind, I was complicating this whole process because I wasn't thinking about just using get_post_meta().
add_action('draft_to_publish','gcpl_draft_to_published');
function gcpl_draft_to_published($post){
$exp_processed = get_post_meta($post->ID, '_expiration-date-processed', true);
// check if the custom field has a value
if($exp_processed != '') {
delete_post_meta($post->ID, '_expiration-date-processed');
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wpdb"
} |
How to store post meta in an array
I am creating a plugin, where the user can create forms with an unlimited amount of fields. I would like to store each field the user creates as an array in a post meta field. What would the code look like for this please? (This is the first plugin i've ever created). @Wyck previously touched on this topic below, but didn't outline the complete code. I'm quite confused about the requirements.
Link to this topic discussed previously
Thanks! | WordPress automatically serializes/unserializes the data when it's stored and retrieved, all you need to do is pass a php array as your data and you'll get the same array back when you `get_post_meta`.
$data = array(
'label' => 'something',
'desc' => 'someval',
'id' => 'someval',
'type' => 'someval'
);
update_post_meta( $post_id, 'your_key', $data );
$data = array(
'field_1' => array(
'label' => 'something',
'desc' => 'someval',
'id' => 'someval',
'type' => 'someval'
),
'field_2' => array(
'label' => 'something',
'desc' => 'someval',
'id' => 'someval',
'type' => 'someval'
)
);
update_post_meta( $post_id, 'your_key', $data ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom field"
} |
Fixing YARPP plugin FULLTEXT MySQL indexing
I just found out that the Yet Another Related Posts plugin (YARPP) uses FULLTEXT indexes on the wp-posts table, which greatly slows down sites with a large amount of posts.
Can I can just delete the plugin, or do I have to clean out the wp-posts table of those indexes in order to fix the issue? | YARPP doesn't do anything on uninstall.
So you have to uninstall it then go remove the indexes manually from the DB. The index names should be prefixed with `yarpp_`. Very untested SQL follows:
SHOW INDEXES ON wp_posts;
DROP INDEX yarpp_title ON wp_posts;
DROP INDEX yarpp_content ON wp_posts; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database"
} |
What are the main parts of a Wordpress Template?
This may sound like a stupid question, but...
What are the main parts of a Wordpress template, and which parts are mandatory and which parts are optional?
So far I am aware of:
* Posts (mandatory)
* Pages (mandatory)
* Page Templates (optional)
* Tags (optional)
* Categories (optional)
* Search / Search Results (mandatory)
* Archives (mandatory)
* Widgets (optional)
Is there anything else? | Indeed, it is as toscho has said. index.php and style.css are the bare minumum.
Developers like to separate things, though, so instead of having one index.php file to rule all, you'll find parts like:
header.php
footer.php
sidebar.php
index.php
style.css
functions.php
and additional templates like ones you mentioned in the question.
This page will show you how its done at the minimum level. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "templates, customization"
} |
Custom image size not regenerating when image editted
I have a custom image size at 200x150 that works fine in a plugin I'm working on. Uploading new files is no problem but when I edit an image, the default image sizes get regenerated but my custom size does not. Is there a way to force the regeneration programatically in a filter or something? | To regenerate custom image size when image is edited in image editor , You have to add following options in wp_options table using update_option function along with add_image_size.
**Example :**
$img_size_name = 'custom-size'; // The new image size name.
if ( function_exists( 'add_theme_support' ) )
add_image_size($img_size_name, 100, 100 , true);
update_option($img_size_name.'_size_w', 100);
update_option($img_size_name.'_size_h', 100);
update_option($img_size_name.'_crop', 1); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "images, cropping"
} |
Does the 'nav_menu_css_class' filter accept 2 or 3 arguments?
I've been using the `nav_menu_css_class` filter in one of my plugins, implemented as:
add_filter( 'nav_menu_css_class', 'wbwcrf_nav_menu_css_class', 10, 3 );
function wbwcrf_nav_menu_css_class( $classes, $item, $args )
{
/* snip */
return $classes;
}
The filter clearly has 3 arguments in the code (source) yet someone using my plugin has told me they get the error `Warning: Missing argument 3 for wbwcrf_nav_menu_css_class()`.
So I looked at the codex documentation on `nav_menu_css_class` which has an example using 2 arguments, I changed my code to 2 arguments since I'm not actually using the $args argument and everything seems to be working fine.
But I'm still really stumped as to why the source has 3 arguments yet the codex has 2 and why I don't receive any error when using 3 arguments, yet someone using my plugin does. Anyone able to clear up my confusion here please? | I can confirm that this filter applied with 3 parameters as you mentioned in your snippet. The warning is very strange and shouldn't appear if WordPress core wan't hacked.
The best practice for this case is to request parameters, which are required by your hook. So if you don't use `$args`, so don't request it:
add_filter( 'nav_menu_css_class', 'wbwcrf_nav_menu_css_class', 10, 2 );
function wbwcrf_nav_menu_css_class( $classes, $item )
{
// ...
}
Another approach is to set default values for income arguments:
add_filter( 'nav_menu_css_class', 'wbwcrf_nav_menu_css_class', 10, 3 );
function wbwcrf_nav_menu_css_class( $classes, $item, $args = array() )
{
// ...
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, menus, filters, hooks, walker"
} |
Author_meta ONLY if it exists
I'd like to ONLY show the authors website link if it exists, but I can't work out the exact syntax for it.
I have this
if ( get_the_author_meta('user_url') ) : // If a user has filled out their decscription show a bio on their entries
echo the_author_meta('user_url');
endif;
But I need to wrap it in a link and give that link a class, like this
<a class="meta-website" href="<?php the_author_meta('user_url') ?>">Author's Website</a>
The problem is when I add another 'echo' before the_author_meta one it just breaks the site. | Try passing $user_ID global variable to function as following. it is working for me.
<?php
global $user_ID;
if ( get_the_author_meta('user_url',$user_ID) ) : // If a user has filled out their decscription show a bio on their entries
?>
<a class="meta-website" href="<?php the_author_meta('user_url',$user_ID); ?>">Author's Website</a>
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post meta"
} |
How to use the empty space left and right of a post?
(WordPress 3.5.1, theme 20-11)
I would like to use the red colored areas left and right to a post and can't find information on what plugin might deal with that.
How can I add content there - widgets f.x. Or would I have to change the theme? I would prefer to not alter the code for this purpose.
!enter image description here | Here's how to get a sidebar next to pages and single-post pages:
1. Install "Twenty Eleven Theme Extensions"
2. Go to Appearance > Theme Extensions
3. Select "Enable the widget sidebar on (single-post) pages"
Done. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin recommendation, sidebar"
} |
Gallery Only Displaying One Thumbnail
My image galleries are showing only one thumbnail in the post the gallery sits in. <
**My single.php markup can be found here:** <
Additionally, previous_image_link and next_image_link are not displaying when the image is clicked (these would lead to the other images in the gallery).
**My entire image.php markup can be found here:** <
**My gallery shortcode:** `[gallery link="post" ids="2245,2246,2247"]` | It ended up being a problem with a code to pull a custom number of posts via an options panel. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "gallery, errors"
} |
Update a WordPress website FROM Twitter or Facebook
I'm looking for a way to update a wordpress website when I post something to a specific twitter or facebook account. Is it possible? Is there any plugin that do this?
I find only plugins that do the inverse, updating social networks from WordPress. What I'd like to do is to update WordPress from my social network accounts. | You can do this with the If This Then That service.
You will have to enable posting via XML-RPC (enabled by default in WP 3.5+), Then you can create a recipe which uses Twitter or FaceBook as the trigger, and WordPress as the action. If you poke around, someone has probably already created these recipes. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, automatic updates, automation, social connect"
} |
Is there a way to direct unregistered user to registration page when click a link?
everyone: this question seems pretty commmon to ask, but I did not find any answer.
I was wondering, if there is a php function that I could use to direct a user to the site's registartion page, so that I can use php instead of link that I need to customize every time I change the link.
THank you | It's simple, use the function `is_user_logged_in`:
<?php if ( is_user_logged_in() ) { ?>
<a hef="link-for-logged-users"></a>
<?php } else { ?>
<a hef="link-for-users-not-logged-in"></a>
<?php } ?>
See here < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, user registration, buttons, references"
} |
Noob Loop Question
I come with a basic question but I can not solve, I think that will be easy for you. I would like, if I have 2 or more post on loop, show the entire loop. I tried the following:
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$portfolio = new WP_Query(array('post_type' => 'project', 'posts_per_page' => 12, 'paged' => $paged));
$count = 0; ?>
<?php if ($portfolio < 2) : ?>
[CONTENT LOOP]
<?php if ($portfolio) : while ($portfolio->have_posts()) : $portfolio->the_post();
[/CONTENT LOOP]
<?php endwhile; ?>
<?php endif; ?>
<?php endif; ?>
However, that didnt work, the single post still appearing. Like I said, if i have one post in the loop, will show nothing of the loop. Sorry for the question, is that I'm not very familiar with wordpress yet. Thank you! | If you want to check the number of posts on each page, you can use the `found_posts` method of `WP_Query` :
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$portfolio = new WP_Query(array('post_type' => 'project', 'posts_per_page' => 12, 'paged' => $paged));
if ($portfolio && $portfolio->found_posts >= 2) :
while ($portfolio->have_posts()) : $portfolio->the_post();
echo "<div>";
the_title();
echo "</div>";
endwhile;
endif;
wp_reset_postdata();
?>
and here we use `$portfolio->found_posts >= 2` to check if we got `2` or more posts on the page. Finally `wp_reset_postdata()` is added to restore the global `$post` to the current post in the main query. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, loop, support"
} |
Shortcodes that are created based on user input information
I am creating a plugin that users can create forms with. Then the user will be able to input a shortcode to display this form. The shortcode will be the form name, which is stored as a `meta_value` in the `wp_postmeta` table. When the user uses a shortcode, how do I refer back to the form name & display the form?
When the user creates a form, should I automatically create a shortcode in the same script? How would you approach it? | You could use it like
[form id="abc123"]
where the value of `id` is the `meta_value`. You could generate the shortcode so the user can easily copy/paste it into the editor. Or even have a custom made button in the editor to insert it.
You can check how it's done in other plugins like `Contact Form 7`:
[contact-form-7 id="50" title="My form"]
<
and `Fast Secure Contact Form`:
[si-contact-form form='1']
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode"
} |
Custom Portfolio String
I have a field on my portfolio admin page which shows the url when the user write a url(obviosly).
I want to when the user write in the field, elements appear along with it. And if the field is empty dont shows anything.
The code that shows what the user is writing in this field is:
<?php echo get_post_meta($post->ID, '_url', TRUE);?>
I tried:
<?php if (strpos($post->ID,'_url') !== true) { ?>
[CONTENT] <?php echo get_post_meta($post->ID, '_url', TRUE); ?> [/CONTENT]
<?php } ?> | Just write a if statement using the `get_post_meta` like this
<?php if(get_post_meta($post->ID, '_url', true)){?>
<p> Display some stuff.</p>
<?php } ?>
There is an example here < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, php, query string"
} |
Custom post types loop on a page template
Hi I'm trying to make a page template that shows a list of a custom post type ordered by a meta key, I easily made it with `query_posts` but I am trying to do it via `pre_get_posts` so I made a function like this:
add_action('pre_get_posts', 'events');
function events($query) {
if ( is_page_template('page-myevents.php') ){
$query->set('post_type', 'events');
$query->set( 'meta_key', 'start' );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'DESC' );
$query->set('numberposts', 5);
}
}
But it does not work when i enter the page it sends me to the 404 page, I even added `$query->get_posts()` but nothing I get errors with that, any suggestions? | I'm not sure this is possible. Why do you need a page template? Why can't you use a custom post type archive, which is built-in to WordPress ( if you register the post type with `has_archive` set to true). I'm ignoring all your other possible $args, because I don't know how you are registering this post type.
register_post_type( 'events', array( 'has_archive' => true ) );
Then you can just adjust the query to order by the meta
add_action('pre_get_posts', 'events');
function events($query) {
if ( is_post_type_archive('events' ) ){
add_query_var( 'meta_key', 'start' );
add_query_var( 'orderby', 'meta_value_num' );
add_query_var( 'order', 'DESC' );
add_query_var('numberposts', 5);
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, query, pre get posts"
} |
Change filename during upload
I check the below answer to rename files during upload and tries to change it to something like postid_originalfilename.jpg but failed. Any help?
function make_filename_hash($filename) {
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
return md5($name) . $ext;
}
add_filter('sanitize_file_name', 'make_filename_hash', 10);
< | If you want to use the above `sanitize_file_name` filter, you could try this:
function make_filename_hash($filename) {
if( isset($_REQUEST['post_id']) ) {
$post_id = (int)$_REQUEST['post_id'];
}else{
$post_id=0;
}
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
if($post_id>0){
return $post_id."_".$name . $ext;
}else{
return $name . $ext;
}
}
add_filter('sanitize_file_name', 'make_filename_hash', 10);
where for example `image.jpg` is changed to `123_image.jpg` where 123 is the parent post id. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "attachments, sanitization"
} |
Editor background colour in full screen
In this Q&A, How do you change the visual editor's background color?, it is shown how to modify WordPress' editor background colour.
My question is how can I modify the editor's background colour, in full screen mode? (also called "distraction free" mode).
The solution in the linked thread does not work for full screen editor mode. | This kind of problems are solved using Chrome Inspector or Firefox Firebug.
Inspecting the element, we get the necessary ID's or Classes to add in the stylesheet.
; $content = apply_filters('the_content', $post->post_content); echo $content; ?>
How can I add to or filter this snippet to allow the shortcodes from said page to fully display, rather than outputting raw [/tab] text? | If you want to display the shortcodes in the string variable `$content` you can use the Wordpress function `do_shortcode()` like this:
echo do_shortcode($content);
See more in the Codex:
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, shortcode"
} |
Why Editor reformats my code
I'm using TinyMCE Advanced and SyntaxHighliter plugins on my WordPress install.
Why does the editor change my inserted code, from:
[php]
<?php
/**
echo('code');
/**/
[/php]
to:
[php]
<!--?php <br ?-->/**
echo('code');
/**/
[/php] | I suggest you to use `htmlspecialchars()` before sending content and`htmlspecialchars_decode()` before showing content on page, here is functions that you need to copy/paste to your functions.php :
function wp_po9568($content)
{
return htmlspecialchars($content);
}
add_filter('content_save_pre','wp_po9568');
And:
function wp_po5689($content)
{
return htmlspecialchars_decode($content);
}
add_filter( 'the_content','wp_po5689');
Wordpress by default comments out php tags. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "tinymce, editor"
} |
custom permlink .htaccess file 404 Not Found error
i read alot of atricles taking about this but i could fix my problem yet .. i want to make the permlink custom
> /%category%/%postname%
and i searched for the .htaccess in the wordpress files and i couldn't find it so i created one and added this code
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /sitename/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /sitename/index.php [L]
</IfModule>
# END WordPress
in the RewriteBase this name is the name of the folder of wordpress in my hosting , when i open my site the permlink changed as i want but when i open the page it gives me an error 404 Not Found error by the way i tried to choose the twentytwelve but its not working also , i added the .haccess file in the file mythemes in mytemplate is that the right place ?? | If your Wordpress installation is in the folder 'sitename', than this .htaccess should go in that folder. Not your theme folder.
From the Wordpress codex: WordPress's index.php and .htaccess files should be together in the directory indicated by the Site address (URL) setting on your General Options page (< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, htaccess"
} |
How to use is_feed() to target a category feed?
`is_feed` (one of the many conditional tags) can be used to determine if the current query is for a feed.
But how do I use it to target all category feeds? (or tag or custom taxonomy feeds for that matter)
This doesn't seem right:
if (is_category()) {
if (is_feed()) {
// Code Goes here
}
}
And I have no clue as to whatelse I'd try. | If you want to determine if you are in a category feed, for example:
you can do so with
add_action('wp', 'mycheck');
function mycheck() {
if(is_feed() && is_category() ){
// do stuff
}
}
or
add_action('wp', 'mycheck');
function mycheck() {
global $wp_query;
if($wp_query->is_feed && $wp_query->is_category){
// do stuff
}
}
You can similarly check if you are in a tag feed, for example:
with `is_tag`.
You can then check if you are in a custom taxonomy feed, for example:
with `is_tax`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "feed, conditional tags"
} |
How to declare WooCommerce support in your theme
I have built my own theme, which integrates quite well with WooCommerce, but I want to know how to properly get rid of the notification on top of my theme that said my theme didn't support WooCommerce / properly declare support (going a bit further than just clicking away the message). | Digging into the code that generates the notification (`current_theme_supports('woocommerce')`) gives the answer: place `add_theme_support( 'woocommerce' );` in your functions.php
simple! | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 9,
"tags": "plugins"
} |
Cannot locate specific <a href> link/string using String Translation with WPML?
I have added a link on the footer of my page in the format
`<a href="URL">Link</a>`
I would like to allow wmpl to translate it in french and have tried scanning my theme but the link's text doesn't appear in the string translation manager in the dashboard.
After reading this: < I have tried wrapping the link in gettext but do not know how to add an href link into this line of Php:
##
How could I do that? | You need to put your strings in translatable format.
<a href="URL"><?php _e( 'Link', 'your-theme-text-domain'); ?></a>
Function reference: **`_e()`**, this one `echo`es the value, for assignment, use `$my_string = __( 'String', 'text-domain' );`.
Also, check the following documentation: WordPress_in_Your_Language#Introduction and WPML - Getting String Translation to Work. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin wpml"
} |
Sorting posts by custom field value in array
I have a custom field value that is an array and it has date as one of the values:
a:3:{s:4:"date";s:10:"03/06/2013";s:6:"target";d:1000;s:8:"currency";s:3:"USD";}
I'm trying to sort posts with this date but I'm having trouble doing it.
Here is my query:
$args = array (
'showposts' => -1,
'post_type' => 'project',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'date',
'value' => date('m/d/Y'),
'compare' => '>=',
'type' => 'DATETIME',
)
),
'cat' => $cat_id);
$posts = get_posts( $args ); | Sadly you can't.
You can't query based on serialized data and since you store the data in an array it is saved as serialized.
you should use a separate row for each field you want to query / sort based on.
**I asked this same question about two years ago**. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, custom field"
} |
Add class to DIV depending on page loaded
I'm designing a new theme and in my page template a have a section where an image is displayed . I would like this image to change depending on which page is loaded.
The section is a DIV like this: `<DIV class="ximage"></DIV>`
What I would like to do is to add a class to the DIV depending om page loaded and then style the class with background-image in CSS.
I know you can do this with for example body_class() if you want to add classes to BODY. But how do I do this with a DIV?
There will be quite a few pages in this theme, so ceate a template for each page seems wrong. | You might want to consider using the Wordpress function `body_class()`
<body <?php body_class($class); ?>>
Then you could use the body class as your current page reference.
This function is for example used by the Twenty-Twelve theme.
For a single post it will become
<body class="single single-post ...">
and for the home page:
<body class="home blog ...">
You can read more about this function in the Codex here:
<
**Edit:**
> I know you can do this with for example body_class() if you want to add classes to BODY. But how do I do this with a DIV?
You could use it in your `div` tag:
<div <?php body_class(); ?>></div>
but it should be sufficient to have this only in the `body` tag. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, css, conditional tags, conditional content"
} |
Display Something in the Header After All Styles are Loaded
I'd like to include a functionality in a theme that will overwrite styles from previously included CSS files. For this purpose, I need to be able to display a `<style>` in the header after ALL stylesheets have been displayed.
Is there a hook to do this? | Hook to `wp_enqueue_scripts` with a high priority number. For example:
function load_my_style_wpse_90225() {
wp_register_style( 'mystyle', get_template_directory_uri() .'/path/to/stylesheet.css');
wp_enqueue_style( 'mystyle' );
}
add_action('wp_enqueue_scripts','load_my_style_wpse_90225',1000);
That should reasonably load last in line.
Basically the same answer as here: Wooslider custom css
## Refernce
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "css, actions, wp enqueue style, wp head"
} |
Contact information footer
I am new to Wordpress but forced to create a website as a Wordpress template for my current employee (I am a front end developer, mostly build new systems/apps etc from scratch). Creating the template is no issue, but how do I go about making everything fully editable? For example the footer: it contains contact information and I would like information to be fully editable from within the Wordpress admin. Everything however seems to resolve around posts and articles... so, my first idea was to simply make posts and categorize those as "Footer" and then filter the displayed posts on the loop in footer.php by that category but that doesn't seem very logical. What is a more common approach? Widgets? If widgets is the answer, how exactly do those present themselves in the admin section?
Sorry for the long question :) | Another option is to create a new post type called "modules" or something to that effect. Then you can create as many of those as you like, for example, "Footer: Contact Information," "Footer: Social Media," "Header: Callout," etc, and you can use that post's ID to bring it into the designated spots in your template.
While the sidebar suggestion from Jacob is also good, if you have a lot of those one-offs, it can get pretty overwhelming to manage. By making it a post type, you can search it, you get a WYSIWYG editor, and you can add additional custom fields if needed. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop, widgets, footer"
} |
Theme URLs problem
I programmed a theme post (edit: probably that's the `single.php` template) which uses the function `get_userdata( $_GET['p'] )`. But the main admin reformatted urls to this: `~/author/gamelaster` (default is `?author=1`) and now this is not working correctly.
> How do I get the id of Author in this URL format?
Or
> how do I get user slug + get id from database?
But, I cannot use the standard author functions/post functions(get_ID etc). | If you are on an "Author" page, and since you mentioned `author.php` it seems that you are, `get_queried_object()` will give you the author data, which it seems is what you want.
Try:
var_dump(get_queried_object());
I believe that is all the information you need. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes"
} |
Dynamic content in a static page
I have developed some calculators (in php) for my website and I need Wordpress integration. The calculators have a form and, after submission, the result is shown. The result depends on a query in the database. **Is it possible to create "static pages" (at least static URLs) that provide to the user dynamic content?**
Just to clearfy, I want something like:
website/blog
website/forum
website/calculators
website/calculators/one
website/calculators/two
I heard about Pages, but I cannot include php code on it. Worth point out that the calculators aren't static, the result will change everyday. | You _do_ want static pages. The easiest way to do this, and a very good way even if perhaps not the only way, is:
1. Create one or more custom template files for your static pages. This is where your PHP comes in.
/*
Template Name: Calculator
*/
get_header();
// your calculator code
// Whatever PHP you have should work
// This is very minimal. You may want something more complicated.
get_footer();
2. Save the file as some name not on the reserved list
3. Create your static pages from wp_admin->Pages. Why creating the pages, save them with appropriate "Template"-- that is, one of the ones you've created. (Look in the right sidebar under "Page Attributes".)
This way, you can keep the calculator pages consistent with the other pages on the site. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "pages"
} |
What is the purpose of $merged_filters?
Savvy WordPress user here, or at least trying to be. I have the hang of hooks and filters with the code in WP's plugin.php
The only thing I cannot seem to understand is the $merged_filters global. The value for a tag is unset when a filter or action is added.
However, when an action or filter is executed, the $merged_filters[$tag] value is set to "true".
What is the purpose of this?
Thank you | For those of you who may be wondering what this does - I have figured it out.
When a new function is added to an action/filter hook, it is added at the end of the array. However, WordPress specifies that those functions are to be executed by priority.
When a function is added, merged_filters is used to keep track of whether functions for a hook have been sorted by priority or not. merged_filters is checked on do_action/apply_filters to determine whether the functions should be sorted (by priority) or not before the hook is executed | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugins, filters, actions"
} |
how to get all the child category name in a specified category name?
Supposed the specified category name is "product", which has three layered sub-categories. The structure is like the following:
* product one
* product two
* product three
* product four
I want to output all the subcategory names in the `sidebar.php` of my theme. How do I do?
in my theme index.php i using: `<?php include("productHallofHome.php");?>` in productHallofHome.php i using code:
<ul class="productList_h">
<?php wp_list_categories( 'child_of=4&depth=0'); ?>
</ul> | Please have a look at `wp_list_categories`, which is all you need. Just choose the arguments to your liking and place the code in your sidebar.
Suppose, the ID of your 'product' category is 666, then the basic code could look like the following:
<ul>
<?php wp_list_categories( 'child_of=666&hide_empty=0'); ?>
</ul> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development, wp query"
} |
Plugin update, is a deactivation and activation done?
When a plugin is being updated via the automatic updater, is that plugin deactivated and then re activated when the plugin update is finished?
Also is a maintenance file created during theme and plugin updates, or only during core updates? | According to the source code of _wp-admin/includes/class-wp-upgrader.php_
**Single plugin update:**
add_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade'), 10, 2);
add_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'), 10, 4);
It'll deactivate the plugin before upgrade and you need to re-activate it manually after upgrade.
No maintenance file generated
**Bulk Pluigns Update**
add_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'), 10, 4);
// Only start maintenance mode if running in Multisite OR the plugin is in use
No deactivation before upgrade. The plugin status will be as what it was. So, if it is activated now, it'll still be activated after upgrade.
And maintenance file will be generated if running in Multisite OR the plugin is in use.
I urge you to read the source code yourself in case if I'm wrong. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
How we redirect to other pages in WordPress?
I am using an `onclick` function to redirect the user if they are not login.
I am calling a php function in achor tag like this
<a href="#" class="fright hrtacnhor" onclick="<?php checkstatus(); ?>">save to my favorite</a>
and the function I am using is
<?php
function checkstatus(){
wp_redirect( get_permalink( 8 ) );exit;
}
?>
But the problem is that when i click it not call the fucntion. I also try to use `wp_redirect()` function directly in `onclick` but it not working so any one please guide me how it works. Thanks | You could do the redirect by means of JavaScript:
<a href="#" class="fright hrtacnhor" onclick="window.location='<?php echo get_permalink( 8 ) ?>'">save to my favorite</a>
But why yould you want to do it that way and not just use the link directly? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp redirect"
} |
Best Practice: Remove data on deactivation or uninstall?
When is it appropriate to remove a plugin's settings? On deactivation or uninstall? | Remove data only on uninstall. Deactivating plugins can be done by mistake or in order to troubleshot some other problem and you don't want to make the plugin users to config everything again in this situation.
Think about your PC software, does it delete its data when it is being closed and become inactive? no, only when it is uninstalled. Same applies here.
Actually the uninstall option is relatively new and it was created specifically to have a point where you know it is safe to delete data. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins"
} |
Utilize Function in Child Theme / Template File
With a plugin, I have used require_once in the init.php of a plugin that I have made for my site to make functions available.
With a child theme, where should I put the calls to require_once? When I put them into the template file that uses it, it doesn't seem to work.
### EDIT
I would have thought that this
locate_template('../../plugins/events-and-bookings/lib/class_eab_event_model.php', true, false);
Would be equivalent to this:
if (!function_exists('jupiter_init')) {
function jupiter_init() {
require_once('../../plugins/events-and-bookings/lib/class_eab_event_model.php');
}
}
But the first code snipper isn't working (but the second one is). I am placing both in the functions.php file of my child theme right after the initial | When you create a theme, you can use `functions.php` file for all utilize functions. Also this is the best place for all your `require_once` calls.
One trick I would like to recommend for theme development approach:
Don't use direct `require_one` call to include your scripts. Instead of it, use `locate_template` function to load scripts. By using this function, all child themes will be able to override your scripts. So for instance, you have file called `utilize.php`, and it lies in `inc` folder of your theme, then instead of calling `require_once 'inc/utilize.php';`, call `locate_template( 'inc/utilize.php', true, false );`.
Now it will be possible to create `inc/utilize.php` file in a child theme and override parent file. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, functions"
} |
How to add style to category link?
<h1><?php the_category(' • '); ?> » <a href="<?php the_permalink(); ?>" class="my-title-class"><?php the_title(); ?></a></h1>
How to add `class="my-category-class"` to the links, produces by `the_category` function? | You can use `the_category` filter to hook a callback function like this:
add_filter('the_category','add_class_to_category',10,3);
function add_class_to_category( $thelist, $separator, $parents){
$class_to_add = 'my-category-class';
return str_replace('<a href="', '<a class="' . $class_to_add . '" href="', $thelist);
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "categories"
} |
display specific sidebar for each role
Does someone know if it's possible to display a specific sidebar per user-role ? (only accessible if the user is logged as the specific role related to the specific sidebar )?
What I want is to have one "profile-like" page in the front end with a custom sidebar per role (with custom nav, custom content, custom links...)
i.e : role A access to the "profile" page and has sidebar A, role B access to same page but has sidebar B...
Thanks for any help! | You could either read the role of the current user, then show the desired sidebar elements, or (what I'd prefer) check for certain capabilities.
**User Role**
global $current_user;
$roles = $current_user->roles;
$role = array_shift( $roles );
switch ( $role ) {
case ...
}
**Capabilities**
if ( current_user_can( SOME_CAP ) ) {
} elseif ( current_user_can( SOME_CAP ) ) {
} else { //maybe display nothing or an error or whatever} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sidebar, user roles, profiles"
} |
Email address or username used to login in wordpress
How can i allow users to login to my wordpress site using both email id and username? Currently it is allowing only username. | As of WordPress 4.5, logging in with the email address instead of username has been added to core functionality. It was introduced in ticket 9568.
If you are running a version of WordPress older than 4.5, the following small small plugin will work. If you don't (or can't) use a plugin, this should - in theory - as well work from within your `functions.php` file. Just leave the plugin comment header out.
<?php
/** Plugin Name: (#90328) Login with E-Mail address */
function login_with_email_address( &$username ) {
$user = get_user_by( 'email', $username );
if ( !empty( $user->user_login ) )
$username = $user->user_login;
return $username;
}
add_action( 'wp_authenticate','login_with_email_address' );
Hope this helps. | stackexchange-wordpress | {
"answer_score": 13,
"question_score": 3,
"tags": "login"
} |
Costum walker with sub menu item count
I have a menu like:
-Item1
--Sub1
--Sub2
--Sub3
--Sub4
--Sub5
--Sub6
-Item2
-Item3
and want to do some costum stuff after x subitems, so I have to determine when x is reached. I tried to define a variable in my costum class and then increment it in end_el():
class Walker_Nav_Menu_Costum extends Walker_Nav_Menu {
var $x = 0;
function end_el( &$output, $item, $depth = 0, $args = array() ) {
if ($depth == 1)
{
$x++;
}
$output .= "<!-- x:".$x."-->";
$output .= "</li>\n";
}
}
but unfortunately its always 1 for every element :-/
How would one do this correctly? | Inside the function your `$x` is local.
You might want to use a static variable:
class Walker_Nav_Menu_Costum extends Walker_Nav_Menu {
static $x = 0;
function end_el( &$output, $item, $depth = 0, $args = array() )
{
if ( 1 == $depth ) self::$x++;
$output .= "<!-- x:".self::$x."-->";
$output .= "</li>\n";
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, navigation, walker"
} |
How to add enctype to multipart/form-data to comment form?
I need a way to change the encoding type for my comment form, without hacking the core files.
I'm aware of the function to work on the post editing form: `post_edit_form_tag`.
I've tried this:
jQuery('#comment_form').attr("enctype","multipart/form-data");
But it doesn't work, the only next step I know of is to hack the source code... Any help would be very much appreciated—thanks in advance! | One Trick Pony answered the question, here's his solution:
jQuery('#comment_form')[0].encoding = 'multipart/form-data';
And here's a jsFiddle of it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "comments, comment form"
} |
Creating a Horizontal menu
i'm new to creating wordpress themes and want a menu at the Top of my page. I do have the following: Header.php
<html>
<head>
<title>Tutorial theme</title>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>">
</head>
<body>
<div id="wrapper">
<?php wp_nav_menu( array('menu' =>'Top Navi', 'container' => '', 'items_wrap' => '<ul id="menu-primary" class="menu" >%3$s</ul>' ) ); ?>
<div id="header">
</div>
functions.php
<?php
add_theme_support( 'menus' );
if (function_exists('register_nav_menus')) {
register_nav_menus(
array(
'main_nav' => 'Main Navigation Menu'
)
);
}
?>
And finally my css file <
However my menu comes out in a list, not horizontally. What am i doing wrong? | In my opinion, this is a CSS-only question.
You have to provide the `<li>` elements in your menu with the CSS style `display: inline;` (or 'inline-block'). | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -1,
"tags": "menus, css"
} |
How to make widget title accept php?
I am trying to make widgets accept php, but without resorting to plugins.
So far I have enabled php for the widget_text but cant make it work for widget_title.
I am using the following code in functions.php:
add_filter('widget_text','execute_php',100);
function execute_php($html){
if(strpos($html,"<"."?php")!==false){
ob_start();
eval("?".">".$html);
$html=ob_get_contents();
ob_end_clean();
}
return $html;
}
What would I have to do to enable php in the title as well? | You can use the filter `widget_title` and a "virtual" shortcode. Of course, as One Trick Pony points out, the "why" (and the "what") is essential to find a proper solution...
Supposing the widget title was `Title [php] More Title`:
add_filter( 'widget_title', 'pseudo_php_wpse_90360', 10, 3 );
function pseudo_php_wpse_90360( $title, $instance, $id_base )
{
if( FALSE === strpos( $title, '[php]' ) )
return $title;
$break_it = explode( '[php]', $title );
$title = $break_it[0] . 'hello world' . $break_it[1];
return $title;
}
The output is `Title hello world More Title`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, widgets, widget text"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.