INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Hacking TinyMCE for better usability (shortcodes and html)
I'm looking for some theme or plugin examples that showcase ways in which to enhance the usability of editing shortcodes and/or custom html objects that have been inserted into the editor.
I know that its possible to apply runtime styles to elements (nextpage and image rollovers are a couple examples) and I'm looking for some examples of scripts that seek to extend this to other elements (custom classed divs for example).
I've never seen an example of shortcode editing that went beyond the basic bracket+properties+content.
Ideally, I'd like to see an example where someone has abstracted shortcodes into their html equivalent, with rollover and right click events to modify element attrributes.
Just looking for any examples of work in this field. | Have a look at my Gridster Plugin, it replaces every shortcode `[gridster id="" title=""]` with a visual replacement, like you know from the [gallery]-Shortcode.
!enter image description here
To change parameters of the current shortcode, you're able to click a button and a tinyMCE modal will let you change anything within a user-friendly GUI.
!enter image description here
The functions are based on the the way, the gallery-shortcode-replacement works.
If this points into the right direction, I could get in more detail if you want. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "jquery, tinymce, hacks"
} |
How can I show/hide HTML elements if the page is_front_page
For example if its `'is_front_page'` I want to hide a div. If its not the `'is_front_page'` i want to show the div. How can i achieve this?
I am not sure on how I can achieve this. Any assistance would be great. Thanks | This is really not enough information, so I have to guess.
### A) The _div_ is part of the content
Use PHP, check for front-page, and if not, handle the div:
<?php if (! is_front_page()) : ?>
<div />
<?php endif; ?>
### B) The _div_ is located somewhere else on the page
Give the div an ID and use jQuery:
<?php if (! is_front_page()) : ?>
<script>
jQuery(function ($) {
$('#DIV-ID-HERE').remove();
});
</script>
<?php endif; ?>
**// EDIT**
Of course, method A should be preferred! I'd suggest to include the above code where the div is generated. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 1,
"tags": "homepage"
} |
hrecipe microformat tag to "featured image"
I have a website made with wordpress which includes recipes. Now I would like to add the "photo" `hrecipe` Microformat tag in order to have a thumbnail on Google searches (hrecipe photo tag)
My recipes pictures come from the featured image section. How can I now add `itemprop="photo"` to the `<img>` tag?
For example:
<img itemprop="photo" src="apple-pie.jpg" />
This is were my Thumbnail is created:
<div class="post-thumb">
<?php if( !is_singular() ) { ?>
<a title="<?php printf(__('Permanent Link to %s', 'zilla'), get_the_title()); ?>" href="<?php the_permalink(); ?>"><?php the_post_thumbnail('blog-large'); ?></a>
<?php } else {
the_post_thumbnail('blog-large');
} ?>
</div> | Use the filter `post_thumbnail_html`. The callback takes 5 parameters, the first (`$html`) is the one that's returned and that we modify, and the others can be helpful to build the modification.
add_filter( 'post_thumbnail_html', 'add_tag_to_featured_wpse_95469', 10, 5 );
function add_tag_to_featured_wpse_95469( $html, $post_id, $post_thumbnail_id, $size, $attr )
{
$modify = str_replace( '<img', '<img itemprop="photo"', $html );
return $modify;
}
Relevant Q&A: Where to put my code: plugin or functions.php? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "post thumbnails"
} |
Wordpress Flyout Menus
I have a bit of a complicated menu structure that I am trying to figure out the best way to do this.
**I have a top nav** that has 4 SECTIONS. Each Section has upto 2 levels deep.
Also, **I have a SUB Nav** that is based on what section you are in and displays as a drill down showing what page you are own.
For example, say I click on a second level TOP NAV - I would then go to that SUBPAGE showing the SUB nav having that section open and selected.
I hope I explained that correctly...
Thanks.
My Question is: What is the best way to do this. I've researched some plugins but I can't seem to find the right one. I don't have to use a plugin. | also got UberMenu from code canyon that works perfect for the top menu, I can just use the conditional widgets on the right. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus"
} |
Add a 'guide' image to custom post type admin page
I've created a custom post type and on the admin page for that post type I want an image displayed that can act as a guide for the users uploading images. Is there a function that I can use to insert an image into the admin for just that custom post type. (I have tried to Google this but all the results seem to be related to uploading images). | You could add a custom help
Simple example taken from here
function mqw_example_contextual_help( $contextual_help, $screen_id) {
# Uncomment this to see actual screen
# echo 'Screen ID = '.$screen_id.'<br />';
switch( $screen_id ) {
case 'mycustompostname' : //Your custom post name
//Just to modify text of first tab
$contextual_help .= '<p>';
$contextual_help = __( 'Your text here and the image after.' );
$contextual_help .= '</p>';
break;
}
return $contextual_help;
}
add_filter('contextual_help', 'mqw_example_contextual_help', 10, 2); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, admin"
} |
SEO smart plugin not working for words ending with ä, ö, å
Custom keywords don't get linked if words end with this letters : ä, ö, å
It works if those letters are inbetween. any idea how to fix this?
Custom Keywords :
> 1. meäts, www.google.com - works
> 2. tillhört, www.rediff.com - works
> 3. Elektrobitissä, www.git.com - does not work
> 4. tillhrtö, www.rediff.com - does not work
>
So out of the above keywords, 1 and 2 works. 3 and 4 does not work. If word ends with those special letters, word is not linked otherwise if letter appears in any position except last, it works.
< | The author is using string functions for single-byte encodings:
$url = substr($line, $lastDelimiterPos + 1 );
$keywords = substr($line, 0, $lastDelimiterPos);
But in WordPress everything is encoded in UTF-8, a multi-byte encoding. So each time you have a character in your keywords that needs more than one byte, something gets lost.
File a bug report and ask the author to read this article. He will use the mbstring functions then. Probably. :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, links"
} |
How to remove calendar widget?
I just want to remove calendar widget from the dashboard. How can I do that? | It's easy to remove a default widget from WordPress. Just add this to your functions.php file:
function remove_calendar_widget() {
unregister_widget('WP_Widget_Calendar');
}
add_action( 'widgets_init', 'remove_calendar_widget' );
See more here: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets"
} |
unused post IDs
Recently I installed plugin called Delete-Revision and noticed that every post has registered few post IDs. I usually use save drafts and update post a few times when I write a post. Here's the screenshot . As you see I have 53 posts and Wordpress already registered 646 post IDs. How can I stop it and clear unused IDs? | You can stop WP creating revisions by adding the following to your wp-config.php:
define('WP_POST_REVISIONS', false );
You can replace `false` with an integer if you just want to restrict the number a maximum number of revisions.
If you check the plugin directory you'll find several that will clean up old revisions, such as this one.
You cannot turn off drafts. You can reduce the frequency of autosaves if you wish, but WP only keeps one autosave per post anyway:
define('AUTOSAVE_INTERVAL', 160 ); // seconds | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, id"
} |
Get count of custom post type created by current user
I'm trying to get the count of published posts in a custom post type for the current user (to display on a profile page).
I found this here on the forums:
<?php
global $wp_query;
$curauth = $wp_query->get_queried_object();
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $curauth->ID . "' AND post_type = 'user_video' AND post_status = 'publish'");
?>
But, it's just giving me a big fat ZERO even though there are definitely published posts of that type. What am I doing wrong and is there a better way to do this? | I'm posting a new answer because I found this thread while searching for the same thing and the solutions here weren't optimal.
The `post_type` argument can be a **string** or an **array** of post types.
function custom_count_posts_by_author($user_id, $post_type = array('post', 'page', 'custom_post_type'))
{
$args = array(
'post_type' => $post_type,
'author' => $user_id,
'post_status' => 'publish',
'posts_per_page' => -1
);
$query = new WP_Query($args);
return $query->found_posts;
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "custom post types, wp query, count"
} |
Schedule future post to custom post status instead of publish?
I've been doing some research into custom post statuses and scheduling posts and I had a question: I was wondering if it were possible to schedule a post to got from `future` to a custom post status instead of `publish`? Main reason I'm asking is that I have a custom post type called `stream` and I've created a custom publish meta box that allows a user to select 2 post statuses: `online` and `offline`. I'm trying to make it so that if I set a future date, the stream post will transition to `online` instead of `publish` as it normally would.
My train of thought would be to hijack via filter the post status to automatically transition to `online` whenever WordPress tries to set it to `publish`. Would that be a viable option? | Here is one idea:
You could try to use the `future_to_publish` action to change the post status:
add_action('future_to_publish', 'set_status_online_wpse_95701');
function set_status_online_wpse_95701( $post ) {
if ( $post && $post->post_type==="stream"){
$post->post_status="online"; // change the post_status
wp_update_post( $post );
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "post status, scheduled posts"
} |
home_url(); showing current page instead of site address
Does anyone have an idea why my home_url() function gets the URL of the current page instead of the site address? (The site runs locally using MAMP.) | Since you didn't post actual code in your question, I can only speculate. However, a common problem is that, when calling `home_url()`, it is not _echoed_. The value of the function is _returned_ , rather than _echoed_, so it must be explicitly echoed by the code.
I'm guessing you have something like this:
<a href="<?php home_url(); ?>">Home</a>
Which renders like so:
<a href="">Home</a>
...and would explain why the linked URL is the current page, rather than the expected URL for the site front page.
If so, change it to this:
<a href="<?php echo home_url(); ?>">Home</a> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "urls, home url"
} |
Create Table Failed Column Date DateType
I have a plugin that creates tables and one of them is failing and I feel like it's due to either my syntax or the fact that I'm trying to create a column with datatype DATE and not TIMESTAMP (only one that I can make work). Can someone look at my syntax below and tell me what is wrong?
$table = $wpdb->prefix.SSM_ACADEMIC_YEAR_TABLE;
$sql = "CREATE TABLE IF NOT EXISTS " . $table . " (
id mediumint(12) NOT NULL AUTO_INCREMENT,
description VARCHAR(200) NOT NULL,
begin_date DATE NOT NULL,
end_date DATE NOT NULL
PRIMARY KEY (id));";
$wpdb->query($sql);
and now just looking at the other field in question, is it possible that it doesn't like VARCHAR(200)? Having issues here and running out of steam and time. Any help would be greatly appreciated! | Well, after looking at the other tables I **_had_** created successfully, only difference was the `description` column. Apparently WordPress or MySQL doesn't like that as a column name and somehow has it reserved. So, after renaming it, the table was created fine. Hope this helps someone else in the same boat. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wpdb, table, wp list table, customization"
} |
Get date of last update outside of loop
I'm trying to figure out how to display the date that a post was last updated outside of the loop. I'm able to display the published date using `get_the_time()` but there doesn't seem to be a "loopless" function to get the date of the last update.
Does anyone know hot to do this? | It is unclear if you are looking for the last updated post or for the last updated date for some particular post. The answer by @PatJ assumes the former. To do the latter:
$qry = new WP_Query(array('p'=>1));
var_dump($qry->posts[0]->post_modified);
Or...
$date = $wpdb->get_var("SELECT post_modified FROM {$wpdb->posts} WHERE ID = 1");
var_dump($date);
Of course you need to change the post ID to match the post you are looking for. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "loop, date, date time"
} |
How to make wp cron job not fire immediately?
I'm scheduling a job in wp cron:
add_action('my_cron_hook', 'my_cron_action');
wp_schedule_event( time(), 'interval1', 'my_cron_hook' );
function my_cron_action(){
//do something
}
The variable interval1 is set by the admin in another part of the code.
Also, there is a switch that lets the admin _enable_ or _disable_ the wp crop job.
**My problem is this:**
my_cron_action is executed as soon as it is scheduled
(this means, as soon as the admin enables the cron job from the backend).
**What i want to do is this:**
if we suppose that the time that the admin enabled the job is **T** ,
i want the job to be run at **T+interval1** for the first time, and _not at T_.
The next thing i want after this is done, is to create a button "Execute job now" that will run the job as soon as it's clicked. | As described in wp_schedule_event first parameter is `$timestamp` \- the first time that you want the event to occur. So just add interval to $timestamp. I think it should be like
wp_schedule_event( time() + $delay, 'interval1', 'my_cron_hook' );
And set `$delay` as miliseconds before hook starts. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "cron, wp cron"
} |
output specific location in the header
Is there a way in which I can output some code in the header and choose it's location? some where like wp function add_admin_menu (where you can choose the placement). | Okay, here is a working example of what you (might) want to do.
Put the following in your `functions.php`:
add_action('wp_head', 'my_jquery_code', 999999999);
function my_jquery_code() {
$jquery_code = <<<JQUERY
<script>
// jQuery code goes here...
</script>
JQUERY;
echo $jquery_code.PHP_EOL;
} // function my_jquery_code | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp head"
} |
Remove default subpages from Custom Post Menu
I am creating a Custom Post Type using `register_post_type`. After running the function a new menu item appears in the Admin Panel.
Under this item there are menu items for `new_item` and `all_items`. Is there a way to get read of the these two options considering that I created a custom page to manage these posts. | You can manipulate the global variable `$submenu` and remove them. In normal circumstances, the index key values are `5` (All items) and `10` (New item). In this example, the post type is `portfolio`:
add_action( 'admin_init', 'remove_cpt_submenus_wpse_95797' );
function remove_cpt_submenus_wpse_95797()
{
global $submenu;
unset(
$submenu['edit.php?post_type=portfolio'][5],
$submenu['edit.php?post_type=portfolio'][10]
);
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "admin"
} |
Remove class that has been added by parent theme
My parent theme generates the following class in `body`: `style-cupcake`. I don't want that. The best way to get rid of this is by adding my own functions in a `functions.php` file in my child theme, right?
I tried this (a solution I found on WPSE) but it does not seem to work. "custom background" is removed, but style-cupcake persists.
<?php
function my_body_class( $wp_classes, $extra_classes )
{
// List of the only WP generated classes that are not allowed
$blacklist = array('custom-background', 'style-cupcake');
// Blacklist result: (uncomment if you want to blacklist classes)
$wp_classes = array_diff( $wp_classes, $blacklist );
// Add the extra classes back untouched
return array_merge( $wp_classes, (array) $extra_classes );
}
add_filter( 'body_class', 'my_body_class', 10, 2 );
?>
Any idea? | If you want to apply a filter to the same content another function has filtered, change the _priority_ argument (which should have been named _execution_order_) to a higher number.
So …
add_filter( 'body_class', 'my_body_class', 11, 2 );
… will make sure `my_body_class()` will be called after `another_body_class()` that has been registered with 10:
add_filter( 'body_class', 'another_body_class', 10, 2 );
Also note the _priority_ argument will be used as an array key. It doesn’t have to be a number, just a valid key.
// this works!
add_filter( 'body_class', 'my_body_class', 'very late please', 2 );
add_filter( 'body_class', 'my_body_class', PHP_INT_MAX, 2 ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "php, functions, filters"
} |
How to solve dropdown menu problem
Please look and help me how to solve this
I want look like: Here
But my code show:
On Chrome
On mozilla
Website link Here | Is the dropdown symbol a webfont? becuase it is not getting loaded. There's a 404 error
Failed to load resource: the server responded with a status of 404 (Not Found) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "dropdown"
} |
List of all existing Wordpress plugins
Is there a place from where I can get a list of all existing Wordpress plugins located in <
I am trying to test my website for vulnerabilities and need such list. Thanks | <
Good luck. It's a very long list and Otto normally becomes very angry if someone try to scrape the complete SVN-Repo. | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 6,
"tags": "plugins"
} |
unexpected '$mm' (T_VARIABLE) in wp-includes/functions.php
I have a few Wordpress sites and all are down:
> An unexpected condition was encountered while the server was attempting to fulfill the request. Error code: 500
When I look at the apache log, there are errors (for different sites):
[Mon Apr 15 04:00:28 2013] [error] [client ...] PHP Parse error: syntax error, unexpected '$mm' (T_VARIABLE) in /var/www/SITEA/html/wp-includes/functions.php on line 192, referer: http:...
[Mon Apr 15 04:00:55 2013] [error] [client ...] PHP Parse error: syntax error, unexpected '$mm' (T_VARIABLE) in /var/www/SITEB/html/blog/wp-includes/functions.php on line 183
[Mon Apr 15 04:01:42 2013] [error] [client ...] PHP Parse error: syntax error, unexpected '$mm' (T_VARIABLE) in /var/www/SITEC/html/wp-includes/functions.php on line 203
How can I fix the error? Or is it related to the recent wordpress attack? | The correct line number for this variable in the most recent WordPress version are 207 and 209. So I guess something has mangled your files.
It is impossible to answer what exactly happened without seeing that code.
Look for new user accounts, and re-upload all WordPress files from the source. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "500 internal error"
} |
How can i show categories of custom post
I make my `custom post` and the name of that custom post is `FAQ`. so now i want to show the `categories` of that `post`. The code i am using for this is
<?php wp_list_categories('orderby=name&include=3,5'); ?>
But this not showing the post of that `custom post` type. What can i do to get the `categories` of that `custom post` type. | Instead of wp_list_categories('orderby=name&include=3,5'); use get_categories function shown in following code to get categories from custom post type.
<?php get_categories('post=faq&orderby=name&include=3,5'); ?>
For more information visit this page. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories"
} |
Implement location at wordpress post via custom taxonomies?
I would like to add a new custom hierarchical taxonomy (or 3 custom taxonomies... dependent your answer) which contain the location by: City + States&territories + Country.
for example: Orlando + Florida + United States Monroeville + Pennsylvania + United States Noyabrsk + Yamalo-Nenets Autonomous Okrug + Russia
In the final implementation the user can choose post (or posts list) by choosing Country (and or) states & territories (and or) City.
One more thing for my example: if the user choosing Russia as Country he won't get the option for Florida as States&territories...
Can I implement it as custom hierarchical taxonomy (or 3 custom taxonomies)? | Yes implement it as a heirarchical taxonomy. Have your countries as the top level terms, then states, then cities. Your URL structure will naturally reflect this. I would advise against /city/state/country, as it is illogical and counter intuitive, and doesn't make for a good heirarchy ( so bad SEO too ).
On your frontend, taxonomy-location.php should be your template. I'd strongly advise against using 3 dropdown lists, as it's poor UI/UX and a pain to implement. Instead look at ecommerce sites and implement the drilldown list pattern of picking a country, then picking a state on the next page, then a city on the next, letting users look on a country wide level or a state wide level or a city depending on how specific they want it.
The details of how to implement that however are beyond the scope of this question and answer, you will need to ask in another question | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types"
} |
User capability per post
According to Codex we can perform `current_user_can` checks for certain `post_ID`, but I fail to find any bit of info how to set a capability explicitly for that `post_ID`.
A follow up question - how to set custom capability (for ex. `download_doc`) of the same type that could be later checked by `current_user_can( "download_doc", get_the_ID() );` | As far as I know, you can not (easily) set up a custom capability for a certain post/page ID. What is described in the Codex, are the so-called _meta capabilities_ (a set of predefined capabilities with additional arguments/information).
A (not-that-easy) way is to write your own `my_add_cap`, `my_current_user_can`, `my_has_cap` etc. functions.
Regarding your follow-up question...
You could choose to not add/check the capability `download_doc` with an ID as argument, but the unique ID-based capability `download_doc_{$ID}` instead. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "capabilities"
} |
How to get category names in post_class?
I have this class for my posts:
<?php post_class( 'entry-image' ); ?>
I want to add the **category names** to get isotope work, i followed this guide < and i used this code to get category names:
$post_cats = get_the_category(); foreach( $post_cats as $category ) { echo $category->slug.' ';}
but this doesn't work. I tried to add a comma between the class and the category:
<?php post_class( 'entry-image', $post_cats = get_the_category(); foreach( $post_cats as $category ) { echo $category->slug.' ';} ); ?>
I checked the firebug but I don't see category name in loops (posts).
Why this doesn't work?
Thank you for help! | You have to pass the values, not `echo` them.
So something like this should work:
$post_cats = get_the_category();
$slugs = wp_list_pluck( $post_cats, 'slug' );
post_class( join( ' ', $slugs ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, post class"
} |
How do I remove unwanted pages like archive, search, etc.?
By default WordPress pushes out a whole array of pages I don’t want or need - archive, author, blog, monthly, recent posts, categories, comments, attachment, taxenomies, search, search results, and probably a few others I’ve missed.
Most of the time I’m building regular broshure websites with no need for anything except a few fairly static pages. How do I get rid of all the other pages? Is there a plugin that will do this? Do I have to set up a dozen redirects in the .htaccess? I’ve tried searching, but all I find is how to hide parts of a page, or customise the sitemap to hide from searches. But I don't want those pages at all, so even entering the direct URL shouldn't work. | You could redirect anything that's not a page or admin to home via the `parse_query` action:
function wpa_parse_query( $query ){
if( ! is_admin() && ! $query->is_page() ) {
wp_redirect( home_url() );
exit;
}
}
add_action( 'parse_query', 'wpa_parse_query' );
If it's not an admin screen or a query for a page, it'll redirect. You can see all of the types of pages this will remove under the Conditional Tags page in Codex. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 8,
"tags": "archives, private, customization"
} |
Is it possible to store visitors IPs in wp_postmeta table?
Or in any of the other 11 Wordpress tables. I also need to store: submission date, name, contact number in the same table.
What approach would be best? A custom table or using a standard table? | If it's information that logically belongs to a **post/page** \- you store it in `postmeta` (with `update_post_meta` function). If it's something that pertains to a **user** \- `usermeta` table is for you. More still, there's Settings API in case you have a plugin that needs to persist any settings.
From your question it is somewhat unclear which of these would be best for you. What's a " _submission date_ "? The name and contact number, I'm guessing, are for a user, and so would belong in the `usermeta`. Function `update_user_meta` is a good place to start. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "database, post meta, user meta, ip"
} |
Adding widgets to header and footer from plugin
i created 4 header and 4 footer widgets using a site spesific plugin, the reason been that when i change themes, i keep all of my widgets. i created two files, one for the header widgets and one for the footer widgets. what i need to do now is to add these to the header and footer files.
at this stage i'm putting the following code manually in my header at the bottom after my header closing tag:
<? if ( is_front_page() ) : ?>
<?php get_sidebar( 'homepage' ); ?>
<?php endif ; ?>`
and the following code in my footer at the top:
<?php get_sidebar( 'footer1' ); ?>
How can i insert these codes automatically into my header and footer files from my plugin.
many thanks | Actually including that code in your theme template files is the only surefire way to include those widgets in various themes. It's also the best to get them where you want them.
Alternatively, you could accomplish this using hooks, but that relies on your themes actually calling the hook, and in the proper location. The safest bets are the `get_header` and `get_footer` hooks, which are called just before fetching the footer.php and header.php files, respectively.
add_action( 'get_header', 'header_widgets' );
function header_widgets() {
if( is_front_page() ) {
get_sidebar( 'homepage' );
}
}
add_action( 'get_footer', 'footer_widgets' );
function footer_widgets() {
get_sidebar( 'footer1' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, widgets"
} |
Jetpack Publicize and Android
I'm using the Jetpack plugin's Publicize module to push out post links to Facebook and Twitter. This works fine through the normal website, but not when I write and publish a post through the Android app. I'm wondering if there's any way to get it to do so. | At this time, there's no way other than logging in to the backend of your site from your mobile device. This currently doesn't work on the iOS WordPress app either. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin jetpack, android"
} |
display specific custom fields
I have few custom field assigned for each post, like: "Club" with value "club1" "Date" with value "date1" and so on...
Now, I want to display from all the custom fields just those 2 " club" and "date".
This is my markup :
<div class="meta-container"><?php the_meta(); ?></div>
The problem with this, is that is retrieving all the custom fields and I don't want this. I was thinking to add css psedoselector like nth:child(n) but I'm sure that I can do this with this function. Thank you! | You should use `get_post_meta()` twice (Ref to your other question):
<?php
echo get_post_meta( get_the_ID(), 'club', true );
echo '<br />';
echo get_post_meta( get_the_ID(), 'date', true );
?> | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "custom field, post meta"
} |
Automatically add this attribute to the gallery shortcode
When inserting a gallery it adds the following shortcode:
[gallery columns="6" ids="18,150,146,23,147,17,21,20,22"]
I would like it to automatically add link="file" as the last attribute, whenever a shortcode is added. Like so:
[gallery columns="6" ids="18,150,146,23,147,17,21,20,22" link="file"] | You can hijack the shortcode handler and set the attribute to a value of your choice. Then call the native callback for this shortcode.
add_shortcode( 'gallery', 'file_gallery_shortcode' );
function file_gallery_shortcode( $atts )
{
$atts['link'] = 'file';
return gallery_shortcode( $atts );
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "shortcode, gallery, customization"
} |
unique identifier for the same pages in a multilanguage/site context
I've got always the same problem. If I program a multisite for multilanguage purposes, I cannot find a way to not change the page links in every language. I mean, suppose I've got a page named 'Activity' in the english version. Then got the Italian version, and the same page is called 'Attività'. If I've got a manually-setted link outside the menus, say:
get_page_by_title('Activity')
Then I've got to translate it in the IT theme:
get_page_by_title('Actività')
And so on for all the other languages.
So, is there a way to avoid having to check for all links in every language?
Thank you | I've found out that another answer could be to just use the is_page_template tag.
Since I'm preatty sure that the NAME of the php template file that needs custom css and/or js will be the same through all the languages (both using the multisite way or things like WPML), I can say
if(is_page_template('that-page.php')) do this..
Simple and fast. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, permalinks, multi language"
} |
Wordpress plugin for nicer looking slugs? Have multiple pages named the same but they get different slugs
This wordpress site I'm touching up has a page hierarchy which is responsible for the urls.
Basically the urls look like page1/subpage/subsubpage etc.
The problem is, this site is for a recurring competition and therefore the urls are like 2011/results 2012/results 2013/results
Which wordpress in turn makes 2011/results 2012/results-1 2013/results-2
Which doesn't look that great..
Is it possible to mod_rewrite or something to work around this? I understand the need in Wordpress for unique slugs but I really can't see why they enforce it even when it's impossible to get duplicate urls for different pages... | I use the Custom Permalinks plugin for Wordpress. With it, you can choose the permalink of each post/page individually. It is great for situations like yours where you want to fine tune the URLs in some corner cases. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, seo, slug"
} |
Query "Category A" + 1 post from "Category B" - how?
It's pretty easy to query posts from one category but what if I need also one single post from another category?
$query = new WP_Query( 'cat=4' );
I'm looking for something like this:
$query = new WP_Query( array( 'cat' => 4, 'post__in' => array( 20 ) ) );
But the above code will not return anything because there are not posts with an ID of 20 in category 4. I'm wondering if anyone has any idea how this could be done. | I don't see a way to do this with `WP_Query` alone. However...
function posts_where_add_post_wpse_96030($where) {
global $wpdb;
return $where." OR {$wpdb->posts}.ID = 1";
}
add_filter('posts_where','posts_where_add_post_wpse_96030');
$query = new WP_Query( 'cat=9' );
That will alter the query everywhere it runs so you will need to add conditions to the callback so that `$where` is only altered where you want it to be. For example...
function posts_where_add_post_wpse_96030($where) {
global $wpdb;
if (is_home()) {
$where .= " OR {$wpdb->posts}.ID = 1";
}
return $where;
}
Now the query will only be altered when it runs on a page where `is_home` is true. I don't know what conditions you need. You didn't include that in your question so you will have to work that out yourself. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp query"
} |
Exclude page by title for non admins
I have this snippet built from a couple of sources, it works great and if the user is not an admin it hides the page with an id of 243 from being seen in the edit pages section....
add_action( 'pre_get_posts' ,'exclude_pages' );
function exclude_pages( $query ) {
if( !is_admin() )
return $query;
global $pagenow;
if( 'edit.php' == $pagenow && ( get_query_var('post_type') && 'page' == get_query_var('post_type') ) )
$query->set( 'post__not_in', array(243) );
return $query;
}
I would really like to modify this so that it can work with page title instead of id, can anyone point me in the right direction? | Get the page by its title, then use its ID:
add_action('pre_get_posts', 'exclude_pages');
function exclude_pages($query) {
if(! is_admin()) return $query;
global $pagenow;
if ('edit.php' === $pagenow && (get_query_var('post_type') && 'page' === get_query_var('post_type'))) {
// Get the page by its title, ...
$page = get_page_by_title('TITLE_HERE');
// then use its ID
$query->set('post__not_in', array($page->ID));
}
return $query;
}
References: `get_page_by_title` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pre get posts"
} |
Programmatically set page_on_front
I am trying to programmatically set the 'page_on_front' option with the id value retrieved from the get_page_by_title command...
$homepage = get_page_by_title( 'Front Page' );
update_option('page_on_front', $homepage);
update_option('show_on_front', 'page');
This isn't working, can anyone help? | `get_page_by_title()` returns an object.
Use `$homepage->ID`.
You should also check if you really got a usable return value:
$homepage = get_page_by_title( 'Front Page' );
if ( $homepage )
{
update_option( 'page_on_front', $homepage->ID );
update_option( 'show_on_front', 'page' );
} | stackexchange-wordpress | {
"answer_score": 27,
"question_score": 14,
"tags": "frontpage"
} |
Is it a good practice to change media settings on theme activation?
I want to change default image sizes when user activates my theme so that the default medium image width is exactly the width of page content (for pages with sidebar) and the large image size fits nicely on full-width templates.
Is it considered a bad practice? | Best practice would be to implement your own post_thumbnails. Then, add those sizes as options in the Add Media dialog. Here is a nice write up on that. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "images, media settings"
} |
P3 Profiler and Yoast SEO plugin
I have profiled my blog with the P3 Plugin and it pointed out that Yoast SEO slows down the site a bit. I then found out that the biggest performance penalty is paid when you "force rewrite" the titles[1], which I am doing.
Now I do have quite an aggressive caching turned on with WP Super Cache. Does it still matter if I force-rewrite the titles then? Or in my case it doesn't change a thing since pages are pre-generated and served as static content?
[1] < | > Now I do have quite an aggressive caching turned on with WP Super Cache. Does it still matter if I force-rewrite the titles then? Or in my case it doesn't change a thing since pages are pre-generated and served as static content?
Yes it does matter because you are not serving cached content 100% of the time and you also have to think about the time and resources it takes to rebuild the cache.
You eliminate the need to force title rewrites by fixing your theme and replacing whatever is currently being used in the title tags with:
`<title><?php wp_title() ?></title>`
I'm leaving wp_title() blank without any arguments because the plugin is going to filter that content anyway. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin wp seo yoast, profiling"
} |
How to show a users bio on a page
I'm fairly new to Wordpress. I have users that create profiles on my site and one of the sections is their bio. How can I take this information and display it on lets say a "users profile page".
Thanks | WordPress already comes with the `author` page/functionality.
Let's say you have the author `john` on your site `www.example.com`, then you'd see his author page at `www.example.com/author/john`.
If you want to customize this, you have to tweak (or maybe even create, depending on your theme) the `author.php` or other author template files. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "php, users, actions"
} |
Remove "Published On" inside wp-admin
How do I remove this? Preferaly would like to do an action hook inside functions.php to remove this. I don't want the editor to see/edit when they published the article.
Thank you for your help.
!enter image description here | You could hide it for non-admins with _CSS_ :
function hide_curtime_wpse_96106() {
if(get_post_type() === "post"){
if(!current_user_can('manage_options')){
// only for non-admins
echo "<style>.misc-pub-section.curtime {display:none !important;} </style>";
}
}
}
**Before:**
!Before
* * *
**After:**
!After | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "functions, wp admin"
} |
Filter everything from content except output of a shortcode
Is it possible to filter the output of either the content or excerpt so that I only get the the shortcode output and so that if a user enters more than the shortcode the rest of the content for that page would be stripped. | function shortcode_only_wpse_96114($content) {
$regex = get_shortcode_regex();
preg_match_all('/'.$regex.'/',$content,$matches);
if (!empty($matches[0])) {
$content = do_shortcode(implode(' ',$matches[0]));
}
return $content;
}
add_filter('the_content','shortcode_only_wpse_96114',1);
That should check for any registered shortcodes and if present completely replace the post content with the output of the shortcode(s), removing any other content. If no shortcodes are found the post content gets returned as normal.
Barely tested. Possibly buggy. _Caveat emptor._ No refunds.
## Reference
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "filters, shortcode"
} |
SlideDeck 2, make back-end visible for admins only
I'd like to make the back-end of the SlideDeck 2 plugin visible for admin users only.
Also, I'd like to remove that "Insert SlideDeck" button from the editor.
How can I do this? | Put the following in your `functions.php`:
if (is_admin() && ! current_user_can('install_plugins')) {
add_action('admin_init', 'remove_slidedeck_menu_page');
add_action('admin_footer', 'remove_slidedeck_media_button');
}
// remove the menu page
function remove_slidedeck_menu_page() {
remove_menu_page('slidedeck2-lite.php');
}
// remove the button
function remove_slidedeck_media_button() {
echo <<<JQUERY
<script>
jQuery(document).ready(function($) {
$('#add_slidedeck').remove();
});
</script>
JQUERY;
}
**Note** : I **did** test this. If something doesn't work for you, please report back. If it does, please come back as well (and vote up/accept). ;)
**// EDIT** : the menu page is now working.
**// EDIT 2** : the button as well. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "menus, customization, admin"
} |
How to enqueue style before style.css
How do I enqueue a .css file before style.css is loaded? Or make the default style.css dependant on another .css file?
I'm trying to load a .css reset, which style.css would overwrite.
Here's what I have:
add_action('wp_enqueue_scripts', 'load_css_files');
function load_css_files() {
wp_register_style( 'normalize', get_template_directory_uri() . '/css/normalize.css');
wp_enqueue_style( 'normalize' );
}
However this is loaded after style.css. | Enqueue the `style.css` too, and set `normalize` as dependency:
if ( ! is_admin() )
{
// Register early, so no on else can reserve that handle
add_action( 'wp_loaded', function()
{
wp_register_style(
'normalize',
// parent theme
get_template_directory_uri() . '/css/normalize.css'
);
wp_register_style(
'theme_name',
// current theme, might be the child theme
get_stylesheet_uri(), [ 'normalize' ]
);
});
add_action( 'wp_enqueue_scripts', function()
{
wp_enqueue_style( 'theme_name' );
});
}
WordPress will load the dependencies now first automatically when `theme_name` is printed. | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 10,
"tags": "css, wp enqueue style, wp register style"
} |
Empty string supplied as input when parsing content
I have this code:
<?php
function mb_find_my_image( $content ) {
if( is_home() ) { /* if is home start */
$dom = new domDocument;
$dom->loadHTML($content);
$dom->preserveWhiteSpace = false;
} /* if is home end */
return $content;
}
add_filter( 'the_content', 'mb_find_my_image' );
?>
However, it seems that I always get the following error:
> Empty string supplied as input on line 6
What I'm I doing wrong here? | I have fixed the problem.
The main problem was that I was calling the function `mb_find_my_image` from `index.php`. After I've removed the calling from `index.php`, everything works as it should. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "filters, content"
} |
How can I add a filter to a particular post format?
I have several post formats and I want to use `add_filter` selectively, applying the filter to some of the post formats but not all. When I do this in my `functions.php` file it affect all the post formats. It also affects all my custom post types which I want to avoid.
function test_filter($content) {
$content = "test" . $content;
return $content;
}
add_filter('the_content','test_filter'); | Use `get_post_format()`:
function test_filter($content) {
$format = get_post_format();
if ( ! $format )
return $content;
if ( 'audio' === $format )
// do something with audio
if ( 'aside' === $format )
// do something with aside
return "$content <hr>post format: $format";
}
Since `the_content()` requires a global `$post` object to work, `get_post_format()` will always work. It will return `FALSE` if the current post type does not support post formats and a post format slug otherwise. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "custom post types, filters, hooks, post formats"
} |
How can I send edits to my blog programmaticly?
I have started a very simple wordpress blog for a hockey pool I run. The site is located at: <
I manage the actual stats counting and player movement using a local application I made in c#. I have written some logic to output the HTML needed for the body of each persons team page. (e.g. < Right now, I need to open up each of the 6 team pages, press the edit button to bring up the page's html, and then paste then new version of the body HTML in. I am looking for a way to automate this.
I have looked at the wordpress REST API, and it seems like it has the features I would need (< but I have no idea how to use this API. Am I headed in the right direction? How do I use this API in a script running on my local machine to access my blog, hosted by wordpress? | Use the XML-RPC API to post to your blog. Windows Live Writer and other apps are using that too. I am not very familiar with that API, so I have no good examples. But you should find enough with the keyword. There are also many plugins with sample code. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "api, automation"
} |
Additional image sizes are not being generated
When I upload an image through the admin interface, the image is only saved at full-size. The other sizes are configured to their default values in Settings > Media. The automatic resized versions are not being generated. I have a feeling this is due to not having a specific PHP extension installed/enabled, but I don't know what extension WordPress uses or how to install/enable it. | The solution turned out to be avoiding php-gd altogether as I couldn't get it installed. Instead, I installed the ImageMagick Engine WordPress plugin as well as ImageMagick on the server. Then I regenerated image sizes using the plugin to create the additional sizes for images I had already uploaded.
I posted the solution on my blog if you want more detail. < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "php, images, thumbnails"
} |
Force index.php have_posts() loop to exit if no sticky posts found
I'm currently using the code below to list sticky posts on my index.php.
However, when no sticky posts are present, its loading the latest posts (up to the number specified in "settings > reading > blog posts show at most ___ posts".
How can I alter the script so that if there are no sticky posts, it exits out of the while?
query_posts(array('post__in'=>get_option('sticky_posts')));
if (have_posts()) :
while (have_posts()) : the_post(); | That is because `get_option` will return an empty array if there are no sticky posts and the query will default to everything.
$sticky = get_option('sticky_posts');
if (!empty($sticky)) {
$args['post__in'] = $sticky;
$qry = new WP_Query(array('post__in' => $sticky));
if ($qry->have_posts()) :
while ($qry->have_posts()) : $qry->the_post();
echo $post->post_title;
endwhile;
endif;
}
And please don't use `query_posts`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, loop"
} |
Disable /wp-admin/plugin-install.php
How can I disable plugin upload and installation via Wordpress Admin?
Should still be able to activate/deactivate plugins in admin. | There is a constant you can define in `wp-config.php` to do this.
It will also disable the theme edit, however.
<?php
// somewhere in wp-config.php
define('DISALLOW_FILE_MODS', true);
That will remove the plugin and theme file editor (which are a terrible idea anyway) and remove the ability to install plugins and themes from the admin area. | stackexchange-wordpress | {
"answer_score": 23,
"question_score": 11,
"tags": "plugins, wp admin"
} |
Format Date for Manual Insertion into post
I have the following `$mydate = "26 January, 2012, 5:05 AM";`
I want to format this date properly so I can insert it into a post_date. Is there a simple way to do it?
$post_ information = array (
//other data is also inserted
'post_date' => $mydate;
); | That format is almost readable by `strtotime`. Remove the commas and it will convert.
$t = '27 January, 2012, 5:05 AM';
$t = str_replace(',','',$t);
$t = strtotime($t);
echo date('Y-m-d H:i:s',$t); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "date, date time"
} |
get page id's - not get pages?
I'm trying to do something like this: Hide a page in the admin end without a plugin?
However, I don't want to hardcode the page-ids. I want to get the page id's based on template-name.
$pages = get_posts(array(
'post_type' => 'page',
'meta_key' => '_wp_page_template',
'meta_value' => 'product.php'
));
^^This probably does the job, but it gets entire pages, and I start worrying about efficiency, especially when I only need id's and there could be thousands of pages being returned by this command.
I know SQL pretty well, so if I should just write my own query, then let me know.
Or maybe I don't need to worry about this at all? | Use the parameter `'fields'`:
$pages = get_posts(
array(
'post_type' => 'page',
'meta_key' => '_wp_page_template',
'meta_value' => 'product.php',
'fields' => 'ids'
)
);
_Not tested,_ but it should fetch just the IDs. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "id"
} |
Different Subdomain changes page content
I know it seems to be a strange ask here but hear me out. I have a client who has several subdomains for different countries, such as us.example.com and uk.example.com. I want to change one or two pages of a wordpress website when there is a certain subdomain entered.
Before anyone asks I have mentioned having the different options selectable in the main site but they would rather have it this way.
I could always just have another wordpress install, or put it under a multi-site but if one can do it this way that would be great.
Thanks in advance! | Just check the current host:
add_filter( 'the_content', 'domain_dependent_content' );
function domain_dependent_content( $content )
{
// get_the_ID() will return the current post ID if you need
// more information about the current page.
if ( 'page' !== get_post_type() )
return $content;
if ( 'au.example.com' === $_SERVER['HTTP_HOST'] )
return "G'Day buddy!<br>$content";
if ( 'uk.example.com' === $_SERVER['HTTP_HOST'] )
return "How do you do?<br>$content";
if ( 'us.example.com' === $_SERVER['HTTP_HOST'] )
return "Hi!<br>$content";
return $content;
}
You could also create metaboxes for the extra content, so the client can edit it. Then you check if there is extra content for this post with `get_post_meta()`, and if you found something, you change the content. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, subdomains"
} |
$wpdb->insert Database Error Duplicate Entry Error Logging
Is there an equivalent to `INSERT IGNORE` in the `wpdb` class? As I'm fetching and inserting a twitter feed and the field in which I store the tweet ID is keyed `UNIQUE`, I am aware that duplicates are going to occur and do not need Wordpress informing me of them in my PHP error log. (Note, I would write the query I need and `$wpdb->prepare` it, but for whatever reason, that throws a bunch of other errors [that I'd be happy to share though don't consider them relevant to this question]). | To answer the question directly, there is `$wpdb->update` but nothing that will strictly duplicate `INSERT IGNORE` that I know of. If `$wpdb->update`, does not work I am fairly sure that you will need to write your own query and use `$wpdb->query` and `$wpdb->prepare`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "errors, wpdb, duplicates, logging"
} |
How to remove file versions from the file source links in wp_head?
I observed the inside the `wp_head` function in the source links of every `.css`, `.js` files a `?ver=1` ( _or other number based on the file's/library version_ ) is added. How can I overwrite them, to remove them?
This issue I think is causing problems on the cache manifest part. | You can hook into `style_loader_src` and `script_loader_src` and run `remove_query_arg( 'ver', $url )` on the URL:
<?php
/* Plugin Name: Remove version parameter for scripts and styles */
add_filter( 'style_loader_src', 't5_remove_version' );
add_filter( 'script_loader_src', 't5_remove_version' );
function t5_remove_version( $url )
{
return remove_query_arg( 'ver', $url );
}
Without this plugin:
!enter image description here
After plugin activation:
!enter image description here
There is one case where that will fail: When someone didn’t use the script/style API, but added a hard coded string to the header. | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 9,
"tags": "urls"
} |
Is 'repeatable' a field type for meta boxes?
This is probably a silly question, but I'm new to wordpress development so easily confused at the moment. Code:
` array(
'label' => 'Repeatable',
'desc' => 'A description for the field.',
'id' => $prefix.'repeatable',
'type' => 'repeatable'
)
`
My Q: Is ` 'repeatable' ` a standard feature of wordpress, or is it something the developer has created? (have picked this code off the internet to learn).
Thank-you! | WordPress has no real form API, you have to create almost all form elements from scratch.
`'type' => 'repeatable'` is part of an external library.
Google lead me to this article: Reusable Custom Meta Boxes Part 3: Extra Fields – maybe a starting point for your research? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "metabox"
} |
Adding a custom post type meta field to rss
So I added my videos custom post type to my rss feed via this code.
//Add videos custom post type
function myfeed_request($qv) {
if (isset($qv['feed']) && !isset($qv['post_type']))
$qv['post_type'] = array('post', 'videos');
return $qv;
}
add_filter('request', 'myfeed_request');
Is there a way to add a custom post type meta field to the output.
Example:
Title
Post meta field (in this case a video)
Post data | Filter `the_content_feed`:
add_filter( 'the_content_feed', 'wpse_96342_add_video' );
function wpse_96342_add_video( $feed_content )
{
// fetch post meta
// add to content
return $feed_content;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, customization"
} |
How to centre menu items on horizontal nav bar? (e.g. make margins equal)
I'm currently working on building this site:
<
I would like to centre the menu items so that there isn't the large gap after "Row Club" on the right. I've tried to locate the section in style.css that deals with the menu, but I can't find it... how do I do this? | on the ".main-navigation li" (line 1487) from css, you put {padding: 0 24px; margin:0px; position: relative;}, and remove anything else.
This should do the trick.
\--- or ---
you move the top and bottom borders on the menu-nav-bar-container div, and you remove the borders and width from the ul.
This shoud do the trick too. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "menus, css, links"
} |
Include HTML template file in wp_mail
I'm using `wp_mail()` to send an HTML email. But there's quite a lot of HTML code in the email, so rather than including all the code in my `wp_mail()` function, is it possible to have the code in a separate template and just include this template in the function? Here is what I have:
<?php if ( isset( $_POST['submitted'] )) {
add_filter('wp_mail_content_type',create_function('', 'return "text/html"; '));
$emailTo = '[email protected]' ;
$subject = 'This is the subject';
$body = get_template_part( 'includes/my_email_template' );
$headers = 'From: My Name' . "\r\n";
wp_mail($emailTo, $subject, $body, $headers);
}?>
I'd like to be able to put all of my HTML code in 'my_email_template' but when I try this, no email is sent. Am I including the template incorrectly? Thanks in advance for any answers. | Per my comment to your question, I believe the problem is that `include`ing files, whether directly or using `get_template_part` isn't likely to give you a string to pass to `$body` and that is going to cause errors in the code, or at the very least unespected behavior.
I would avoid reading files into memory and just create a function that returns your `$body` content.
function get_email_body_wpse_96357() {
$body = '<p>Hi</p>';
return $body;
}
Then use `$body = get_email_body_wpse_96357();` as needed. An advantage of this method is that you can easily pass parameters to the function if you ever decide to do so. You could also use variables in an included file but it can be messy.
If you don't want to load that function all the time, then put it in a file by itself and include that file only when you need the function. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "email, wp mail, html email"
} |
Custom wp_list_pages() function
I have following code in my `.php` file:
$my_pages = wp_list_pages("title_li=&child_of=".$my_id."&echo=0");
Then I create an `<ul>`
<ul>
<?php echo $my_pages; ?>
</ul>
Problem is, that I would like to list a **title** in `<h2>` tag, and **excerpt** of the page on the text below. It´s possible to do that using `wp_list_pages`? | No, it is not possible. you will want to use `WP_Query()`
Here is the Codex Article on that.
Example:
<?php
// Query All Pages
$my_query = new WP_Query( 'post_type=page' );
// The Loop
while ( $my_query->have_posts() ) :
$my_query->the_post();
echo '<h2>' . get_the_title() . '</h2><p>' . get_the_excerpt() . '</p>';
endwhile;
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "pages, excerpt, wp list pages"
} |
Search Post Title Only
I'm using the standard WordPress search form to search a custom post type. Here is my code:
<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
<input type="hidden" name="post_type" value="attorney" />
<input type="text" value="" name="s" />
<input type="submit" value="Search" />
</form>
I would like to limit this to ONLY search the post title. Is there a way to do that? Thank you. | I didn't test the code below, but I guess it works.
/**
* Search SQL filter for matching against post title only.
*/
function __search_by_title_only( $search, &$wp_query )
{
/*my solution */
if($_GET['post_type'] != 'attorney' )
return $search;
/*my solution*/
//please copy the rest of the code from the link below
}
add_filter( 'posts_search', '__search_by_title_only', 500, 2 );
how to limit search to post titles? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, search, title"
} |
Customize Search Results for Custom Post Type
Is there a way to use a custom PHP template for search results of a custom post type. I know that you can have specific archive and category templates for custom post types. For example, archive-custom.php. But, the same doesn't work for search.php. Any suggestions? | According to this answer of yours, you can do the following inside your `search.php`:
if (isset($_GET['post_type']))
get_template_part('search', $_GET['post_type']);
else
// no post_type given
Then you have to set up the `search-{post_type}.php` files.
If you want to handle **only some** of the existing post types differently, do this by means of a `switch`:
$type = (isset($_GET['post_type'])) ? $_GET['post_type'] : '';
switch ($type) {
case 'attorney':
case 'criminal':
case 'musician':
get_template_part('search', $type);
break;
default:
// default search stuff
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "custom post types, search"
} |
Problem with is_tax in WP_Query loop
The code below is the 2nd of 4 loops in "page-balls.php". Everything else is working correctly.
I'm trying to display a tennis ball graphic if the post being retrieved has a the term "tennis-ball" term. It's not working. Is this because the PAGE does not have the term TENNIS-BALL?
How can I make this work correctly?
<?php
$args = array (
'post_type' => 'balls',
'orderby' => 'menu_order',
'order' => 'ASC'
) ;
$myQuery = new WP_Query( $args ) ;
?>
<?php if ($myQuery->have_posts()) : while ($myQuery->have_posts()) : $myQuery->the_post(); ?>
<?php if(is_tax( 'ball-types', 'tennis-ball' )) : ?>
SHOW THE TENNIS BALL GRAPHIC
<?php else : ?>
SHOW THE PLACEHOLDER GRAPHIC
<?php endif ; ?>
<?php endif ; ?>
<?php wp_reset_postdata() ; ?> | The codex on `is_tax`:
> This Conditional Tag checks if a custom taxonomy archive page is being displayed.
That is not the condition you want to check for.
Take a look at the `has_term` function and use it like so:
if( has_term( 'tennis-ball', 'ball-types', $post->ID ) ) {
/* SHOW THE TENNIS BALL GRAPHIC */
} else {
/* SHOW THE PLACEHOLDER GRAPHIC */
}
And as an aside, remove some of the `<?php` opening and closing tags. They serve no purpose and simply make your code less legible. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp query"
} |
Woocommerce price including tax with formatting from options
Af first, I'm not a programmer. In Woocommerce I need to display both product prices, including tax and excluding tax. Code in price.php
<?php if ( $price_html = $product->get_price_html() ) : ?>
is showing default price we entered as product price (this price is excluding tax). I have a problem with displaying price including tax - I'm using this code I found at stackoverflow:
<?php echo $product->get_price_including_tax(); ?>
But the price this code is showing is without formatting and currency I set in Woocommerce settings. Can you help me with this? How to display price_including_tax with proper formatting and currency? I will use this code in some woocommerce template pages, I'd like to avoid editing functions or classes if possible. | Try:
<?php echo woocommerce_price($product->get_price_including_tax()); ?> | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 3,
"tags": "php, plugins"
} |
Admin Posts List (edit.php) by post IDs
I'm writing a plugin that creates posts in bulk. I provide a way for the user to set certain parameters of the created posts beforehand. But it would be useful to use the WordPress default "All Posts" (`edit.php`) interface to fine-tune the details after the posts are created. I had a look at the `class-wp-list-table.php` and duplicating its functionality is going to be a lot of work.
The best solution would be to just send the user to edit.php - limited only to the posts created by my plugin. I have the IDs of the posts, so I'm looking for a solution like `edit.php?id=1&id=2`, revealing a nice list table with only the posts with those IDs. | It can be achieved using `pre_get_posts`.
It is important to prefix all your variable names, `id` seems not be in the reserved terms list, but anyway this practice avoids any unforeseen bug.
/**
* Usage:
*
*/
add_filter( 'pre_get_posts', 'limit_post_list_wpse_96418' );
function limit_post_list_wpse_96418( $query )
{
// Don't run on frontend
if( !is_admin() )
return $query;
global $pagenow;
// Restrict to Edit page
if( 'edit.php' !== $pagenow )
return $query;
// Check for our filter
if( !isset( $_GET['my_pids'] ) )
return $query;
// Finally, filter
$limit_posts = explode( ',', $_GET['my_pids'] ); // Convert comma delimited to array
$query->set( 'post__in', $limit_posts );
return $query;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development, query, wp list table"
} |
Extend the wp_users table
I'd like to to extend the `wp_users` table in my WordPress' database.
Why? I want people to add more information about themselves when they sing up at my website.
I know how to extend it, but I'm afraid that when WordPress needs an update the `wp_users` table, i.e. the columns I added, will be deleted.
I there anyone here who has some experience with extending the `wp_users` table?
Will this table be updated when the WordPress version is updated? | **There are data loss risks to doing this!** If you do this you might lose any data stored this way when WP updates and "fixes" the table schema in a database upgrade.
Instead of modifying the user table, make use of User Meta. It has a dedicated table, and works the same way as post meta, but for users.
* add_user_meta
* get_user_meta
* update_user_meta
There are also user taxonomies and terms, but meta is the best way to attach additional data to a user.
There are many tutorials explaining how to add additional fields to the user profile using User meta to store them, and it's how a lot of standard data is stored already, such as the positions of boxes on the dashboard when you drag them around, how many posts to show at once in the edit screen, or which popups you've clicked dismiss on | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "database, users, user meta, columns"
} |
Only list categories that contain posts of a specific custom post type
I have three custom post types set up, `articles`, `videos` and `photos`.
I am using standard categories for these post types, and sharing the categories across all post types.
I am trying to create a nav menu for each post type, listing the categories, that should follow the following structure:
* Photos
* Cat 1
* Cat 3
* Cat 5
* Videos
* Cat 2
* Cat 3
* Cat 5
* Articles
* Cat 1
* Cat 2
* Cat 4
Categories that do not contain the custom post type should be hidden.
`get_categories()` with `hide_empty` set to `1` is obviously close, but it doesn't allow you to specify a post type. | Put the following in your `functions.php`:
function wp_list_categories_for_post_type($post_type, $args = '') {
$exclude = array();
// Check ALL categories for posts of given post type
foreach (get_categories() as $category) {
$posts = get_posts(array('post_type' => $post_type, 'category' => $category->cat_ID));
// If no posts found, ...
if (empty($posts))
// ...add category to exclude list
$exclude[] = $category->cat_ID;
}
// Set up args
if (! empty($exclude)) {
$args .= ('' === $args) ? '' : '&';
$args .= 'exclude='.implode(',', $exclude);
}
// List categories
wp_list_categories($args);
}
Now you can call `wp_list_categories_for_post_type('photos');` or `wp_list_categories_for_post_type('videos', 'order=DESC&title_li=Cats');` and the like. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "custom post types, categories"
} |
Best way to achieve multiple links in a post title
Usually I would get a post title no problem, however now I need to achieve something like this:
> The Example is written for this title
As you can see two words are links in the title, another problem is that there could be any number of links, as it will depend on a content. How can I achieve this? will I have to use additional fields in WordPress? how to show WordPress which words in the title are links? And in addition, I will need to somehow store url for the link. | The easy way of doing this is to not display the title on your page template, and have a h1 header as the first thing in your content. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, customization, post meta, title"
} |
Custom <blockquote> HTML markup
In Wordpress, I would like to add a custom styling to the `<blockquote>` elements, replacing Wordpress' default usage by using a function (or however is easiest).
When using the WYSIWYG editor, highlighting text, and then clicking the "blockquote" button, I would like the highlighted text to be wrapped with the following HTML rather than just a `<blockquote>` tag:
<div class="span3 quote well">
<i class="icon-quote-left icon-2x pull-left icon-muted"></i>
<blockquote class="lead">HIGHLIGHTED TEXT</blockquote>
</div> | Put this in your `functions.php`:
add_shortcode('my_blockquote', 'my_blockquote');
function my_blockquote($atts, $content) {
return '<div class="span3 quote well">'.PHP_EOL
.'<i class="icon-quote-left icon-2x pull-left icon-muted"></i>'.PHP_EOL
.'<blockquote class="lead">'.$content.'</blockquote>'.PHP_EOL
.'</div>';
}
Then, on a page/post, just write:
> [my_blockquote]Content goes here...[/my_blockquote]
and that's it.
* * *
**// EDIT** : To add a _quicktag_ button, put this also in `functions.php`:
function add_blockquote_quicktag() {
?>
<script type="text/javascript">
QTags.addButton( 'my_blockquote', 'B', '[my_blockquote]', '[/my_blockquote]', 'B', 'My blockquote', 1 );
</script>
<?php
}
add_action( 'admin_print_footer_scripts', 'add_blockquote_quicktag' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, customization"
} |
How to count current user's pages?
There are a lot of answers on how to count users posts by using:
<?php
if ( is_user_logged_in() ) {
global $wpdb;
$user = wp_get_current_user();
$where = get_posts_by_author_sql( 'page', true, $user->ID );
$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" ); ?>
//option 1
<h2>Hey <?php echo $current_user->display_name ?>, check your page here: {page title with link to page} </h2>
<?php } else { ?>
//option 2
<h2>Welcome <?php echo $current_user->display_name ?>, etc.. text with tags etc.</h2>
<?php } } else { ?>
//option 3
<h2>text with tags etc.</h2>
<?php } ?>
But since users can also create pages, how does one get the count of current user's pages in a similar situation as the code above? | Look what `count_user_posts()` does inside and change the post type parameter:
global $wpdb;
// 'page' is the important part here
$where = get_posts_by_author_sql('page', true, $userid);
$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
Then you change your snippet to:
global $wpdb;
$user = wp_get_current_user();
$where = get_posts_by_author_sql( 'page', true, $user->ID );
$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
if ( $count >= 1 ) {
// echo your text snippet
} else {
// echo your form
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "pages, users, count"
} |
w3c validation problem - Twitter share button pulling content
I have this twitter share button that pulls 100 characters from the content of the post and its URL for the twitter share.
<a class="popup"
href="
echo urlencode(get_permalink($post->ID));
?>&text=<?php the_content_limit(100, "");?>">
<img src=" alt="twitter">
</a>
It's working but I always get the following validation error !Error
Can someone help me? | You are sending `text` unencoded. `urlencode` that just like you do the permalink.
<a class="popup" href=" echo urlencode(get_permalink($post->ID)); ?>&text=<?php echo urlencode(the_content_limit(100, ""));?>"><img src=" alt="twitter"></a>
Although, `the_content_limit` looks like it probably `echo`s (based on your usage) instead of returning a string, which you will need. So I expect you will have to find that function and alter it or duplicate it or find some other alternative to get a string that you can encode. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "validation, twitter"
} |
Two Search pages, One search form
I have a search form that I want to place in multiple pages (it will be in different header types) I do this by using the 'get search form' function. On my Search form I have radio sections listing two custom post types 'poster' and 'house'.
I have two different search pages for each post type. I want them to be separate because I want to add the search separate search pages on my Navigation e.g. "search for a poster", "search for a house".
Is there a way how I can get the search form to redirect the user to either the "search for a house" page or the "search for a poster" depending on the radio button selected before the entry was submitted?.
Preferably I would like to keep all the necessary coding within the Searcform.php file if possible. | This is my Solution, I used Onclick attributes for the radio buttons to change the 'actions' of elements within the form.
<form id="searchme" action="<?php echo site_url(); ?>/postersearch" method="get">
<ul class=" four columns inline-list offset-by-one">
<li><label for="radio4"><input name="post_type" CHECKED type="radio" id="radio4" onclick="document.getElementById('searchme').action='<?php echo site_url(); ?>/postersearch'; document.getElementById('searchsubmit').value='Search For Posters';"/> Events</label></li>
<li><label for="radio5"><input name="post_type" type="radio" id="radio5" onclick="document.getElementById('searchme').action='<?php echo site_url(); ?>/housesearch'; document.getElementById('searchsubmit').value='Search For Houses';"/> Locations</label></li>
</ul>
<input id="searchsubmit" type="submit" value="Search For posters" style="width:100%"/>
</form> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "pages, search, navigation"
} |
How can I prevent redirects from mysite/page to mysite/wp path/page?
Apparently this is built into WP somwhere since going to mysite/wp-login.php takes me to mysite/<wp path>/wp-login.php (same for wp-admin and I presume other paths).
The problem is, I don't like this functionality. My paths are intentionally not the default in order to make them less accessible to automated brute force attacks, but these redirects prevent the from being effective.
I'm assuming I can just filter this away, but I don't know which filter(s) would need to be used. Any nudges in the right direction would be appreciated! | I have hidden that in this answer, so I duplicate it here as a separate solution:
<?php # -*- coding: utf-8 -*-
/* Plugin Name: No admin short URLs */
remove_action( 'template_redirect', 'wp_redirect_admin_locations', 1000 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp admin, wp redirect"
} |
Using MathJax in text
I have installed a Mathjax plugin on my local wordpress installation, and the plugin works fine. However, I can't get it to show Latex in-text; it creates an own line for every latex formula. I end up with pages like this (this is an extreme example to get my point across better :)):
!Mathjax
How can I make it work to show Latex in-text? I've tried multiple plugins and they all seem to have this issue, with no option to resolve this. | To create an inline formula in LaTeX we can use single dollar signs `$`:
This formula $x=y+z$ is inline.
To display math on its own line, we can use double dollar signs `$$`:
$$ a = b + c $$
Here is an example with Simple Mathjax installed:
.
For example, in a template, if you were wanting to display products specifically by ID:
<?php
echo do_shortcode('[products ids="1, 2, 3, 4, 5"]');
?>
> WooCommerce comes with several shortcodes which can be used to insert content inside posts and pages: <
>
> You can add shortcodes to a post or page easily via the shortcode shortcut button in the post editor: !Woo Commerce Shortcode Editor | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 4,
"tags": "php, templates, plugins"
} |
Call sidebar from a template
I need to call a sidebar into my header. I've switched to the new twenty twelve theme and created my own child theme. With this new theme I decided to keep things organised and together, so I put my widgets functions, stylesheet and two new sidebar templates (one for header and one for footer widgets) in one folder called `pgwidgets`.
This is the call i used in my header
<? if ( is_front_page() ) : ?>
<?php get_sidebar( 'homepage' ) ; ?>
<?php endif ; ?>
This calls the `sidebar-homepage.php` file into my header from the themes' root directory. How do I change the `get_sidebar( 'homepage' )` part to call the sidebar from the pgwidgets folderfolder (`pgwidgets/sidebar-homepage.php`) | Impossible with `get_sidebar()`.
From that function’s body:
function get_sidebar( $name = null ) {
do_action( 'get_sidebar', $name );
$templates = array();
if ( isset($name) )
$templates[] = "sidebar-{$name}.php";
$templates[] = 'sidebar.php';
So if you pass a `$name` or any other custom value to the function, they will be set between two fixed strings.
You can use `locate_template()` instead:
locate_template( 'pgwidgets/sidebar-homepage.php', TRUE ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "widgets, sidebar, theme twenty twelve"
} |
Changing Woocommerce Product Description
I've been changing the way that the Single product page looks. I've moved a few things about by hooking into Woocommerce and also editing the css.
Out of the box the single product page shows the short description (described as woocommerce_template_single_excerpt in the content-single-product.php file) next to the product image, but I want to show the full description.
The full description is shown in the product data tabs underneath the product. Looking in the tabs directory at the description.php file it seems to just set the heading. Presumably as the product is a custom post type the product description is the content of the custom post.
I've worked around it by putting the full description in the product short description section but I'd like a solution that doesn't require someone adding products to have to do this.
Can anyone suggest a way of doing this please? | Slightly different fix provided by Woocommerce so I thought I should include it here:
In templates/single-product/short-description.php where it says:
$post->post_excerpt
Replace this (2 occurrences) with;
$post->post_content
Thanks | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "plugins, woocommerce offtopic"
} |
Move WordPress from /blog folder to root but leave post at /blog
I am working on a WordPress blog for a client. Currently they have around 3,000 posts.
The WordPress is installed at `/blog/`
I need to move the WordPress install to the Root directory but still have the Blog posts show up at `/blog/` so after I move the blog, all the Post URLs will remain the same.
I have to do this regardless of how I do it this has to be the outcome. I'm hoping for an easier method though.
Any ideas? | 1. Create an empty page with the slug `blog`.
2. Go to _Settings/Reading_ and set that page as _Posts page_.
3. Go to _Settings/Permalinks_ and set the URL pattern to `/blog/%postname%/`.
That should do it. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "blog"
} |
Change the link URL in default RSS feeds
My wordpress feeds post item looks following:
<item>
<title>Taste Trail – Lima and Cusco’s Best Eats</title>
<link>
<comments>
<pubDate>Tue, 16 Apr 2013 03:24:37 +0000</pubDate>
<dc:creator>anzprod</dc:creator>
<guid isPermaLink="false">
<description>
<![CDATA[Data]]>
</description>
<wfw:commentRss>
</wfw:commentRss>
<slash:comments>0</slash:comments>
</item>
I want to change the URL of the post to something like
Please help me with how to do this!
Thanks | You could filter `'the_permalink_rss'`:
add_filter( 'the_permalink_rss', 'wpse_96602_change_feed_item_url' );
function wpse_96602_change_feed_item_url( $url )
{
$parts = parse_url( $url );
return $parts['scheme'] . '://' . $parts['host'] . '/#!view' . $parts['path'];
}
But … I strongly recommend not to do that. Hash-bangs will break your web site. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "rss, feed"
} |
Finding a post's slug
I'm using `wp_query()` to get custom posts from the database. I want to list these out as links to the entries, so I'm thinking I could use the slugs. Sadly these don't seem to be included in the `wp_query` object.
Here's my code:
$oWP = new wp_query(array(
'post_type' => 'letters_of_ref'
, 'orderby' => 'meta_value'
, 'meta_key' => 'aaaConsultant_dateofletter'
));
So, given the post ID, how do I get the post's slug?
Alternatively, am I going down the right path to construct the link?
**Update** : just found the `get_permalink()` and `the_permalink()` functions, so I'm good for the link. Still want to find the slug though. | The slug is already in the post object, it's `$post->post_name`.
And as you observed, yes, the way to get the post link is `get_permalink( $post->ID );` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, plugin development, wp query"
} |
Remove comma from last item output from loop
(or add comma to all items but the last one...)
Most of the information I have found relates to using a counter within a `foreach` loop. In this particular situation I am using Advanced Custom Fields and I am within a standard loop, not a `foreach` loop.
I need to add a comma to the end of each item except the last.
<?php while( has_sub_field('images') ): ?>
<?php $image = wp_get_attachment_image_src(get_sub_field('image'), 'wsn_canvas'); ?>
<?php echo $image[0]; ?>
//echo comma here
<?php endwhile; ?> | There is nothing 'standard' about a `while` loop and in this case it makes things harder, since you need a total count of all the items in loop in order to know if you are on the last item or not. It is not obvious how to get that total count with a function like `has_sub_field` but there is a quick way to do this that I use fairly often to build character separated strings when I don't know how many items will be in the final result.
$attach = array();
while( has_sub_field('images') ):
$image = wp_get_attachment_image_src(get_sub_field('image'), 'wsn_canvas');
$attach[] = $image[0];
endwhile;
echo implode(', ',$attach); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop, advanced custom fields"
} |
Should I remove install.php and install-helper.php?
Is keeping `wp-admin/install.php` and `wp-admin/install-helper.php` a security leak on the newer versions of wordpress? By default file permission on those files are 644.
If there is any leak, what kind of please? | No, there is no security risk. Both files do sanity checks before anything happens.
If WordPress is already installed:
* `install-helper.php` returns just a blank page.
* `install.php` says WordPress is installed and you should log in: !enter image description here
You can forbid access to both files with a simple rule in your .htaccess above the permalink rules:
RedirectMatch Permanent wp-admin/install(-helper)?\.php /
This will redirect all requests to these files to the home page. | stackexchange-wordpress | {
"answer_score": 20,
"question_score": 16,
"tags": "security, installation"
} |
Conditional menu display
I have the line of code below with the intention to display the called menu in every other page except the home page but it still shows up on the home page. Any ideas what the problem could be.
<?php if (!is_home()) {
wp_nav_menu (array('menu'=>'sideBar','menu_class' => 'navbar'));
} ?> | Is your home page blog index or static page?
`is_home()` is meant to check if we are on blog index (latest posts), while `is_front_page()` checks if home is static page set in _Settings > Reading_. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "menus, conditional tags, frontpage"
} |
creating wp query with posts with specific category
Im running a specific wp_query to show the thumbnails in a slider of a specific category.
<?php $the_query = new WP_Query ('showposts=2', 'category_name=Events'); ?>
This doesnt appear to be working, am i missing array at the beginning somewhere
<?php $the_query = new WP_Query array('showposts=2', 'category_name=Events'); ?>
the above seemed to crash it.
Any advice would be great. | Use either:
$the_query = new WP_Query('posts_per_page=2&category_name=events');
or
$the_query = new WP_Query(array(
'posts_per_page' => 2,
'category_name' => 'events', // this is the category SLUG
));
* * *
**// EDIT**
**Please note** that `category_name` actually is the category **slug** (which is for one-word names originally the same). It is not the actual name (maybe having spaces, special characters etc. in it), though. In your case, where you just want to specifiy a certain category, you can do this either by means of the ID (`cat=42`) or the slug (`category_name=events`).
If you really want/have to use the name, you have to use `get_cat_ID('Category Name')`, for instance like so:
$the_query = new WP_Query(array(
'posts_per_page' => 2,
'cat' => get_cat_ID('Events'),
)); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "wp query"
} |
wpdb query problem to access previous 3 days posts
I am trying to get all published posts titles by author id 2 most recent by post date for the last days. Here is my query:
"SELECT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_author = 2 ORDER BY post_date DESC LIMIT 3 "
This displays most recent 3 posts instead posts of last 3 days. How to get that query right? | You are asking for the last three posts ordered by post date, not for the posts from the last three days-- `ORDER BY post_date DESC LIMIT 3`. `post_date` has a time component to it. It is not just marked with a date. Even so, that `LIMIT` would restrict the query to last three in the list, not all of the posts that are more recent than three days.
What you need is something like this:
SELECT post_title
FROM $wpdb->posts
WHERE post_status = 'publish'
AND post_author = 2
AND post_date > DATE_SUB(CURDATE(), INTERVAL 3 day)
ORDER BY post_date DESC
See the following for other options and caveats: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "query, wpdb, sql"
} |
Wp-admin Custom User Management
I am working on a plugin for which I will have to develop a backend page similar to the built-in "Users" one, in the sense that it will be basically do the same things: list the existing users ( using the `WP_List_Table` class ), edit / remove, and add new ones as well. The only difference is that it will have a couple of additional fields, as well as some other custom functionality.
My question is: should I be working with the already existing WP functions for handling users: `wp_insert_user`, `wp_update_user`, `wp_remove_user` or is it recommended to make direct calls to the database? Although this may be a little more complicated, I was wondering if it's the way recommended / only way to go. | Always use the existing functions, if those functions do what you need. That way, your code has the best chance of staying functional as the Core changes. If you make direct queries to the database then you have to keep track of changes to the database and alter your code accordingly.
Using Core functions also means that hooks have the best chance of working where they are intended to work. If you make direct queries to the database you bypass those hooks, unless you make a special effort to support them. Again, you will have to monitor changes and update your code accordingly.
Also, the database is complicated making some queries are extremely complicated and easy to get wrong. Let the Core handle it when it can.
I am not against making direct queries the database but it is not something that should be done lightly. If this is a first plugin, avoid it if all possible. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, wp admin, users"
} |
Link each category to last post
I would like that each category link to the last post of each category.
* category 1 ----> link to the last post of category 1
* category 2 ----> link to the last post of category 2
* category 3 ----> link to the last post of category 3
How can I do it? | You can filter `category_link` and replace the URL here. I have used the _newest_ post in the following example, because _first_ could also mean the _oldest_ and that sounds … strange. :)
add_filter( 'category_link', 'wpse_96677_cat_link_to_first_post', 10, 2 );
function wpse_96677_cat_link_to_first_post( $url, $term_id )
{
$term = get_term( $term_id, 'category' );
// sub-terms only
if ( ! isset ( $term->parent ) or 0 == $term->parent )
return $url;
$post = get_posts(
array(
'numberposts' => 1,
'category' => $term_id
)
);
if ( ! $post )
return $url;
return get_permalink( $post[0]->ID );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories"
} |
Hooking Into Widget Output Loop
When wordpress sidebar outputs any particular `registered sidebar` it loop through all widgets that assigned through it and outputs it (i guess). Is is possible to hook into the loop and add some content, say **I want to add a ad code every three widgets**.
**What I have tried?** Unable to find any leads. Tried to search on wordpress source code but not sure what to search. searching `widget` or `widget loop` doesn't help. | Hook into `'dynamic_sidebar'` and count how often it is called.
You get the current active sidebar with `key( $GLOBALS['wp_registered_sidebars'] )`.
add_action( 'dynamic_sidebar', 'wpse_96681_hr' );
function wpse_96681_hr( $widget )
{
static $counter = 0;
// right sidebar in Twenty Ten. Adjust to your needs.
if ( 'primary-widget-area' !== key( $GLOBALS['wp_registered_sidebars'] ) )
return;
if ( 0 !== $counter && 0 === $counter % 3 )
print '<hr>';
$counter += 1;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "widgets, register sidebar"
} |
Add javascript confirmation popup on "Move to Trash" link
I want to open javascript error message when some one clicks on "Move to Trash" link in Publish box in wp-admin | Put the following in your `functions.php`:
if (! empty($GLOBALS['pagenow']) && 'post.php' === $GLOBALS['pagenow'])
add_action('admin_footer', 'trash_click_error');
function trash_click_error() {
echo <<<JQUERY
<script>
jQuery(function($) {
$('#delete-action a').unbind();
$('#delete-action a').click(function(event) {
event.preventDefault();
alert('Error!');
setTimeout(
function() {
$('#save-action .spinner').hide();
$('#publish').removeClass('button-primary-disabled');
},
1
);
});
});
</script>
JQUERY;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp admin"
} |
How to make a meta box field a requirement
I'm building a plugin that has a meta box. Some of the fields in the meta box are required. Is using jQuery the only method for achieving this? Can I require that a field is filled in using PHP? | You can use Javascript to create a first-line convenience warning, but that is not a secure solution. You will need to interrupt the post save to truly create a required field.
function req_meta_wpse_96762($data){
$allow_pending = false;
if (isset($_POST['meta'])) {
foreach ($_POST['meta'] as $v) {
if ('your_required_key' === $v['key'] && !empty($v['value'])) {
$allow_pending = true;
}
}
}
if (false === $allow_pending) {
$data['post_status'] = 'draft';
}
return $data;
}
add_action('wp_insert_post_data','req_meta_wpse_96762');
That will also reset the post to 'Draft' if the meta field is deleted. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "metabox"
} |
qTranslate in functions.php
I have a function which redirects user to certain page:
wp_redirect('
Usually I would just use:
<?php _e("<!--:en-->english permalink<!--:--><!--:de-->german permalink<!--:-->"); ?>
But this is specific situation and I can't use it this way...
Any idea how to do this?
Thanks! | Are we talking permalinks here or any URL? If any, create an `array( 'en' => 'en_url', 'de' => 'de_url' );` and get the URL by accessing the array using `qtrans_getLanguage()` index.
If you're translating internal permalink use the `qtrans_convertURL()` function. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions"
} |
Set attached to state
In the media library every attachment post has an "Attached to" column. I've developed a plugin that adds author profile and a facebook like banner image.
I now discovered that the attachment posts, that are used as profile pictures, are not marked as "attached to".
I used a wordpress console plugin to get `WP_Post` objects of a linked and of an unlinked attachment. But I couldn't find any difference between them that I could use to set it manually.
Is there any way to set the attached ststus of attachment posts? | Attachments are attached to a parent post. So when you get an attachment object, look into `$attachment->post_parent`. If that is `0`, the file is not attached.
The parent post ID refers always to another post in the `posts` table, never to an user. To attach the file to a user, you could create a hidden custom post type and one entry per user. But I don’t think it is worth the efforts. There is nothing wrong with unattached files.
To change the `post_parent` value use `wp_update_post()`.
Pseudo-code, not tested:
$att = get_post( $attachment_id );
$att->post_parent = $new_parent_id;
wp_update_post( $att ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugins, posts, attachments, post meta"
} |
Why does WordPress change a file's permissions?
If I set the permissions to the CSS file in my theme to 444 and then attempt to edit it in the Appearance Editor, WordPress is not prevented from editing the file and in fact change the permissions to 644 while it makes the edit.
Why does WordPress change a file's permissions?
How do I make the site more secure and prevent this? | Per the link provided in my comment to your question, if you wish to prevent the editing of files by WordPress, just disable the file editor.
To do that add the following to your site's `wp-config.php` file:
define('DISALLOW_FILE_EDIT',true);
Or to disable the file editor and the plugin and theme installation/update system:
define('DISALLOW_FILE_MODS',true); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "security, html editor"
} |
TinyMCE Advanced list type drop-down
I want to be able to change the list-style-type, for example:
list-style-type: circle;
list-style-type: square;
list-style-type: lower-roman;
list-style-type: lower-alpha;
...
In the plugin directory for TinyMCE Advanced There is a screenshot that shows what appears to be a drop-down menu to do just that.
!enter image description here
My installation doesn't seem to have that feature. Is there something I need to do to enable it?
!enter image description here | Go to Settings -> TinyMCE Advanced, and simply enable Advanced List Options. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "tinymce"
} |
Can I specify template to use with the_permalink?
Can I specify a template to use with the_permalink()?
Why I need this: when they click a link from a certain page, I want to show that user a different template (extra content) on the linked page. | The `the_permalink()` function links to the **single post view** for the given post-type. As per the **Template Hierarchy**, the page used to render the single post view is **`single.php`**.
So, if you want to modify the template used to render the page when clicking `the_permalink()`, create/modify `single.php`, or for a specific post-type, create/modify `single-{posttype}.php`.
If you want to reference the referring page, you may want to look at hooking into `template_redirect`, and referencing `$REFERRER`, or something. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "permalinks"
} |
implement separate templates for 1 post type
* I have a custom post type 'courses', with a course description as post_content, and number of attachments
* I also have a custom post type 'course units', linked to the courses with a custom field 'course-id'
* I created a template file for the course dashboard, showing a list of the units, and a couple of links - to the course description, and to an archive of the attachments.
My (pretty generic) question:
* I'm stuck at how to create/implement the seperate 'pages' for the description, and the attachment archive - can't get my head around it.
Some additional info:
* I'm not using 'pretty permalinks' (because of some plugin conflicts), so the URL of the course dashboard is just <
* Ideally the description should be available on something like and the attachments on \- both URLs should forward to a specific template file in my theme folder.
Any ideas / suggestions? | You may use template redirect action to check if there is parameter set for description and based on that you can show desired template.
<?php
add_action('template_redirect', 'course_template_redirect', 1);
function course_template_redirect()
{
global $wp_query;
if($wp_query->post_type=='courses' and $_REQUEST['showdesc']=='1')
{
//include your template from your theme folder. for e.g include('mytheme/coursetemplate.php');
}
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, templates"
} |
Display meta data from a custom field within plugin Category Grid View Gallery
I am using this plugin, which creates a gallery of posts, fetching a thumbnail and the titles of the posts displayed in it.
I have enabled Custom Fields, and have created (and filled in values) a field for the posts I want displayed in the gallery. I know that I have to put `<?php the_meta(); ?>` within the loop for the meta data from the fields to show, which I have done and it works.
Now what I am wondering is: Can I somehow show the meta data from the fields within the plugin? Specifically, beneath (or instead of) the post title which the plugin already fetches and displays? | You should be able to pass the name of the custom field in the shortcode:
[cgview title="fieldname"]
Not tested; I just took a look at the source code (and now my eyes hurt). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, shortcode, post meta, gallery"
} |
current-menu-item not working with custom post type
I'm a wordpress newbie and I have annoying problem. I have a few custom post types (capability_type=post). Two of them i created with "Custom Post Types" plugin and when i put its categories in navigation menu they are working well. When clicked it gets current-menu-item. The problem is with one of the other post type (Events) which is created by "Events Manager" plugin. When its categories are included in navigation menu, and clicked they don't get class current-menu-item ... there is nothing starting with current in classes. Can anyone help me pleace? Link to the site: <
Look at the big red navigation and Events li and its sub-menu. I've read This post but i can't figure it out how to make it work.
Print screen in admin area here | **Solved!**
The problem was in the plugins settings ...
To fix this problem go to:
**Events** (Left Admin Sidebar) -> **Settings** -> **Pages** -> **Event Categories**
and set " **Override with Formats?** " to **NO**
Thats it ... I hope this information to be useful for others, and save them a lot of time, which they coud use for a walk, drinking beer and whatever they want. ;)
Cheers! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom post types, navigation"
} |
Copy posts from one blog to another in multisite environment
I am creating a plugin for post.php page where user can select (one or more) blogs and copy the post content,title,author,categories everything in selected blogs. The copied post would be the child of original post and now the original post would be parent post.
I want to know that is there any WP function which can directly take care of copy posts to other multisite blogs or what would be the best function to do it. | To copy a post from one blog to another you can do something like this:
function copy_post_to_blog($post_id, $target_blog_id) {
$post = get_post($post_id, ARRAY_A); // get the original post
$post['ID'] = ''; // empty id field, to tell wordpress that this will be a new post
switch_to_blog($target_blog_id); // switch to target blog
$inserted_post_id = wp_insert_post($post); // insert the post
restore_current_blog(); // return to original blog
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "multisite, query posts, wp admin"
} |
Change the name of the wp_editor tab "html/text"
I'm using the German version of WordPress and in wp_editor the two tabs for "visual" and "html" are named "visuell" and "text".
I would like to change the "text" tab to "html". Do you know how I can achieve that?
Here is a screenshot to show you exactly which tab I am talking about.
< | Filter `gettext_with_context` and change the name here:
<?php # -*- coding: utf-8 -*-
/* Plugin Name: Rename 'Text' editor to 'HTML' */
add_filter( 'gettext_with_context', 'change_editor_name_to_html', 10, 4 );
function change_editor_name_to_html( $translated, $text, $context, $domain )
{
if ( 'default' !== $domain )
return $translated;
if ( 'Text' !== $text )
return $translated;
if ( 'Name for the Text editor tab (formerly HTML)' !== $context )
return $translated;
return 'HTML';
}
### Result
!enter image description here | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp editor, tabs"
} |
changing function wp_register
how can i change function in general-template.php without affecting this core file on this:
if ( ! is_user_logged_in() ) {
if ( get_option('users_can_register') )
$link = $before . '<a href="' . site_url('wp-login.php?action=register', 'login') . '">' . __('Register') . '</a>' . $after;
to this:
if ( ! is_user_logged_in() ) {
if ( get_option('users_can_register') )
$link = $before . '<a href="' . site_url('/profile') . '">' . __('Profile Page') . '</a>' . $after; | Use the following filter named `register`:
add_filter( 'register', 'wpse_96892_register_link' );
function wpse_96892_register_link( $link )
{
if ( is_user_logged_in() )
return $link;
return str_replace(
// search
array (
site_url('wp-login.php?action=register', 'login'),
__('Register')
),
// replacements
array (
site_url('/profile'),
__('Profile Page')
),
$link
);
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "functions, wp register script"
} |
how to import custom taxonomy (& terms)
I exported a working Wordpress (v3.5.1) blog content with multiple custom taxonomies (& terms) and whenever I try to import these terms and taxonomy into a new blog the wordpress-importer fails with the message "failed to import ".
How can I 1) export and import custom taxonomies? (or) 2) fix the current export & import functions to make it work? ... looks like the terms are not created at all, even less associated to the posts.
thanks.
feel free to try it with the following export, where the post "hello world!" is associated with terms "parent term2" and "child term 1" of my custom taxony "taxonomy test": < | I have found that you need to set up the same Custom Taxonomies in your new blog. If your old one was registered as "my_custom_taxonomy", create the same in your new blog. Don't create any entries, then try your import again. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, import, export"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.