INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Show 1 post and after a specific date show the next one
I used the following query to have only 1 post published on the homepage from a particular category:
<?php if ( have_posts() ) : ?>
<?php query_posts('posts_per_page=1&orderby=date&order=DESC&cat=6'); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php wpe_excerpt('wpe_excerptlength_index', 'wpe_excerptmore'); ?>
<?php endwhile; endif; ?>
Each post has two custom fields containing a begin and an end date. What I need is that after the end date the next post (the one with following begin date) will be shown. But I don't know how to do it.
Any hint? | Assuming, as per the above comment, the format of the dates is `YYYY/MM/DD`:
$args = array(
'posts_per_page' => 1,
'cat' => 6,
'meta_key' => 'begin_date', // adjust to actual key
'meta_value' => date( 'Y/m/d' ),
'meta_compare' => '>=',
'order' => 'ASC',
'orderby' => 'meta_value'
);
$wpse72195_query = new WP_Query( $args );
// do something with the result | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom field, query posts, date time"
} |
Failed to invoke other hook from the init hook
Related to this question (Use wp init hook to call other hooks?) but not the same.
Sometimes, I found that the hook will failed to run when I place inside the init hook, e.g.
Not Work:
add_action('init','my_init');
function my_init() {
add_filter('locale', ...
}
Work:
add_action('init','my_init');
add_filter('locale', ...
Of course some hooks/filters will just work okay inside the init hook, but **definitely not all of them.**
So it seems to me that **it is a bad practice to chain actions/filters together?** | The `locale` hook happens long before `init`. To see when which hook, variable, constant, function, class or file is available install my plugin T5 WP Load Order.
You get a looong file with a very detailed log. Search for `Hook: locale`, then for `Hook: init`. You will see that you need `plugins_loaded` as parent action if you want to chain hooks.
Is it a good practice? It depends. If you need the second callback only when the first was running successful, then **yes**. If both callbacks should run independently of each other, then **no**.
Chaining should reflect the logic of your program. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "plugins, plugin development, filters, hooks, customization"
} |
How to use bloginfo( 'template_directory' ) in array
I want to pass `bloginfo( 'template_directory' )` in an array
I tried this but not working. How to write it correctly?
<?php
get_the_image( array( 'size' => 'full',
'default_image' => bloginfo( "template_directory" ) .'/img/dflt.png',
'image_scan' => true,
'link_to_post' => false ) );
?>
`get_the_image` is a function from Justin Tadlock plugin | `bloginfo()` is using `echo`, you need a function that returns its value: `get_bloginfo()`.
In this case you could also use just the function `get_bloginfo()` is using: `get_template_directory_uri()`. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "theme development, themes, array, bloginfo"
} |
Conditionally load CSS/JS/PHP in wp-admin if using a mobile device
I'm looking for a way to conditionally load different scripts if the user is accessing the admin area from a mobile device.
In my case I'm looking to restrict the user to just be able to make new posts, so if you log in to the admin area from a mobile device you're redirected to the post listing and the admin menu isn't even available.
Ideas? | `wp_is_mobile` should be the switch you need, but you may be talking about a lot of edits to a lot of components to do what you describe. I don't know enough about the rest of your code to guess at what kinds of things you would need. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "admin, wp admin, conditional content, mobile"
} |
Does WordPress cache get_user_meta() results?
If I call get_user_meta() to retrieve a value, does WordPress cache the value? If I call get_user_meta() to retrieve the same value, does WordPress have to query the database again or is it stored in PHP memory? | Yes, it does. That function is a wrapper for `get_metadata()`. Inside of that you can find:
$meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
if ( !$meta_cache ) {
$meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
$meta_cache = $meta_cache[$object_id];
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "php, database, mysql"
} |
Get posts from current category?
How can i display 5 posts from current category (exclude current post). Order by post time.
_**Example:_**
* To day news to reading 3 (12/11/2012 - 8:10 PM)
* To day news to reading 2 (12/11/2012 - 6:07 AM)
* To day news to reading 1 (12/11/2012 - 6:05 AM)
* Yesterday news to reading 2 (11/11/2012 - 9:10 PM)
* Yesterday news to reading 1 (11/11/2012 - 7:12 AM) | function filter_where_older( $where = '' ) {
$date = get_the_time('Y-m-d H:i:s');
$where .= " AND post_date < '$date'";
return $where;
}
function filter_where_newer( $where = '' ) {
$date = get_the_time('Y-m-d H:i:s');
$where .= " AND post_date > '$date'";
return $where;
}
$category = get_the_category();
if(!empty($category)) {
$cat_id = $category[0]->term_id;
add_filter( 'posts_where', 'filter_where_older' );
// retrieve older posts from current post
$query = new WP_Query( "cat=$cat_id&order=ASC&posts_per_page=5" );
remove_filter( 'posts_where', 'filter_where_older' );
add_filter( 'posts_where', 'filter_where_newer' );
// retrieve newer posts from current post
$query = new WP_Query( "cat=$cat_id&posts_per_page=5" );
remove_filter( 'posts_where', 'filter_where_newer' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, query posts, get posts"
} |
Why execute the_post()?
When I'm getting custom post types with WP_Query->query(), it isn't really necessary to execute the the_post() function, because you can iterate over the query result array. Is it considered good behaviour to do this, or is it truly just a convience method? | It is necessary to execute that function if you want to use the template functions such as `the_title()` & `the_permalink()`. You should not use it if you aren't using those kind of functions but for the themes it's generally recommended to use these functions since they automatically ensure that all wordpress filters are being applied. This functions modifies the global variables but still it's safe to use as long as you also reset the postdata after finishing the query.
Iterating the array results is useful if you're only interested in raw data. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "wp query, loop"
} |
Using wp_enqueue_script with social media buttons?
I want to embed a social sharing button in the theme. Following is the standard code to embed the twitter button.
<a href=" class="twitter-share-button">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
However, WordPress recommends to use the `wp_enqueue_script` to include any kind of javascript code. So I am wondering how can I include the above script code properly in a WordPress theme? Thanks. | Put everything between `<script>` & `</script>` in a separate file. Then use `wp_enqueue_script` with the correct path of the file & dependencies to false. After that you can use only `<a href=" class="twitter-share-button">Tweet</a>` to add the tweet button. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, themes, javascript, social sharing"
} |
Separate Media Library for each user
I'm creating a theme for a client and one of their requests is to allow users to upload images for their own use, but there may be an option to share the images.
Here are some of the caveats:
* Each user has the ability to upload their own images to their own Media Library.
* These images must be capable of being 'tagged' exactly similar to how we 'tag' 'posts' now.
* The Admin can manage these images also.
Firstly is this possible and is it possible to create a 'tag' taxonomy for images?
Thanks for your help. | ## Built in features
The Media Library has major updates with the upcoming version. You can see the changes in the slides by Daryl Koopersmith here. You can read the announcement and discussion on "Make".
> Your request for "tags/categories" is already built into 3.5.
### Note
The difference between themes and plugins is pretty easy: Display vs. Functionality. So I'd suggest to not build such functionality into a theme, but keep it separated as plugin. Your benefit from doing this: You/Your client wouldn't loose this functionality on update or theme change. It simply makes your life a lot easier. Imagine, that you got another client requesting this. Then you'd simply upload your already existing plugin instead of ripping this out of your theme and moving it into the next theme. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 6,
"tags": "images, taxonomy, tags, media library"
} |
WP e-commerce: getting products by SKU
I'm working on a site that uses the WP e-commerce plugin (Gold version) and I need to display a list of products that match a list of SKUs. Users fill in a form, and a list of product SKUs is generated depending on their answers. I need to create a page that fetches these products and displays them, preferably in the default grid view/list view style.
Any ideas how to do this? Looking through the documentation, I was expecting a "get_products()" function that could take the SKU as an argument, but there doesn't seem to be anything like that. How could I go about doing this?
Thanks a lot,
Will | WP E-commerce uses WordPress post objects to store products, so you don't need any special functions or callbacks. `query_posts` will support everything you need, you can learn about the details of how everything is set up by reading about their database schema.
Specifically, the SKU is in the `wp_postmeta` table with a `meta_key` of `_wpsc_sku`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "e commerce, plugin wp e commerce"
} |
list or get meta_key where meta_value is 'something'
I'm trying to get with
get_user_meta
the meta_key where the meta_value is `'ive-read-this'`
But I do not get the value. What should I do? | I agree with @Simon Blackbourn, but for arguments sake, here's one technique:
$data = get_user_meta( $user_id );
$data = wp_list_filter( $data, array( 'ive-read-this' ) );
$keys = array_keys( $data ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "query, meta query, user meta"
} |
Wordpress apply_filters() Arguments Missing
I'm customizing a Woocommerce Wordpress site.
In the Woocommerce product class (`class-wc-product.php`) the `get_price` function applies a filter as follows:
function get_price() {
return apply_filters('woocommerce_get_price', $this->price, $this);
}
In my functions.php I want to add a filter as follows:
add_filter('woocommerce_get_price', 'custom_price');
function custom_price($price, $product) {
...
}
When I call this I get the following PHP warning:
Warning: Missing argument 2 for custom_price()
Why is the second argument missing? Is `$this` not sent to the filter call? | It's missing the second argument because you didn't tell WordPress you wanted it with your `add_filter` call. By default, actions and filters only get one argument. Try this:
<?php
add_filter('woocommerce_get_price', 'custom_price', 10, 2);
function custom_price($price, $product) {
...
} | stackexchange-wordpress | {
"answer_score": 14,
"question_score": 3,
"tags": "plugins, filters"
} |
How to add multiple chat rooms in a WordPress website
I am building a sports chat website and I cannot find a good method to add multiple chat rooms.
What I mean, for example - I want to create a chat room for each NFL team, but each chat room should be on its own page. | Finally found a plugin that seems to work - Chat Room - < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -3,
"tags": "plugin recommendation"
} |
Allow all attributes in $allowedposttags tags
I would like to use `$allowedposttags` to allow extra HTML tags during entry submission. Can I allow all attributes for a specific tag using `$allowedposttags`?
For example, the code below will allow iframe tags and the src, height, and width attributes in the iframe tags:
$allowedposttags['iframe'] = array(
'src' => array(),
'height' => array(),
'width' => array()
);
How can I allow all attributes in this example, not just src, height, and width? | I'm pretty sure you have to explicitly name all allowed attributes - just use:
$allowedposttags['iframe'] = array (
'align' => true,
'frameborder' => true,
'height' => true,
'width' => true,
'sandbox' => true,
'seamless' => true,
'scrolling' => true,
'srcdoc' => true,
'src' => true,
'class' => true,
'id' => true,
'style' => true,
'border' => true,
);
If you can think of others let me know! | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "escaping, iframe, allowedtags"
} |
Redirect from the dashboard to edit.php if wp_is_mobile() is true
Looking for a way to redirect the user from the dashboard straight to `edit.php` if `wp_is_mobile()` is true.
This is what I've tried:
function redirect_if_mobile() {
$screen = get_current_screen();
if($screen->base == 'dashboard') {
if ( wp_is_mobile() ) {
$url = admin_url( 'edit.php' );
wp_redirect( $url );
}
}
}
add_action( 'admin_menu', 'redirect_if_mobile');
The problem is that `get_current_screen()` isn't defined in either `admin_init` or `admin_menu` (if you hook onto `admin_head` instead it's too late and headers have already been sent).
Ideas? | The action you're looking for is auth_redirect, which is before the headers but still recognizes $pagenow to tell which page you're on:
add_action('auth_redirect', 'the_mobile_boot');
function the_mobile_boot() {
global $pagenow;
if ( $pagenow == 'index.php' && wp_is_mobile() ) {
header( 'Location: ' . get_admin_url(null, 'edit.php') );
exit;
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "admin, wp admin, redirect, wp redirect"
} |
Offset Loop by 1 , Limit next loop to 1 (Most Recent) Post
I have a loop that I would like to Offset by 1 so the most recent post is not displayed, and another loop where I only want 1 item which would be the most recent post.
These are the loops I tried: for both:
Offset Loop: `<?php query_posts('offset=1'); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>`
and Most Recent Post Loop: `<?php query_posts('posts_per_page=1'); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>`
The page doesnt load for me when I tried this, any ideas? | Neither of those are complete loops. That is, in both you have the start of an `if` but not the end of it, and the start of a `while` loop, but no the end of it. Also, you shouldn't be using `query_posts` either, as it over writes the main query and is rarely the right function for pulling posts. `get_posts` would be better.
I would do this, using one as an example:
<?php $r = get_posts('offset=1');
if ( !empty($r) ) :
foreach ( $r as $post ) :
setup_postdata($post);
// stuff
endforeach;
endif; ?>
That should solve your problem with the page not loading.
What you are doing can be done with a single loop though, since get_posts without the offset will pull everything. You just need to take the first element as the recent post and loop through the rest. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop, recent posts, offsets"
} |
Blog post not showing title
When on my main site NewMediaNook.wordpress.com, one particular post does not show a title (see image below). When I am on just that one post, the title appears, and all other titles appear when on the main site...but that one does not show up.
All browsers look the same, regardless of login status.
Can I just add it in with code?? (I just don't want to risk extra code to junk it up or potentially show the title twice in some random spots).
Sorry, I'm new at WordPress, so I'm not sure what other information is needed. But all help is appreciated!
!enter image description here | This happens because you have set the post format of that entry to `link`, and for that post format TwentyEleven does not show the post title:
.format-link .entry-title {
display: none;
}
Solution: Use another post format (`standard` for example) or another theme.
!enter image description here | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, title, theme twenty eleven"
} |
How to restrict access to wp-content, wp-includes and all sub-folders
after searching I didn't find an answer still confused of how do I hide the
-> wp-content
\--> uploads
\--> themes
\--> plugins
-> wp-includes in browser. What I want is when viewer browse some like this: < they will see an error: **You don't have permission to access this page**.
Other said that just upload index.html or index.php with .htaccess in the folder you want to hide. But what if I have many subfolder inside wp-content I will do that every folder manually? Or there is a way either in _cpanel_ , or in _.htaccess_ ? Suggestion please, thanks. | Use in your .htaccess:
Options -Indexes
… to disable directory listings. See the Apache manual for details.
To restrict the access just to two URLs you might use:
RedirectMatch 204 ^/wp-content/$
RedirectMatch 204 ^/wp-content/dir/$
`204` is the _No Content_ response. Very fast. :) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "htaccess, directory, nofollow"
} |
Featured Image or Post Thumbnail Displaying on index.php?
When I'm on the main page, of my site, `site.com` it shows an excerpt of each post along with a category to the side. it also displays the same thumbnail image but above the content and I'm guessing because its grabbing the first image in the post.. I already tried removing `<?php the_post_thumbnail();?>` from the single.php and it didnt help.
How do I stop any additional images from displaying on the homepage? | WordPress will never use `single.php` to render the site front page. Refer to the Template Hierarchy for Site Front Page:
* `front-page.php`
* Static page hierarchy: `$custom-template.php`, `page-$slug.php`, `page.php`
* Blog posts index hierarchy: `home.php`
* `index.php`
Ensure that you are calling `body_class()` inside of the HTML `<body>` tag, and provide a live link to your site, and we can provide a more specific answer regarding which file to edit. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "images, loop"
} |
How to create an upload page (front side)
I would like to have a methodology for creating a functionality. When the user is connected, he will can access to a new page. In this page he will have the possibility to submit some fields like : a title, a description, an image and some tags.
I have thought several things :
* I have to create a little plugin which will display the form
* I have to create a custom post types with a the fields above
Am I right ?
Then the goal is to manage all the submissions (admin side). The admin will decide if this custom post type will be published.
What is the way for validate, insert into the bdd and display the submissions in the admin dashboard ? | I recommend the Gravity Forms plugin. You can create a form for your user to submit, and include a field for uploads.
Less work on your side and a kick-ass plugin. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "custom post types, plugin development"
} |
woocommerce product category tabs
Can someone help me how to generate dynamic tabs with product categories in woocommerce. \- product category as tab name, and their subcategories thumbnails as tab content | If you mean 'tabs' as in the way WooCommerce presents the Product Description, Attributes, and Review on the product page then take a look at the template files for WooCommerce. You can find them at ../wp-content/plugins/woocommerce/templates.
There's a good article on customizing the templates at <
You need to follow these guidelines to make sure that your changes are upgrade safe. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories, plugins, tabs"
} |
Hide submenu wordpress?
How to hide customize menu and another submenu on wordpress?
I already hide some submenu on wordpress like
function hiden() {
remove_submenu_page( 'themes.php', 'widgets.php' );//widget
remove_submenu_page( 'themes.php', 'theme-editor.php' ); //editor
remove_submenu_page( 'themes.php', 'theme_options' );} //theme-option
add_action('admin_head', 'hiden');
but if I want to remove customize menu `remove_submenu_page( 'themes.php', 'customize.php' )`... but It can't... Anybody can help me, whats wrong ??? Thank you | If you deal with wp menus you shoudl use admin_menu filter.
add_filter('admin_menu', 'admin_menu_filter',500);
function admin_menu_filter(){
remove_submenu_page( 'themes.php', 'widgets.php' );//widget
remove_submenu_page( 'themes.php', 'theme-editor.php'); //editor
remove_submenu_page( 'themes.php', 'theme_options' ); //theme-option
}
add_action('admin_print_styles-themes.php', 'hide_customize');
function hide_customize(){
echo '<style>#customize-current-theme-link{display:none;}</style>';
}
you can place it to your plugin or functions.php in your theme. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "hacks"
} |
Can't call Javascript function - scope?
I get a method not defined error when trying to call a function loaded with `wp_enqueue_script` from `site.js`.
I'm guessing it's because of scope caused by the jQuery ready wrappers? How do I get around that?
**site.js** (loaded in `head`)
jQuery(document).ready(function($) {
$(window).load(function() { // wait until everything has loaded
doSomething(); // results in face palm
});
});
**my-script.js** (loaded in footer)
jQuery(document).ready(function($) {
function doSomething() {
alert("Time for a coffee break!");
}
});
**functions.php**
wp_register_script( 'my-script', get_template_directory_uri().'/js/my-script.js', array( 'jquery' ), '', true );
wp_enqueue_script( 'my-script' );
// Pass in PHP variables
wp_localize_script( 'my-script', 'my_script', localize_post_vars() ); | You need to put your `doSomething` in the correct namespace, or at least in a namespace. The simplest way would be to put it in the `window` namespace:
jQuery(document).ready(function($) {
window.doSomething = function() {
alert("Time for a coffee break!");
};
}); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "functions, jquery"
} |
Disallow authors to edit/delete their own or other published posts
I would like to have people write on my blog and i am ok with editing their own posts while on draft. However, once their posts are published, I wouldn't like them to be able to edit/delete any published posts, not even the owned that they have written.
Is there a way to do that ? | Downgrade tham to Contributors user role. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "plugins"
} |
How to get plugin's folders permission
I have built a wordpress plugin (wp-content/plugins/MyPlugin) and I would to check some folders permission inside the MyPlugin directory.
My problem is that I don't what Wordpress constant or what PHP function I should use to target on of these directories.
if( !is_writable(WP_PLUGIN_URL.'MyFolder') )
{
echo 'NOK'.'<hr>';
}
This piece of code always returns 'NOK' whereas I am 100% sure 'MyFolder' is actually writable .
Can you give me some piece of advice here to get the right file in order to target any folder that would be in my plugin directory?
thanks | Perhaps `WP_PLUGIN_DIR`? `WP_PLUGIN_URL` is responsible for URLs. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins"
} |
How can i disable a plugin for a mobile phone?
Is there a way I can not show something to mobile users? I have a floating social bar on my responsive theme, but it get in the middle of the content if I'm on my Android phone.
I don't want to use display:none, since the JS will still load. Is there a function I can use to only show the floating bar for desktops users, and not mobile ones?
Thanks in advance (: | There is `wp_is_mobile()` function to conditionally display (or block) content for mobile users.
<?php if (!wp_is_mobile()) : ?>
<!-- Stuff to hide from mobile users -->
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "mobile, responsive, social sharing"
} |
How and where is wordpress adding mySQL content to database?
I am currently following this steps to change server and domain for my website. I have been exporting and importing mySQL from one data base to the other. I am about to delete the mySQL content of the database to replace it. I am scared that it will mess up my website.
How does Wordpress create mySQL content on the DataBase and how can I make it re-write the content. In other words: why do i need to export and import the data base from the previous website and not just allow the wordpress files on the FTP to generate the new mySQL content?
many thanks | The files on your server are the WordPress app, themes, and plugins. All page, post, widget, user, and plugin data only exists in the database.
When you create a page or post, add a user, leave a comment, etc., WordPress is writing that data to the database and nowhere else. When a visitor loads your website, the data is loaded from the database and inserted into your template for each page view.
Without the data in the database, the content for your site is irretrievably lost. This is why regular database backups are important, and care should be taken in moving the data. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database, mysql"
} |
roots child theme can't override header.php
I made a child theme for roots and it worked as expected. I can override everything, including footer.php, but not header.php. My header.php looks exactly like the one from roots at the moment, except for the blog title, which I replaced. I googled it, but it seems that I'm the only one facing this problem. | Just to clarify, are you referring to this theme? If so, it doesn't appear to use the architecture of a typical theme - you'll need to copy `roots/templates/head.php` to `child/templates/head.php` and modify accordingly. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "templates, child theme, theme roots"
} |
How to display thumbnail and excerpt of a page on homepage?
How to display attached thumbnail and excerpt (about 200 words) of a page on homepage?
<?php
$page_data = get_page( 401 ); // Get page ID 401
echo '<h3>'. $page_data->post_title .'</h3>';
echo apply_filters('the_content', $page_data->post_content);
?>
I don't know how to display attached image as thumbnail. May be i use mb_substr php function to cut the content to the excerpt.
Sorry, my english is not good. :) Thanks for help! | <?php $post_id = 50; // assign post id
$queried_post = get_page($post_id);
if(is_home()) { ?>
<div class='product_title'><h3><a href="<?php echo get_page_link($post_id); ?>"><?php echo $queried_post->post_title; ?></a></h3></div>
<div class='product_image_location'><?php echo get_the_post_thumbnail( $post_id); ?></div>
<div class='description_product'>
<?php echo $queried_post->post_content; ?></div>
<?php } ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "pages, homepage, frontpage"
} |
How to display text of a page in home or custom page?
I have "About us" content in a single static wp page and want to show a part of it in the front page with a read more... link. I want to make index.php like this:
-Navigation-
_-About Us - -Some part of About us page content_ -
-Latest News- -The loop for latest news-
How can I do the 'about us' part? Thanks | You would use `get_pages` function or create custom query using `WP_Query` class. The codex pages have detailed descriptions of parameters for both functions.
If this is a theme that you want to release for broader public you would probably want to create a theme options page where user sets the page that he wants to display. If it's you custom theme where you know the ID of 'About' page then you can skip the theme options part and use the page ID in either `get_pages` or `WP_Query` method. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "pages, homepage, customization"
} |
How to switch between the Primary Menus programmatically?
Lets say i created 2 Different Primary Menus (in the Appearance > Menu .. section). Then in the (Theme Location > Primary Navigation) Section, i can set 1 Menu to be activated.
So how can i switch between these Primary Menus at the runtime (Programmatically from the Frontend .. WITH A BUTTON CLICK or something) ? | you can do it on the clientside, if you output both menus and change the visibility on the click of the button via javascript.
if you want to do this on the serverside, you could make another template or a `if` to output the menu you want to show to the user.
the only thing you have to change here is the `$args` in calling `wp_nav_menu( $args);` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "menus"
} |
Import Images from one self-hosted WordPress install to another
I am redeveloping a client's site and, for a number of reasons, in the process changing hosts. I'm developing it on the new host and to get the site orgainised I have attempted to import all the pages from the old site using the WordPress export/import plugins.
During the import I checked the "import images" checkbox but it doesn't seem to have worked. All the images in the pages are being loaded from the old site and the media library in the new site is empty. Here are the URLs for reference:
new site: <
old site: < | Although Chip's method may work for some it did not for me. I did get it working however this way:
1. Do the normal export of pages and posts and import them to your new blog (having deleted the original pages and posts)
2. Download the wp-content/uploads folder via ftp from your old site and upload it to your new site, replacing what's there.
3. Go into phpmyadmin on the old site and use an SQL query to select all posts that have post type = "attachment" in the wp_posts table. Export the results of this query and save on your PC.
4. Export the wp_terms table from your old site.
5. Import both the mySQL exports from your old site into your new site via phpmyadmin.
6. Use the "search and replace" plugin to replace all occurrences of your old domain in your database with your new domain.
If all goes well you should have all your attachments in your new site along with all thumbnails stored and referenced correctly. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "images, media library, import, export"
} |
Natural sort / ordering wp_dropdown_categories
I'm using the following code to display an archive dropdown:
wp_dropdown_categories( 'taxonomy=week&hierarchical=1&orderby=name' );
However the format of the taxonomy is week-1, week-2 .... week-10, week-11 I need it to be natural orderered as per < e.g.
> Week 1
> Week 2
> Week ...
> Week 10
> Week 11
Currently it's being ordered true alpha e.g.
> Week 1
> Week 10
> Week 11
> Week 2
Not sure what the best way to do this is, any help or thoughts much appreciated. | not the best way (at least if you have a lot of tags)
add_filter('get_terms_orderby', 'get_terms_orderby_natural_slug',10,2);
wp_dropdown_categories( 'taxonomy=week&hierarchical=1&orderby=slug' );
remove_filter('get_terms_orderby', 'get_terms_orderby_natural_slug');
function get_terms_orderby_natural_slug($orderby, $args){
$orderby = "SUBSTR({$orderby} FROM 1 FOR 5), CAST(SUBSTR({$orderby} FROM 6) AS UNSIGNED), SUBSTR({$orderby} FROM 6)";
return $orderby;
}
but still this is a way to do that... | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, taxonomy, sort, order"
} |
Contact Form 7 not sending emails- no confirmation, no error
Live site.
I've noticed that Contact Form 7 recently stopped working, despite my not having touched any of the settings. What's odd is that I receive neither a confirmation nor an error message; I click "send" and nothing happens. This problem persists across FF, Safari, and Chrome.
I read in other, older threads that it could be something to do with SMTP settings, but as the threads were 2 years old, most of the work-around plugins they suggested are no longer an option. I also found a patch that was intended to address a problem similar to what I'm experiencing, but the patch has made no difference in my situation.
Any ideas?
Once the problem is fixed.. is there any way for me to obtain the lost email? I use the form for my business site and have undoubtedly lost leads because of this..
WP 3.4.2 CF7 3.3.1
ETA: More info here. | I just checked your site. There is **a javascript error** when you submit the form. It looks like the **issue is caused by the plugin wp-super-heatmap**.
Disable that and try it again! If that is not it, start disabling one plugin at a time. I am certain that another plugin causes this issue, and I am pretty sure it is **wp-super-heatmap**! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "forms, email, plugin contact form 7, phpmailer"
} |
WP_enqueue_script inside shortcode?
I've got shortcode that needs to include JS library only once and only there where it's used.
function shortcode_function($atts, $content = null) {
$class = shortcode_atts( array('something' => '0'), $atts );
return "<script src=\"
And here goes HTML code for the map.";
}
add_shortcode("sh", "shortcode_function");
The problem is that above example is going to include library several times if maps shortcode is used several times. How can I prevent that? Or more precisely: how can I do it "the correct way"? Can I use `wp_enqueue_script()` in that place?
Just one requirement: I really need this to include that library **only-when-shortcode-is-used**. | Yes, you should use `wp_enqueue_script()`. The script will be loaded in the footer (action: `wp_footer()`). Just once.
To inspect the order of available hooks, functions etc. per request try my plugin T5 WP Load Order. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "shortcode, javascript, wp enqueue script"
} |
Check if post has gallery images/media
Is there a Wordpress conditional that I can use to check for gallery images/media in a post?
I do not want to check if the [gallery] shortcode exist in a post.
Attached is a screenshot of what I want to check for and if is images I want to output them to the page.
!Gallery has 4 image | No Need for SQL queries in the template.
function wpse_72594_get_attachments( $id, $mime = '' )
{
$args = array(
'post_type' => 'attachment',
'post_mime_type' => $mime,
'post_parent' => $id
);
$attachments = get_posts($args);
if ($attachments)
return $attachments;
return false;
}
Then call the function like this _(300 is the post ID)_ :
* `wpse_72594_get_attachments(300)`, grabs all attachments
* `wpse_72594_get_attachments(300, 'image' )`, only images
* `wpse_72594_get_attachments(300, 'application/pdf' )`, only pdf files | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "shortcode, gallery, media, conditional tags"
} |
How to use the do_action () with parameter
I am trying to trigger an action in _functions.php_ with the `do_action()` function, but I appear to need an attribute.
The following
do_action( 'really_simple_share button="facebook_like"');
does not work...
Can you tell me the proper way to make it work (I have tried many other things that did not work either). | The correct way is to pass first argument as a unique string which acts as an identifier for the action & any additional arguments after that
do_action('unique_action_tag', $parameter1, $parameter2,,,, & so on);
To attach functions to this action you'll do
// 10 is the priority, higher means executed first
// 2 is number of arguments the function can accept
add_action('unique_action_tag', 'my_custom_function', 10, 2)
function my_custom_function($param1, $param2) {
// do something
} | stackexchange-wordpress | {
"answer_score": 19,
"question_score": 6,
"tags": "functions, actions"
} |
Blog page won't show Blog template
I set my "Blog" page to a Blog template I created in Pages (in the dashboard). Also, in Settings > Reading, I set my Home page (home template) as my Front page and my Blog page as my Posts page. However, when I navigate to my Blog page, it shows the home template. Yet, the body class of the Blog page is `blog logged-in`. I am confused. How can I make my Blog page show my Blog template?
I pasted my Blog template here for reference: < | Based on your comment:
> 1) **blog.php** What is the file name of your blog custom page template? 2) **home.php** What is the file name of your front page custom page template?
The answer is simple:
The `home.php` file name is a **reserved** file name in the WordPress template hierarchy, and is used by the template hierarchy to render the **blog posts index**.
So, WordPress is doing exactly what you've told it to do. :)
Simple solution:
1. Rename `home.php` (your **Front Page** template) as **`front-page.php`**
2. Rename `blog.php` (your **blog posts index** template) as **`home.php`**
**Note** : you'll have no need to select either template explicitly, since WordPress will use both automatically. (You need only configure **`Settings -> Reading`** properly, which you've already done.) So, you can also:
* Remove the **`Template:`** PHP header tag from both files. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "templates, page template"
} |
How to get search results in the backend admin on a custom post type?
I have a custom post type books and have many meta boxes for it...etc But in the backend, I am not able to search anything.
For example I try to search the custom post type id in the search field, it comes back with no results.
How can I add different search items into the search query? | Lol, i was just having the same problem :P Well, this plugin is working for me: Search Everything -> < or in wordpress plugin page, by name search everything | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "custom post types, admin"
} |
How to add an inline style to the <p> tag outputted in the_content() using PHP?
I am trying to add an inline style to my paragraph tags which are ouputted using `the_content();`
I've tried string replace, see question I did earlier. But it won't because the_content echo's it and does not return it. If I return the content using `get_the_content();`, it does not output in paragraph tags.
Can anyone help me with this? | Thanks to @papirtiger
Came up with this solution just to apply it to a specific content function.
I did not explain in my question that I only needed to work on a specific the_content, instead I think the above solutions are a global solutions, and both are great solutions from that point of view.
<?php
$phrase = get_the_content();
// This is where wordpress filters the content text and adds paragraphs
$phrase = apply_filters('the_content', $phrase);
$replace = '<p style="text-align: left; font-family: Georgia, Times, serif; font-size: 14px; line-height: 22px; color: #1b3d52; font-weight: normal; margin: 15px 0px; font-style: italic;">';
echo str_replace('<p>', $replace, $phrase);
?> | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "the content"
} |
How do I change the language of only the login page?
My wordpress blog is set up as `de_DE`. This means that my login page is also displayed in `de_DE`.
I would like to **only** have the login page in `en_US`.
So, **How would I programmatically change a single page's language?**
**Note** : I have WPML but I don't wish to use it, I only want to change one page on the whole site. | This will need to go in a plug-in, just put the following inside a file (`login-languge.php`) in `wp-content/plugins/`
/*
Plugin Name: Log-in Language
Plugin URI:
Description: Changes the language for log-in/register screens only
Author: Stephen Harris
Author URI:
Version: 1.0
License: GNU GPL 2
*/
add_action('plugins_loaded', 'wpse72696_login_language_init');
function wpse72696_login_language_init(){
if( in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) ) ){
add_filter('locale', 'wpse72692_login_language',10);
}
}
function wpse72692_login_language( $locale ){
return 'en_US';
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 6,
"tags": "login, multi language, language, wp login form"
} |
How to make certain content of the post noindex and no follow. not entire post?
in my woocomemrce website i am trying to embade faqs which are generated using a short cut code . these faqs are common for all products which may lead to serious duplicate content issue . how to make only the faqs content to noindex and make the remaining part of the product like description and photos under follow and index ? | Some spiders honor the `<noindex>...</noindex>` tags within a page so in that case you could simply wrap your FAQ content with `<noindex></noindex>`. But I honestly don't know if Google or for that matter which spiders honor the tag.
Since this is not really a WordPress question it's off topic for this forum. You'd more than likely have better luck with posting this to < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post meta, seo, plugins, noindex"
} |
get posts from Custom Post Type & Category
Ok, I've been frustrated about this one:
I've got a category page with the Title + Description of the title. Under it I would like to show all the (custom post type, 'blog') posts related with this category and under it related posts of custom post type 'apps'. When applying the following code it only generates all 'blog' topics with all categories (instead of only the current i'm viewing).
I have this for now:
<?php query_posts( array( 'numberposts' => 5, 'category' => 9, 'post_type' => 'blog' ) ); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
When using:
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
Does anyone know how I can only show all related posts of this category with custom post type 'blog' ? | It is 'cat', not 'category'.
query_posts( array( 'numberposts' => 5, 'cat' => 9, 'post_type' => 'blog' ) );
Also, be aware the `query_posts` alters the main page query. Unless you specifically intend to do that, and need to do it, use `get_posts` or make a new `WP_Query` object. And if you do have to use `query_posts` reset the query when you are done-- `wp_reset_query`. This is all right there in the Codex. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, categories"
} |
Custom Post Type Definition should not be in the theme - how?
Is there a way to define a custom post type independent from a theme? All sources I found in the web do that in the theme, fuctions.php or via including other theme-specific php-files. But in my eyes this makes no sense. Where is the separation between content (custom post type) and layout (theme)?
An other problem I see is changing the theme. Data is still in database, I know, but no way to edit or add new items. | > Is there a way to define a custom post type independent from a theme?
Of course, put the Custom Post Type definition in a plugin. Short answer, and kind of obvious, but I am not sure what else to add. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom post types"
} |
When switching from html to visual editor the <p> tag gets erased
I'm facing a problem, basically if I use the
tags into the html and then change to visual editor, the tags disappear, and it stays in plain text.
Scenario:
* In HTML mode, I add some p tags to a post I'm editing.
* I switch to Visual, then back to HTML, and the tag and all of its content are gone.
I'm not using any extended tinymce plugin.
Any Suggestion? | Wordpress doesn't save `<p>` tags. Paragraphs are displayed automatically in the TinyMCE visual editor and then the output gets `<p>` tags automatically (for better or for worse) from the `wpautop` function.
I avoid using `<p>` tags. A double line break will automatically be converted to a paragraph at output. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "tags"
} |
Is this a wordpress bug? get_comment_link auto shoots when user visits his dashboard
If user is **editor** , this function auto-shoots when user visits his dashboard!
How is this possible? This function should only work when user successfully posts comment, so what is happening? could be wordpress bug?
function redirect_after_comment($location)
{
//This should run only when comment is confirmed. But for user level Editor, this function auto shoots!
}
add_filter('get_comment_link','redirect_after_comment');
1. User role is EDITOR
2. user logins, goes to dashboard.
3. Anything inside this function runs. For example return... | It appears that you're intending to redirect the user to a certain page, after the user posts a comment?
If so: **why are you hooking into`get_commenet_link`** for this redirect? The `get_comment_link()` function is intended to return the permalink to a given comment. The **`get_comment_link`** filter is intended to filer the comment permalink returned by `get_comment_link()`. By hooking into `get_comment_link`, your callback is going to fire _everywhere_ that `get_comment_link()` is called. Here is the filter inside of the function:
return apply_filters( 'get_comment_link', $link . '#comment-' . $comment->comment_ID, $comment, $args );
I would recommend using a more appropriate hook related to the comment-posting process, such as **`comment_post`**. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments, bug"
} |
Find out total number of pages in global query on archive page?
I'm trying to find out whether there is more than one page of posts (I've set my posts per blog page to 5 in the reading settings) in a custom category template.
I would think the global query would have the total number of pages as a property but I can't find the call to it. | global $wp_query;
echo $wp_query->max_num_pages;
This shows the number of pages for the current query. If you want to determine the actual number of posts found by the current query, you may use `$wp_query->found_posts`
Source:- < | stackexchange-wordpress | {
"answer_score": 41,
"question_score": 25,
"tags": "wp query, pagination"
} |
Is is possible to rebuild wp_term_relationships table?
Stupidly, I truncated my posts table with out thinking about the term relationships. Now I have a bunch of 404s because there are broken term relationships. Is is possible to rebuild the table with the correct pairings? | If your `AUTO_INCREMENT` value wasn't reset and your new posts will still have unique `ID`s and you can do:
SELECT tr.*, p.ID
FROM wp_term_relationships AS tr
LEFT JOIN wp_posts AS p ON tr.object_id = p.ID
WHERE p.ID is NULL;
to see which term relationships are orphans and use a `DELETE FROM` to fix it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "tags"
} |
WordPress: force users to change password on first login
Users on my website sign up through a form (Gravity form) and after they are manually approved they are sent a username (their email address) and a randomly generated password.
I would like these users to be forced to change their password when they first login, is this achievable?
I took a look at the thread Can I force a password change? but that doesn't resolve my issue. | I've put together a quick plugin at < in response to your question and a recent client request for exactly the same thing.
It adds a user meta field on registration, then checks for the presence of this when a user is logged in. If it's not there, they are redirected to the edit profile page and an admin notice is displayed. After they change their password the user meta field is removed. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "password"
} |
Absolute path in Wordpress Network site
This site is part of a Wordpress Network.
In the theme's CSS, I'd like to reference some font files using @font-face. The fonts live in the theme's directory.
If I use a path like this:
> <
, the file is not found.
The true path is
> <
, but using this path in the CSS does not work (see this answer).
So, I have the problem of the true path not working in CSS, and the Wordpress network path not being found. | It is a googd practice to write references to files from CSS file using relative path to the theme and not one absolute. So, for instance:
background: transparent url('images/sprite_phone.png') no-repeat 0 0;
Anyway, on your case there is something wrong with the uploaded file, because none of the paths you give above work. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "paths"
} |
How do I create a Client Logos section in admin menu?
My company is hosting an event where 50 clients will be at an exhibition.
I want to create an Ehibitors section with separate admin menu. I want to be able to add Exhibits with custom fields for exhibitor_id, exhibitor_logo_img, exhibitor_title and exhibitor_bio.
What is the best way to do this? I dont want to end up with 50 exhibits in one post/page. Ideally, I want 50 separate and sortable pages within a admin menu section.
Any ideas? Hope this makes sense, WordPress noob.
Cheers, | This would probably best be solved with a custom post type for the Exhibit.
That will give you a new section in the admin-area with posts/pages for each exhibitor. That way you can for example use:
* Post thumbnail as "exhibitor_logo_img"
* The post title as "exhibitor_title"
* The content area as "exhibitor_bio"
* And if you need the "exhibitor_id" separate from the content, that could be done with a custom field named "exhibitor_id".
Have a look in the WordPress codex for info on how to setup a custom post type.
Or if you prefer a more graphical way of doing it, you can also do the same with a plugin. There are several plugins that handles the setup. Such as "Custom Post Type UI". | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, gallery"
} |
display post according to the term
I want display all my taxonomy terms on the left side of my website, so that when a user clicks on one of the terms he can see the posts according to it. How can I do this? | Create template according Template Hierarchy. Place your design + posts loop inside. To list your custom taxonomy use wp_list_categories | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, custom taxonomy"
} |
Images not working using Featured post
I have recently moved a wordpress website `abc.com` to `xyz.com`, And `xyz.com` functionality is good and working well.
And i have created a `post` with a image in it using `Featured Image`, and when i `publish` this post, its not displaying images in it. And when i check the `URL` of image using `Inspect Element`, i see the location as
` instead of ` .
And when i changed this to correct url.. then images are working good using inspect element.
And i have changed the `permalinks` and `wp-options` in database for `siteurl` to `xyz.com` , is there any thing more i need to configure or update into site or database anywhere. | I believe there are some root-links that you haven't changed.
Please follow these steps
1. Login to admin section www.xyz.com/wp-admin
2. Navigate to **settings->general->** and change the **'Site Address (URL)'** and **'WordPress Address (URL)'**.
Also please check the permalinks and settings->media there is an upload directory and the default wordpress location is **wp-content/uploads** , check if it is different for you. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "images, post thumbnails, site url"
} |
How to Create a Custom Slug for Tags and Categories with a prefix or suffix?
I wanted to rename the slug to use a custom rewrite with a prefix or suffix that I choose. For example, if the tag name is "product" I want to use a rewrite with a slug that says "product-powerpint-ppt" so the final URL will look like /tag/product-powerpoint-ppt instead of /tag/product
I was looking for a solution to this problem from time ago, without relying on htaccess rules, just tweaking WordPress or using a plugin. Anyone had the same question or can advice on a possible solution? | Filter `'term_link'`. Sample code, not tested:
add_filter( 'term_link', 'wpse_72848_change_tag_slug', 10, 3 );
function wpse_72848_change_tag_slug( $termlink, $term, $taxonomy )
{
if ( 'post_tag' !== $taxonomy )
return $termlink;
if ( 'product' === $term->slug )
return str_replace( '/product/', '/product-powerpoint-ppt/', $termlink );
return $termlink;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, url rewriting, rewrite rules"
} |
Adding Gallery to Footer of Homepage
I wanted to add gallery with Thickbox effect(Pop up), i achieved this easily on the posts page by using WordPress gallery and the lightbox plugin.But the theme is custom made there is a footer.php.I don't know how to add this gallery to the footer pro grammatically please help
EDIT:Code on Posts Page
<a href=" | Since the gallery is rendered via a `[gallery]` shortcode, you can try using **`do_shortcode()`** in `footer.php`. For example, assuming you want to output a gallery with an ID of 1:
<?php echo do_shortcode( '[gallery id="1"]' ); ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, gallery, footer"
} |
Stop wordpress from adding html tags but not remove my own tags?
I've been trying to make wordpress stop adding html tags to my content but leave my own html tags alone?
Tried `remove_filter( 'the_content', 'wpautop' );` and installed PS Disable Auto Formatting but the problem is that it removes my own html tags aswell?
I've tried to get_the_content() and the_content() but the same problem occurs there...
The way I wan't this to work is to let me add html tags and leave these alone, not removing them. Like this:
<p>Some text here</p>
<p>some more text <span class="fat"> fat </span></p> | Try accessing the $post object inside your loop, and echo'ing the content from that. Something like:
<?php echo $post->post_content ?>
### Edit
If you need to parse shortcodes, use **`do_shortcode()`**:
<?php echo do_shortcode( $post->post_content ); ?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "tags, html, the content, formatting"
} |
Is it possible to remove WYSIWYG for a certain Custom Post Type?
I dont want to use the WYSIWYG at the top of my Custom Post Type. I want to use a custom field textarea that i can place at bottom of my list of custom fields instead.
Is this possible? | add_action('init', 'init_remove_support',100);
function init_remove_support(){
$post_type = 'your post type';
remove_post_type_support( $post_type, 'editor');
}
place it to your themes functions.php | stackexchange-wordpress | {
"answer_score": 27,
"question_score": 22,
"tags": "custom post types, wysiwyg"
} |
Add Wordpress MU Network Admin via Database
I am working on getting a copy of a WordPress MU network up and running on my local machine for development purposes (using WordPress 3.2.1 at the moment). I need access to the network administration options.
In the usermeta table, I changed my `user-level` to `10` and `capabilities` to `a:1:{s:13:"administrator";b:1;}`
In the sitemeta table, I added myself to the serialized array of users in the `site_admins` option.
While this did get me access to the generic wp-admin page, I still do not have access to any of the network admin options (such as automatic upgrade for WP, plugins, or themes, etc). | So, it turns out that those three changes were all that were needed. It also turns out that if any of the serialized arrays are modified incorrectly (which is easy to do when modifying them by hand), the system will just assume you are not a network administrator.
Correcting the serialized array for the `site_admins` option fixed the problem. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 8,
"tags": "multisite, admin, database"
} |
How do I serve fully cached full HTML on cloudfront
I am using cloud front but want it to serve not just images and CSS but full static HTML pages that are cached locally. I am using wp super cache ... I assume it is caching the full HTML for posts and pages.
But I am thinking it would be better to have as much of the site in Cloudfront.
I am currently using origin pull, but again it looks like HTML pages as just cached locally.
My site doesn't change much it is mostly interviews updated every couple of weeks. | Yes, you can serve HTML through CloudFront as long as you don't mind every user getting the same content until the cache expires. It completely depends how your caches are being stored.
I can't imagine a CDN that would not support this. They might not advertise it since many web sites are dynamic and can't be cached, but if your site is basically static, then any CDN should work.
**Source:** www.cloudreviews.com/blog | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "cache, performance, cdn"
} |
Change role's settings influence post-thumbnail
In my theme functions.php i get code:
add_action( 'admin_init', 'my_remove_menu_pages' );
function my_remove_menu_pages() {
if(!current_user_can('delete_others_posts')) {
remove_menu_page('edit.php?post_type=page');
remove_menu_page('edit-comments.php');
remove_menu_page('edit.php?post_type=slide');
}
}
but then in role Author user can't edit images for thumbnail - he gives info:
Invalid argument supplied for foreach() in /wp-admin/includes/plugin.php on line 1286
Could anyone tell me what's wrong? | I'll guess that `admin_init` is too early for `remove_menu_page`, the hook should be `admin_menu`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post thumbnails, user roles"
} |
How can I remove the image attachment ALT field?
I've been using the technique described in this post to remove the caption and description fields in the uploads modal window, thus eliminating unused clutter for users. Since the title field is already required when uploading images in WordPress, it's easiest for my users to dispense with the alt field altogether and just pull the alt text from the title field when displaying images on a website.
From what I'm seeing in the media.php file, I should be able to unset the alt field by adding this to my function: `unset($form_fields['image_alt']);`, but it's not working. Any suggestions as to what I might be doing wrong? | Considering that you will come up with a solution to the accessibility issue pointed by @toscho...
Putting a lower priority (later execution) to the filter does the job.
> **$priority** _(integer) (optional)_
> Used to specify the order in which the functions associated with a particular action are executed. Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
> Default: 10
function remove_caption( $fields ) {
unset( $fields['image_alt'] );
return $fields;
}
add_filter( 'attachment_fields_to_edit', 'remove_caption', 999, 1 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "images, filters, attachment fields to edit"
} |
how to display custom fields of post on a web page
I want to ask that how can i dispaly custom field of a post on a web page . I have used get_post_meta but it resulted in just an array .i cant figure out what is the problem | <?php $meta_values = get_post_meta($post_id, $key, $single); ?>
**$single** _(boolean) (optional)_ If set to true then the function will return a single result, as a string. If false, or not set, then the function returns an array of the custom fields. This may not be intuitive in the context of serialized arrays. If you fetch a serialized array with this method you want $single to be true to actually get an unserialized array back. If you pass in false, or leave it out, you will have an array of one, and the value at index 0 will be the serialized string. Default: **false** | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, post meta"
} |
"There doesn't seem to be a wp-config.php file." despite wp-config.php in root
I've encountered an odd problem and I'm not at all sure how to go about fixing it..
I have a site that was working fine until I changed a page title from "PRESS" to "BLOG." Now, when you visit the blog page, this error comes up:
> There doesn't seem to be a wp-config.php file. I need this before we can get started. Need more help? We got it. You can create a wp-config.php file through a web interface, but this doesn't work for all server setups. The safest way is to manually create the file.
What's especially odd about this is, both wp-config.php and wp-config-sample.php are in the site root. Any ideas what's going on and how to remedy?
Thank you. | Looks like you have 2 WordPress installations. One for the main site, other for the Blog.
`
`
If that's not on purpose, you have a `blog` folder in your site root that should be renamed/deleted as it contains a blank WordPress.
If you made a page on your main site titled Blog (and with `blog` slug), then change its slug and see what happens. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "errors, blog, wp config"
} |
"the_excerpt" in loop just keeps repeating first post?
I'm trying to edit the loop in my `archive.php` template so that when I visit a category page, it only displays the post excerpt and uses the featured image as a thumbnail.
When I add `the_excerpt()` to the loop it displays the excerpt of the first post, but then just keeps repeating it indefinitely?
Here's the loop I'm trying to edit / modify:
// Start the Loop
while (have_posts()) {
the_excerpt();
get_template_part('content', get_post_format());
}
// Display navigation to next/previous pages when applicable
if (theme_get_option('theme_bottom_posts_navigation')) {
theme_page_navigation();
} | the_post \- Iterate the post index in The Loop. Retrieves the next post, sets up the post, sets the 'in the loop' property to true.
while (have_posts()) { the_post();
after you trigger the_post your the_excerpt shold return different values. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop, excerpt"
} |
Using dashboard uploader instead of FTP
Recently, I change my host server. that causing a problem. When I want upload a new theme or plugin instead of using dashboard uploader want me to enter FTP host and username and password, What I can do to come back to the previous uploader? | If you're on a shared server, it's unlikely your host will correct this issue, but you can add the upgrade constants to your wp-config file so it will at least stop asking every time. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "uploads, ftp"
} |
How to Auto Approve Comments on a Specific Page?
I am using WordPress comments on a page as a Contact page and I am able to show those comments only to logged in admin.
Now I would like to automatically have any comments placed on my Contact page approved. So, in the front end, I can see all comments placed on that page instead of seeing only the approved comments.
I would love to have a hook in functions.php that works with twenty eleven child theme. | Considering that in `Settings > Discussion` you have this options checked:
!comments moderation and whitelist options
The first is `comment_moderation` and the second `comment_whitelist`.
Then, it is possible to selectively disable them using the filter `pre_option_(option-name)`), as follows:
add_filter( 'pre_option_comment_moderation', 'wpse_72990_auto_aprove_selective' );
add_filter( 'pre_option_comment_whitelist', 'wpse_72990_auto_aprove_selective' );
function wpse_72990_auto_aprove_selective( $option )
{
global $post;
if( $post->ID == 2 )
return 0;
return $option;
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "theme development, comments, filters"
} |
Allow access to a page for admins only
I need to know how to make a page template in WordPress that can only be accessed by admins. How could I apply it to the following template?
<?php /*
Template Name: Agency Area
*/
?>
<?php get_header(); ?>
<div id="body">
<div class="agency_area_menu">
<?php wp_nav_menu(); ?>
</div>
</div>
<?php get_footer(); ?>
I'd prefer to do it without plugins. | <?php
/*
Template Name: Agency Area
*/
get_header();
echo '<div id="body">';
global $current_user;
if( in_array( 'administrator', $current_user->roles ) ) {
echo '<div class="agency_area_menu">';
wp_nav_menu();
echo '</div>';
} else {
// echo '<p>You do not have the rights required to view this page. Sorry.</p>';
/* or with internationalization
(uncomment either, adjust text domain if applicable) */
echo '<p>' .
__(
'You do not have the rights required to view this page. Sorry.',
'theme-text-domain'
) .
'</p>';
}
echo '</div>';
get_footer();
?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "login, wp login form"
} |
Re-ordering Admin Submenu Sections
I was looking at **the method below** to reorder the **Admin Menu Sections** :
<
...and was wondering if it's possible to reorder the **submenu sections** using similar method. | Yes there is, but I cannot find a simpler way...
Here, we are changing the `Media` submenu and inverting `Add new` and `Library`.
add_filter( 'custom_menu_order', 'wpse_73006_submenu_order' );
function wpse_73006_submenu_order( $menu_ord )
{
global $submenu;
// Enable the next line to inspect the $submenu values
// echo '<pre>'.print_r($submenu,true).'</pre>';
$arr = array();
$arr[] = $submenu['upload.php'][10];
$arr[] = $submenu['upload.php'][5];
$submenu['upload.php'] = $arr;
return $menu_ord;
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "admin, admin menu"
} |
Create a live demo gallery for themes
I want to create a live demo site like < that show themes so when I click on the theme screenshot it takes me to the live theme preview.
I tried two plugins themebrowser and wordpress-theme-showcase they are showing the themes in a list and I can click the theme to view, but when I'm trying to go to any page inside the preview theme it takes me to the original theme that already installed, so also I want to be able to browse the demo theme pages and posts like if it is activated.
Thanks
Edit: From the source code of wordpress-theme-showcase plugin the Theme Preview URI: php?preview_theme=WordPress%20Default and that's ok for he home page of the new theme, but if I want to go to some page it redirects me to the home page of the installed theme. So I tried to add &p=1 (post url) to the end of the Theme Preview URI above and it works. The question now is how I can append this url to all the links in the preview page | # Solution
I used the wordpress-theme-showcaseplugin to show a list of themes in the home page, and to can easily browse the theme that is currently preview I changed the way wordpress handle the permalinks. In the wp-includes/link-template.php file in get_permalink function added this code
if(isset($_GET['preview_theme'])){
$permalink = home_url('?preview_theme='.$_GET['preview_theme'] .'&p=' . $post->ID);
}else{
$permalink = home_url('?p=' . $post->ID);
}
and in _get_page_link function added this code
if(isset($_GET['preview_theme'])){
$link = home_url("?preview_theme=".$_GET['preview_theme'] ."&page_id=$id");
}else{
$link = home_url("?page_id=$id");
}
Hope this will be useful for any one will get this problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, gallery"
} |
Insert into post button missing on custom post type
I have just purchased a theme called **HQ Photography** from themeforest which has a custom post type called `gallery`.
I can add images from my hard drive no problem - but if I click the media tab and select an image the 'Insert into post button' is missing
I found a site which suggested I needed to add a custom filter to functions.php
add_filter('get_media_item_args', 'force_send_to_post');
function force_send_to_post($vars) {
$vars['send'] = true; // 'send' as in "Send to Editor"
return($vars);
}
This brings the button back but the button then does nothing.
Does anyone one know what could be wrong?
**UPDATE:** It seams the above function does work! - **however** only for images that are 'unattached' - once an image has been 'attached' the insert into post does nothing
Can you attach images to multiple posts? | It seems like theme author disabled this fuctionality for certian post type's attachments, for a reason. Trying to get it back could very well break something else. Try contacting theme's author. (S)he will probably provide free support. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, uploads, media"
} |
Comments view limited to 20 results - any way to increase to 50 or 100?
Each day I manually delete the spam posted on my blog. The comments view allows a maximum of 20 comments in the view. When I have 200 spam entries - I need to click through 10 times to get rid of it all.
Is there a way I can view 50 or 100 comments in the wordpress admin window at a time? | Adjust the amount of visible comments in the **Screen Options** :
!enter image description here | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "comments, spam, limit"
} |
How to call a plugin function from index.php
I have created a function in my plugin `myplugin` with the name `foo`, how to call it from the frontend?
e.g. index.php? | The same way you would any other:
foo();
Active plugins are loaded before the theme files
You may want to check that your plugin is activated and the function is available so things dont go pear-shaped if you forget to activate it, like:
if(function_exists('foo')){
foo();
} else {
echo "oh dear you haven't activated/installed 'myplugin', go do that before the 'foo' feature is available";
}
Also keep in mind `foo` is a very generic function name, perhaps the "omgfoo" plugin also has a `foo` function. So prefix/namespace your function to something unique
You will eventually want to use actions and filters, as they're safer and better practice, you can continue to read up on that here | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 9,
"tags": "plugins, plugin development, permalinks"
} |
How to crop thumbnail height to auto with set width
I'm looking for a way to only set the width of a thumbnail size and let the height set auto. So if I have two images. One is 600px/420px and one is 600px/600px. I want to set only the width of the thumbnail to 200px so wordpress crops the thumbnails of the above dimensions to 200px/140px and 200px/200px. Any ideas? | In your theme's _functions.php_ file:
/* register new image size
* 200px wide and unlimited height
*/
add_image_size( 'wpse73058', 200, 9999, false );
In a template or the like:
if ( has_post_thumbnail() ) { the_post_thumbnail( 'wpse73058' ); } | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 4,
"tags": "post thumbnails, uploads, cropping"
} |
Viewing category won't show up Custom post type posts
I'm having a strange problem:
I've build a category page and want to load up all related posts of a custom post type but won't give any results. I'm using the following code:
query_posts( array( 'post_type' => 'blog', 'showposts' => 3, 'cat' => 9 ) );
When deleting the 'cat' it shows all posts of the custom post type.
Is anyone familiar with this problem? | > Blockquote
**Taxonomy** _category_ with a **term** with _id_ 9 dosen't have a posts with **post type** _blog_.
Are you sure that you using native category taxonomy for CPT blogs posts?
function query_report($sql){
var_dump($sql);
echo '<hr>';
return $sql;
}
add_filter('query', 'query_report');
query_posts($your_arguments);
remove_filter('query', 'query_report'); | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "posts, categories"
} |
How can I upgrade wordpress with manual?
When I update or upgrade my site automatically ,it corrupted. How can I update or upgrade it safely and manually? | A "Manual" install involves downloading the WordPress zip and extracting it to your site directory (via ftp or a file manager like cPanel has). make sure your `wp-content` folder is fully backed up as you will need it. then run the extract. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "updates, upgrade"
} |
Contact Form 7 - E-mail message template
In contact form 7 email settings, I put in all the necessary details like below:
!enter image description here However, when the e-mail is sent, it still has the "Wordpress" title or person who sent it in gmail:
!enter image description here !enter image description here
What am I missing? Did I set something up wrongly?
Any piece of advice or information would be highly appreciated. Thanks! | In the field "From" you can enter both a name and e-mail like this:
`YOUR-NAME <[email protected]>`
Or with info from the form it self: `[name-field-name] <[email-field-name]>` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "email, plugin contact form 7"
} |
Using shortcodes in PHP
I'm trying to use shortcode in my page, I'm starting with a simple test.
In `functions.php`:
function HelloWorldShortcode() {
return '<p>Hello World!</p>';
}
add_shortcode('helloworld', 'HelloWorldShortcode');
In `index.php`:
[helloworld]
This doesn't produce `<p>Hello World!</p>`. Instead I just get the text `[helloworld]`.
How can I get shortcodes to work in a PHP document? | Referering to the Shortcodes API you can do
echo do_shortcode('[helloworld]');
if your shortcode not in post. Or you can do
echo apply_filters('the_content', '[helloworld]');
but this will also bring other filters to work on your shorcode return html. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "shortcode"
} |
Prevent users from changing post status
The scenario is this:
An agent enters the post data (custom post), but can only do a pending for review or change the visibility of the post. He cannot change the post status manually.
I have achived the pending for review, but I cannot hide the "Status: published/pending etc. Edit". How is it possible (if possible)? | Add this code where it's should be (plugin/functions.php/mu-plugin) - simple "hide" method using css.
add_action('admin_print_styles-post.php', 'hide_publishing_block_using_css');
add_action('admin_print_styles-post-new.php', 'hide_publishing_block_using_css');
function hide_publishing_block_using_css(){
echo '<style>#misc-publishing-actions{display:none;}</style>';
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, admin"
} |
Wp eCommerce meta information search
Out of the box, WP eCommerce does not support Meta search. This is a big problem if you are selling books online and need clients to be able to search by the most important Meta tag, Author!
Can someone please tell me how I could go about including the meta information search or is there a better plugin that does not cost an arm and a leg to search for meta information too?
Many thanks | You can find a duplicate question here that has a number of suggestions and references to plugins that will help. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "search, plugin wp e commerce"
} |
How can I make my blog private?
I want to create a blog to share with my family, but random Internet strangers should not be able to read the posts.
**How can I make posts hidden to the public, by default?** I know I can manually edit the visibility of single posts while I edit them - one at a time.
**Is there some global preference setting that I could set to "private"?** That would have the benefit of also working with the Wordpress app for iPhone, as well as the "post-by-mail" feature of Jetpack. Both of these would otherwise publish a normal, public post.
Several old answers mention variants of the outdated "Members only" plugin - but this is outdated so not an option, even though it might have been a good solution. This plugin question also has the same goal, but it's aimed at plugin development, and the answers don't apply.
**Is there really no (current) plugin that does this?** | I finally found something (I think): **Network Privacy** is currently in version 0.1.4 but looks just about right.
When installed, there's a new _Privacy_ setting screen where I can choose, e.g.
> I would like my site to be visible only to Site contributors.
Given that new users automatically get the permission level _Subscribers_ when they sign up, this setting allows me to select among the registered users and promote them to the _Contributor_ level.
When I visit the site without being logged in, or logged in as a Subscriber (lowest level of registered users) then I am redirected to the login screen that also includes the message:
> [My site] can be viewed only by contributors and above.
> Subscribers and logged-out users are not able to view this site. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "posts, plugin recommendation, private"
} |
Check to see if post is live before displaying the content
I'm trying to pull the content from a post/page into a template file.
I'm using the following code, which works fine HOWEVER the content is pulled in regardless of whether it is set to 'live' or 'draft'.
Is there a way of checking to see whether the post is live before pulling in the content?
<?php show_post('Offers'); // Shows the content of the offers page. ?>
Thank you
* * *
Please note this function is being used...
<?php
function show_post( $path ) {
$post = get_page_by_path( $path );
$content = apply_filters( 'the_content', $post->post_content );
echo $content;
}
?> | Your custom function `show_post()` uses `get_page_by_slug()` to retrieve the specified page.
Looking at source, it doesn't look like `get_page_by_slug()` uses `post_status`. So, you'll need to query `$post->post_status` within your `show_post()` function if you want to account for it in the function output:
<?php
function show_post( $path ) {
$post = get_page_by_path( $path );
$content = '';
if ( 'publish' == $post->post_status ) {
$content = apply_filters( 'the_content', $post->post_content );
}
echo $content;
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "posts"
} |
NextGen - Display Image Count Per Gallery
I am using the NextGen gallery WordPress plugin for a site. In my gallery.php template I want to retrieve the number of images for each gallery displayed in the loop. I cannot figure out a way to get the data and print it under the thumbnail of each gallery that's called in gallery.php
Here is where I want to insert the gallery image count and print it:
<?php
global $wpdb;
$images = intval( $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->nggpictures") ); ?>
<a rel="prettyPhoto" href="<?php echo $image->imageURL ?>" <?php $image->thumbcode ?>>
<span>view</span>
</a>
<?php echo $images; ?> pictures | Using your above code, you were just missing the WHERE clause. Hopefully that should work.
<?php
global $wpdb;
$images = intval( $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->nggpictures WHERE galleryid = {$gallery->ID}") ); ?>
<a rel="prettyPhoto" href="<?php echo $image->imageURL ?>" <?php $image->thumbcode ?>>
<span>view</span>
</a>
<?php echo $images; ?> pictures
It's not the best way to implement it, but if it works for you :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "gallery"
} |
Show preview posts and pages to clients
My clients wants to see the changes i have made in his wordpress site before publishing.
Is it a good method, paste the page preview link to show to him? Of course this method only works if we are both logged in the Panel Administration. Otherwise what how do you recommend to do? I can not physically meet up my client so that's why i need a solution.
Many thanks | Password-protect and publish the page and send your client the password. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "pages, previews"
} |
Is it bad to store many files in a single folder?
I upload thousands of images and it stored in a single folder. Is it bad if too many images are in a single folder? would that slow down the loading of the image even though you're viewing an attachment image which has a path defined? | No the depth of your directory structure has almost no impact to load time.
Maybe if your structure is very depth and the URLs for the images are very long you can hit the maximum length or your markup blows up. But a flat hierarchy should not be a problem as long as you keep the file names short enough.
Then again, if your store everything in one directory, there may be name collisions. But WordPress checks for that during the upload with `wp_unique_filename()`, so you should not worry about that too. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "filesystem, performance"
} |
Custom Post Type Archive.php
I have a custom post type called 'camps', and in there I have different categories ie derbyshire, staffordshire etc.
I have created a template archive-camps.php for this.
archive-camps.php works fine when we go to www.domain.com/camps but if we go to www.domain.com/camps/derbyshire it uses the default archive.php
Why does it do this? | From Codex:
1. taxonomy-{taxonomy}-{term}.php - If the taxonomy were sometax, and taxonomy's slug were someterm WordPress would look for taxonomy-sometax-someterm.php. In the case of Post Formats, the taxonomy is 'post_format' and the terms are 'post-format-{format}. i.e. taxonomy-post_format-post-format-link.php
2. taxonomy-{taxonomy}.php - If the taxonomy were sometax, WordPress would look for taxonomy-sometax.php
There is no custom post type custom taxonomy archive page. Custom taxonomy can exist without custom post type. So what you need is a taxonomy template. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "archive template"
} |
List of taxonomy archive index page links
I want to show all my post taxonomies on the left side of the web page in such a way that when a person click on it the post can be displayed according to the taxonomies.is there anyway to display them and i also want to add some style in it. | You can build a list using two functions: **`get_terms()`** and **`get_term_link()`** :
<?php
function wpse73271_get_term_archive_link_list( $taxonomy ) {
// First, get an array of term IDs
$term_objects = get_terms( $taxonomy );
// Now, loop through $term_ids and get
// an array of term archive permalinks
foreach ( $term_objects as $term_object ) {
$term_object->url = get_term_link( $term_object, $taxonomy );
$term_object->permalink = '<a href="' . $term_object->url . '">' . $term_object->name . '</a>';
}
// Now, build an HTML list of permalinks:
$output = '<ul>';
foreach ( $term_objects as $term_object ) {
$output .= '<li>' . $term_object->permalink . '</li>';
}
$output .= '</ul>';
// Now return the output
return $output;
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, taxonomy"
} |
After activating a Plugin, /wp-admin is no longer accessible
After installing/activating AWPCP (Another Wordpress Classified Plugin), when I type wp-admin/ I get a blank page but with /wp-login.php the login appears.
I this there's a problem with redirection or .htaccess with that plugin but I can't find out what it is. | the plugin is causing a 500 error but php debugging is turned off. The fix it, FTP into the server and remove the plugin then your admin will be back up and running. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "plugins, wp admin"
} |
Convert Wordpress pages to PDF
Just like I customize the CSS print for a page, I want to be able to convert the page to PDF.
Many plugins I tried just display main content of the page or post without design; just plain text. I want to be able convert the page to PDF as it is.
Is there a way to do this even without a plugin? | WP-MPDF has always worked extremely well for me and has a decent templating system you can override. Thanks! | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "plugins, pdf"
} |
WP query by custom post type slug/name
I am running a simple wp query to retrieve just one post.
But the post is a custom post-type post, not a normal post
$ajaxBike = $_GET['varbike'];
$bikeProfile = new WP_Query(array(
'name' => $ajaxBike,
'meta_query' => array(
array(
'key' => 'app_visibility',
'value' => 1,
'compare' => '='
)
)
));
or...
$ajaxBike = $_GET['varbike'];
$bikeProfile = new WP_Query('name='.$ajaxBike);
But I think the **name** parameter only works for posts. But I'm struggling to find anything to work with a custom post type slug.
Can you anyone help work out how to query a custom post type using the slug?
Thanks in advance! | 'post_type' => 'custom post type slug'
By default 'post_type' is set as 'post', you will need to specify your custom post type in any query you make.
In future refer here:
< | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "custom post types, slug"
} |
wordpress get gallery images title
I am retrieving some images post with:
$img = wp_get_attachment_image_src( $attachment_id, 'full' );
How can I retrieve the image title?
Thanks. | In WordPress attachments are stored as posts so you can use most of the post specific WordPress calls and functions to read/write data associated with the attachment. This applies to post meta data for an attachment as well.
So in this case, since you have the post ID ( same as $attachment_id ) you can simply use the `get_the_title()` function:
$sImageTitle = get_the_title( $attachment_id );
This returns a string of the post's title for the given post ID.
See more info. at the codex docs here. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "images, gallery, get the title"
} |
How to display some settings for super admin user only using Settings API
I'm developing a plugin with an options page using the Settings API.
I'd like to have one options array stored for my plugin, but on the settings page, I'd only like some of the settings to be visible to admin users, but the full list of settings to be available to the super admin.
Is this possible? | Test the current user’s role with `current_user_can( 'administrator' )`:
if ( current_user_can( 'administrator' ) )
{
add_settings_field( /* arguments */ );
// or
add_settings_section( /* arguments */ );
}
Make sure to use the same check when you save the options. Otherwise your regular users might delete the values. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "options, settings api"
} |
Wordpress $wpdb no result
I have the following code in my functions.php
$code = 'EUR';
global $wpdb;
$query = 'SELECT * FROM ';
$query .= $wpdb->get_blog_prefix() . 'fxbase ';
$query .= 'WHERE code= '.$code;
$data = $wpdb->get_row( $wpdb->prepare( $query ), ARRAY_A );
The problem is the above query does not give any result. Just to test the following query in mysql is working fine:
SELECT * FROM `1621_fxbase` WHERE `code` = 'EUR'
Not really able to figure out what is the issue here. | Your specific issue in that code is that you're missing the quote marks around the $code.
`$query .= 'WHERE code= '.$code;`
Should be:
`$query .= 'WHERE code= "'.$code.'"';`
In the long run, you should indeed use prepare() properly, but this is the specific problem with the code you posted. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, wpdb"
} |
Replace function in a child theme
Is there a way to replace a function by another function in a child theme? In other words, in a theme there is a function named "theme_function" and this function is called by several files inside the theme.
I would like to find, if exist, an action that replace all occurrences of "theme_function" with another function "child_function" inside the child theme. Please note that "theme_function" that I want to replace do not have the following block:
if ( !function_exists('theme_function') ) :
because if it that case is easy to replace the theme_function with another function having the same name in functions.php | If the parent-Theme function in question isn't either pluggable (i.e. wrapped in a `if( ! function_exists( $function ) )` conditional) or filterable (i.e. returns its output wrapped in a `apply_filters( $filtername, $output )`), then there's no easy way to override the function.
You'll have to do one of the following:
1. Replace all template files that contain instances of the function call, and replace those calls with your own child-Theme function, in all such templates
2. Modify the parent Theme, to delete (or make pluggable) the function in question | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "theme development, functions, actions, child theme"
} |
How to inject content after <body>
I would like to inject some elements directly after the `<body>` tag.
Is that possible using only WordPress hooks? | Just add a custom hook to your template:
<body>
<?php do_action( 'wpse73370_custom_hook' ); ?> | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 3,
"tags": "hooks"
} |
WordPress Admin Interface not styled properly
The laptop I was working on recently crashed. But, I managed to get everything on it backed up, including my recent WordPress project off of my local server (I use MAMP).
I uploaded my SQL database and copied the WordPress website folder into my local server. The WordPress login interface looks normal, but after you get the login, it looks like this:
.
Normally, I would just query_posts three times. Undoubtedly, this is a hack. Normally, it doesn't cause speed issues, however this site has roughly 50k images, and I'm afraid it will cause the load times to significantly decrease.
Is there a better way to do this way to do this? Maybe pull in all images and then sort them based on the category? | It's not a hack, this is what databases are designed for- querying large quantities of data. If you're concerned about load, you should employ caching on data that doesn't change frequently.
That said, you should not be using `query_posts` to create additional queries. Really, you shouldn't be using query_posts at all. Create additional queries via `WP_Query`. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "wp query, query posts, templates, advanced custom fields"
} |
How can i add all videos from youtube playlist as post?
I want to add 200 videos from YouTube playlist to my WordPress blog. Each video iframe add as each post to particular category. I searched many plugins but that's not meet my requirement. | The Youtube playlist have a xml strema, RSS feed.
You can parse this and create post via `wp_insert_post()` and add as content the URL to the video. Publish this and you have wich each new video from the playlist a new post.
The best way is, that you write a custom plugin. But you can aslo use a auto publisher plugin for feeds. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "plugins, youtube"
} |
Using global $post v/s $GLOBALS['post']
It's probably more of a PHP question, but I would like to know if there are any differences in using
global $post;
echo $post->ID;
when compared to
echo $GLOBALS['post']->ID;
to access the ID of a post in WordPress.
This answer on SO suggests that the first method is quicker to process, while the second method is quicker to write.
I also noticed that the first method is often mentioned in the Codex while the second method is mentioned on `the_content` filter page.
Is this only a matter of preference? Or does it come to performance and security too?
Thanks | There is no difference when you are using just `echo`. What works different is `unset()`:
function test_unset_1()
{
global $post;
unset( $post );
}
function test_unset_2()
{
unset( $GLOBALS['post'] );
}
test_unset_1();
echo $GLOBALS['post']->ID; // will work
test_unset_2();
echo $GLOBALS['post']->ID; // will fail
The reason is that `unset()` destroys just the local reference in the first case and the real global object in the second.
For readability use always `$GLOBALS['post']`. It is easier to see where the variable is coming from. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "globals, coding standards"
} |
How do I remove quantcast from my sites?
When I use ghostery on chrome, it finds Quantcast, wordpress stats and google analytics on my sites (nathanblack.com and knuckletattoos.com). I have jetpack and google analytics installed, but where is quantcast coming from and how do I remove it? | Quantcast is coming from the Stats component of JetPack.
You can:
1. Disable Jetpack Stats
2. Directly block Quantcast, such as via the DoNotTrack Plugin | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin jetpack, statistics"
} |
Using get_terms for custom taxonomy in functions.php
I`m trying to retrieve the names of taxonomy items and include them into a theme admin panel.
function retrieve_my_terms() {
global $terms;
$terms = get_terms('taxonomy');
foreach ($terms as $term) {
$option = $term->name;
return $option;
}
}
The function is added after the functions which created the custom post type and taxonomy.
From what I've found out, it seems that the `init` action occurs after the theme's functions.php file has been included, so if I'm looking for terms directly in the functions file, I`m doing so before they've actually been registered.
In other words, init action doesn't fire until after the theme functions file is included, therefore any term retrieval must occur after init.
My problem is that I don`t know how to retrieve the terms after the init.
Any answer will be much appreciated!
Thank you! Madalin | You can add the action on the init itself, just increase the priority of the `add_action` call. The higher the priority the later the function is called.
`add_action('init', 'retrieve_my_terms', 9999);`
But my suggestion is that you should do these kind of things as late as possible, preferably just before the first time they are used. There's an action `'wp_loaded'` which gets called after full wordpress has been loaded & ready to start working on the output. That action might work for you. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "functions, taxonomy, actions, terms, init"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.