INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Word limit in post_content after more tag
I am using the following code to hide the teaser and show content only after more tag in loop:
<?php
$after_more = explode(
'<!--more-->',
$post->post_content
);
if( $after_more[1] ) {
echo $after_more[1];
} else {
echo $after_more[0];
}
?>
Is there anyway to show only first 50 words instead of entire post content? I want to hide teaser and show 50 words after tag. | Use `wp_trim_words` function to limit the content to a certain number of words and returns the trimmed text. Example use of `wp_trim_words` function.
<?php
$content = get_the_content();
$trimmed_content = wp_trim_words( $content, 50, NULL );
echo $trimmed_content;
?>
So I added `wp_trim_words` function in your code to get 50 words after `<!-- more -->`.
<?php
$after_more = explode( '<!--more-->', $post->post_content );
if( $after_more[1] ) {
$content = $after_more[1];
} else {
$content = get_the_content();
}
$trimmed_content = wp_trim_words( $content, 50, NULL );
echo $trimmed_content;
?>
Edited to show 50 words from content if there is no `<!--more-->` in post content. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "the content, read more"
} |
Change date from 2015/02/23 to "1 min ago"
So here is my code to display the post created date:
$date_create = '<div class="mydate-created">';
$date_create .= get_the_date('',$product->id);
$date_create .='</div>';
$output .= '</div>';
$output .= '<div class="mydate-created">';
$output .= get_the_date('',$product->id);
$output .= '</div>';
It displays the date of post created as the following "2015-02-23"
I know there is setting in the backend to change the date displayed.
However is there a way to display it like "1 min ago" or " 1 hour ago"?
Thanks! | Here you go. This goes in `functions.php`
This changes the time on your website everywhere. Now you can keep using `<?php echo get_the_date(); ?>` in your loop or theme files.
// Relative date & time
function wpse_relative_date() {
return human_time_diff( get_the_time('U'), current_time( 'timestamp' ) ) . ' ago';
}
add_filter( 'get_the_date', 'wpse_relative_date' ); // for posts and pages
// add_filter( 'get_comment_date', 'wpse_relative_date' ); // for comments
I added a PHP comment before `add_filter` to also change comment dates too. Because I am not sure if you want that for comments too. Remove PHP comment if needed. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "date"
} |
Get only one product category woocommerce
I have to get and show only one category name from a product. I have almost read everything and tried everything.
<?php
$term = get_the_terms( $post->ID, 'product_cat' );
foreach ($term as $t) {
$parentId = $t->all;
if($parentId == 0){
echo $t->name;
}else{
$term = get_terms( 'product_cat', array('include' => array($parentId)) );
}
}
?>
It shows one long string with all the category names. How should I get only one category and show its name. | Before I begin, just one note, there is no property called `$all` in `get_the_terms`. Here are the available fields which you can use
stdClass Object
(
[term_id] =>
[name] =>
[slug] =>
[term_group] =>
[term_order] =>
[term_taxonomy_id] =>
[taxonomy] =>
[description] =>
[parent] =>
[count] =>
[object_id] =>
)
I'm not very sure what you want to achieve looking at your code, but if you need only one term from the returned array, you can do something like this: ( _NOTE:`get_the_terms` returns a `WP_ERROR` object on invalid taxonomy, so you want to check that, also check whether or not you have terms retrieved_)
$terms = get_the_terms( $post->ID, 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) {
echo $terms[0]->name;
}
`$terms[0]` will return the first term in the returned array. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "terms, woocommerce offtopic"
} |
How do I turn off the blog and archives?
Is there a fixed set of htaccess rewrite rules I can use to "turn off" everything blogging related?
It's not enough to just not show the links in the menu, I want to completely hide everything related to the blog part, including blog posts, archives, tag and category pages. So people or robots can't come across it by guessing the url or though the sitemap.xml In other words just use WP as a CMS for a website. | You are already using pages which does not work the same as posts.
You have to remember, pages don't have taxonomies and they are excluded from the main query by default on all archive pages and the homepage, so there can never be any links to any kind of archive.
Archive pages, whether date, category or tag archives, are just dummy/virtual "pages" which does not exist. Archive pages are just a way to group posts together which shares a common object. If a grouping object does not exist, the archive page can never exist
To conclude, there will be no links to archive pages that can be "guessed" by robots or humans, it is as I said, they will never exist. Links that does not exist will never be indexed anyway.
And any link in a site that does not exist will simply 404, it will not display blank pages | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "rewrite rules, blog"
} |
error_log over 70GB. How to stop this?
I just migrated a website from a host to another. And in one day, my error_log got up to 70GB. How to stop this? | Most important thing here would be to figure out what's causing the errors as opposed to just hiding them. 70 GB file might be tough to open, so you can use tail to open up the last several lines of it `tail -f error.log` and see what's going on. Maybe it's a quick fix.
If it's filling up with notices and things you're okay with you might have debugging turned on? Turn it off in wp-config:
define( 'WP_DEBUG', false );
// don't generate log
define( 'WP_DEBUG_LOG', false );
// don't display errors
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', false ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "errors"
} |
Genesis - Adding custom hooks to display secondary navigation
within my functions.php I added the following piece of code to display my footer accordingly:
//* Customize the entire footer
remove_action( 'genesis_footer', 'genesis_do_footer' );
add_action( 'genesis_footer', 'my_custom_footer' );
function my_custom_footer() {
?>
<div class="site-footer-logo">
<img src="<?=get_stylesheet_directory_uri();?>/images/my-logo-small.png" alt="My Logo Small" />
</div>
<p>Copyright © <?=date('Y');?>, my-url.com.</p>
<?php
}
I want to have the secondary navigation menu displayed between the div `.site-footer-logo` and the following paragraph. Can i just add something like `do_action('my_own_hook');` and then access it via `add_action( 'my_own_hook', 'genesis_do_subnav' );` ?
Is this 'allowed' in the Genesis world?
Thanks. | Yes. you can do that.
function my_custom_footer() {
?>
<div class="site-footer-logo">
<img src="<?=get_stylesheet_directory_uri();?>/images/my-logo-small.png" alt="My Logo Small" />
</div>
<?php do_action('my_own_hook'); ?>
<p>Copyright © <?=date('Y');?>, my-url.com.</p>
<?php
}
add_action( 'my_own_hook', 'genesis_do_subnav' );
function genesis_do_subnav(){
wp_nav_menu( array( 'theme_location' => 'secondary-menu' ) );
}
You also can directly add:
</div>
<?php wp_nav_menu( array( 'theme_location' => 'secondary-menu' ) ); ?>
<p>
Note that `secondary-menu` here should be registered. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "templates, hooks"
} |
pre_get_posts having no effect on my category archive
By default, site is set to show 4 posts per page, but on a particular category (id 76) archive I want it to show 12. I've included this code in functions.php but it's not working. What am I missing here:
add_action('pre_get_posts','filter_archive');
function filter_archive( $query ) {
if ( ! is_admin && is_category('76') && $query->is_main_query() ) {
$query->set('posts_per_page', '12');
}
return $query;
} | You've got a typo there, should be: **is_admin()**. You should enable debugging by setting **define('WP_DEBUG', true);** in wp-config.php to see such errors. Also there's no need of returning anything in action hook.
add_action( 'pre_get_posts','filter_archive', 1 );
function filter_archive( $query ) {
if ( ! is_admin() && is_category('76') && $query->is_main_query() )
$query->set('posts_per_page', '12');
}
**_Sidenote** : personally I prefer to rely on slugs than on IDs in such cases. If the website needs to be set up from scratch on new database, I have more flexibility. I also avoid inconsitencies between development instance and production instance which have (and should have) different databases._ | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "pre get posts"
} |
Overwriting templates in child theme and performance
Is it bad for performance to overwrite custom templates in the child theme?
For example: I have a template called single-music.php in my parent theme. I have put single-music.php in the child theme and have made custom changes there. Is this bad for performance or the incorrect way? | Actually, what you have described is the correct way to do things and there shouldn't be any noticeable impact on site speed and performance.
Using child themes also has the benefit of allowing your changes to persist through theme upgrades. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "themes, child theme, performance"
} |
Site needs massive upgrade - how to proceed?
I have a former customer who, contrary to my recommendations, has not stayed on top of their WP upgrades. They now need to make the leap from 3.5.1 to 4.1.1 (or whatever is current at the moment). They used a fairly vanilla theme (might have even been Twenty Eleven), and not used too many plugins.
I have found numerous threads (here and elsewhere) that talk about doing this 1 mini-upgrade at a time. Is this really necessary, or can bigger steps be taken? E.g. 3.5.1 -> 3.9, then 3.9 -> 4.0, and then 4.0 -> 4.1.1
Thoughts or experiences are appreciated. | Check out the Codex on Upgrading Across Multiple versions.
Regarding the upgrading steps, it says:
> If you plan on upgrading across more than two major releases, please consider upgrading incrementally to avoid potential conflicts and minimize the risks of database damage. For example, if you plan on upgrading from 2.5 to 4.1.1, upgrade to 2.7 first, followed by 2.9, then 3.1, and so on. Essentially, it's okay to skip one release, but never skip TWO when upgrading.
So according to this advice, your upgrade sequence could be:
3.5.1 -> 3.7.x -> 3.9.x -> 4.1.1
I agree with the comments by @Milo and @PieterGoosen; You shouldn't experiment with this on a production install, test this first on your dev install. Deactivate plugins before the upgrades and activate them afterwards, one at a time. Remember to activate the debug log and scan through the `debug.log` for errors.
Remember to backup everything.
You can find the old releases here. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "upgrade"
} |
Excerpt for pages not showing
I am creating a simple wordpress theme and need excerpts for pages. I have tried the code from many topics some resolved on 'wordpress SO' but nothing works.
Because I created the theme from scratch I added a blank functions.php file and put the following code in it.
add_action( 'init', 'my_add_excerpts_to_pages' );
function my_add_excerpts_to_pages() {
add_post_type_support( 'page', 'excerpt' );
}
Nothing comes up so far, but no errors either. Am I doing something wrong? Do i need to register the functions.php file? Any help would be great.
Should add that this is on XAMPP as I am doing everything locally at the moment. | Ok this was a rather simple answer. It appears that once you add the code you have to expand the screen options and enable it in the actual admin view.
This link is what helped me `add_post_type_support()`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, theme development, excerpt"
} |
Get the post thumbnail with wp_query
I am trying to get the post thumbnail to show in line with these other functions and am having no luck:
Info:
<?php echo '<h2><a href=\"' . get_permalink($attractions->post->ID) . '\">' . get_the_title($attractions->post->ID) . '</a></h2>' . get_the_post_thumbnail($attractions->post->ID, 'full') ;?>
I have tried all variations from Googling for an hour and cannot figure this out.
Any suggestions would be great. | If you are using this inside the loop of your `WP_Query` then why are you providing the `Post ID` parameter in functions. You don't need to do that.
So your code will become this.
<?php echo '<h2><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>' . get_the_post_thumbnail( get_the_ID(), 'full' ); ?>
And please read the answer and explanation by @PieterGoosen. He well explained how WordPress functions usually works. And how can you echo the results with `get_` prefix.
Also you were using `\` before double quote which you don't need to do here. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "wp query"
} |
Remove "Category:", "Tag:", "Author:" from the_archive_title
I have the following code in my theme's archive.php:
<?php the_archive_title( '<h1 class="page-title">', '</h1>' ); ?>
This gives me titles like "Category: Russia", "Tag: America", "Author: John".
I would like to remove the "Category:", "Tag:" and "Author:" part and just display the category, tag and author names.
Does anyone know how to accomplish this?
Thank you. | You can extend the `get_the_archive_title` filter which I've mentioned in this answer
add_filter('get_the_archive_title', function ($title) {
if (is_category()) {
$title = single_cat_title('', false);
} elseif (is_tag()) {
$title = single_tag_title('', false);
} elseif (is_author()) {
$title = '<span class="vcard">' . get_the_author() . '</span>';
} elseif (is_tax()) { //for custom post types
$title = sprintf(__('%1$s'), single_term_title('', false));
} elseif (is_post_type_archive()) {
$title = post_type_archive_title('', false);
}
return $title;
}); | stackexchange-wordpress | {
"answer_score": 127,
"question_score": 84,
"tags": "functions, archives"
} |
Schedule Page to Menu
Every week I tend to have 2-4 pages scheduled though I need to get them added to my menu as well.
The "Add New Top Level Pages to Menu" option won't work in my case though as the pages in question aren't top level. In odd cases they're subpages of subpages.
Does anyone know of any way to schedule pages to add to a menu with or without a plugin? I would try and code one in but it's a little too complicated for me.
I posted this exact question on the WordPress support forum and it's gone unanswered for too long, hoping for some answers here.
Thanks.
EDIT: Side question, is there a way to schedule an edit? | I believe that this plugin will do what you want.
**Jamocreations Auto Submenu** <
Here is also a link to the author's site, < , where he discusses why he built the plugin and also two other plugins that also work similarly. The advantage of the Jamocreations Auto Submenu plugin though is that if later you want to edit the menu using Wordpress Menu editor the entries are actually visible there so you can reorder them or whatever.
The plugin works based on selecting a parent page from the Wordpress page editor. If the parent page or parent sub-page has been added to the Wordpress menu, then its child pages will automatically be added as well. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "menus, pages, sub menu, child pages, scheduled posts"
} |
How do I set a specific template for sub-categories?
There's a few posts about getting sub-categories to use the same template as their parent but I want to do something slightly different.
I have a category 67, and I want all sub-categories of 67 to use a specific template. Not the default template, and not the custom category-67.php template.
How do I do that?
I have the following code in functions.php, but it also seems to change the template of category-67
// use specific template depending on category
function myTemplateSelect() {
if (is_category() && !is_feed()) {
if (is_category(get_cat_id('67')) || cat_is_ancestor_of(get_cat_id('67'), get_query_var('cat'))) {
load_template(TEMPLATEPATH . '/category-slider.php');
exit;
}
}
}
add_action('template_redirect', 'myTemplateSelect');
Eventually I will want to add a few more categories to this also.
Any ideas?
Thanks | I would recommend using the `category_template` filter - just check if the current category is an ancestor of `67`:
function wpse_179617_category_template( $template ) {
if ( cat_is_ancestor_of( 67, get_queried_object_id() /* The current category ID */ ) )
$template = locate_template( 'category-slider.php' );
return $template;
}
add_filter( 'category_template', 'wpse_179617_category_template' ); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "categories, templates"
} |
Customize Wordpress admin-bar
I would like to move the admin panel which is shown when I am on my website, not the one in the dashboard.
Now it is as usual, at the top but it is interacting with my fixed navigation, hiding it partially. So I would like to put it to the right site vertically. Is there a setting somewhere to do this or do I have to use CSS? | There is no setting of putting the admin function vertically but if its a nuisance you can choose to not to display it by adding this filter to your functions.php file. The admin bar will be hidden in the frontpage but will be visible in the dashboard
add_filter('show_admin_bar', '__return_false');
When you are working you can also hide it temporarily using firebug. Just select the div #wpadminbar and apply the visibility CSS rule :
visibility:hidden;
This is not a permanent thing it just helps you to visualize the fixed menu hidden beneath your admin bar. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "admin bar"
} |
Unregister Settings Error
Is it possible to unregister or unset an error that has been added using `add_settings_error`? What I am trying to do is run some unit tests on my settings validation function, but I'd like to reset any errors that may have been added in previous tests in the `teardown` function.
Thx. | If you look at the source of `add_settings_error()`, you will see that the errors are stored in the `$wp_settings_errors` global. So in your `tearDown()` function, you can do this:
$GLOBALS['wp_settings_errors'] = array();
Also, don't forget to call `parent::tearDown()`. I sometimes forget, and it can lead to strange behavior. ;-) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "errors, settings api, unit tests"
} |
How to change strings in the theme/core?
When I use Joomla I can change a core string using the language files. So where it would say "Cart" you would go into the language file and change it to what you want it to say.
I want to be able to do this for one of our client's websites which uses WordPress. Is this possible? I am using the wpex-adapt theme.
The exact bit I want to change is on the Portfolio page on the individual item page where it says "newer" and "older" which I want to change to "previous" and "next".
Any suggestions will be greatly appreciated. | This really depends on how your theme has been built, some themes supply a "Translations" file where you can edit most strings. These are usually .po files and can be found in the translations folder within your theme.
If that doesn't help out I would suggest grepping for the string you want to change, and manually editing the files then uploading them to the server. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "language"
} |
WPDB Table Does Not Exist
From this code:
global $wpdb;
$sidebar_table = $wpdb->prefix . 'w3care_sidebar_position';
$checkad = $wpdb->get_results( $wpdb->prepare( "SELECT ad_id, sidebar_position, ad_type FROM `%s` WHERE page_id = '11646' AND page_type='page'",$sidebar_table ));
I'm getting the following error:
WordPress database error Table 'wp_rainnews.'wp_w3care_sidebar_position'' doesn't exist for query SELECT ad_id, sidebar_position, ad_type FROM `'wp_w3care_sidebar_position'` WHERE page_id = '11646' AND page_type='page' /* From [siteurl/] in [/urltopluginindex/index.php:855] */ made by .....
But I don't know how this is possible. If I echo $sidebar_table it returns **wp_w3care_sidebar_position** , so where is this wp_rainnews coming from? And what's with the quotes around it? If anyone can offer any help I would be very appreciative. :) | You can't use `wpdb::prepare` to inject table names - just use `"SELECT ... $sidebar_table"` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wpdb"
} |
I'd like to add an fa icon before a link in my 'recent post' side bar
Similar to your 'how to format' side bar----> I've got the code that will pull the icon the question is: where do I insert that, so that with every new post a link appears in the side bar with the icon in front.
It might be solved through css, but that is not the answer I am seeking. I am sure that the code to invoke an arrow can be inserted into the php.
The question is which php file do I need to modify in order to achieve this. | Sorry, I don't have enough reputation to ask you in comments: Could would be nice, to show what you want to achieve, but you are maybe wondering about this in CSS (if you have implemented FontAwesome already):
yourlement:before { //replace with your element
font-family: FontAwesome;
content: "\f061"; //replace with your icon
}
Here is jsfiddle | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sidebar"
} |
Change Front Page Word Press 4.1
I simply want change which page is defined as the front page. It is currently my About Me page; I want it to be the page called Home. Thanks. | Go to Settings -> Reading -> Front Page Displays. Set it to Static Page and choose your Home from the drop-down. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "frontpage"
} |
Single_cat_title() print the title before text
When I use **single_cat_title()** get the name of the current category in archive page, it works perfectly but it prints the category title before the text
<h2>
<?php
if (is_category()){
echo 'Category: ' . single_cat_title();
}
?>
</h2>
It says:
> UncategorizedCategory:
How do I fix it? Thank you. | Set the `display` argument of the function to `false`.
<h2>
<?php
if (is_category()){
echo 'Category: ' . single_cat_title( '', false);
}
?>
</h2>
Or, to use the function in its more "helpful" form you could do:
single_cat_title('Category: ');
If the display argument is true, WordPress automatically echoes the content on to the page usually within a wrapper html element and this messes with your `echo`. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "categories, themes, title"
} |
How to prepare the HTML for Wordpress
Right now I'm finishing a design in Photoshop and I'm about to turn it to HTML. After that I'm want to turn it into a Wordpress theme using Underscores starter theme. How can I prepare the HTML so the transition to _s would be smooth and easy without changing a lot of HTML and CSS in order it to fit? | The best and easiest solution (imo) would be to develop your design directly in the Underscore theme. This way you will code only once the design - you won't have to redo the dynamic parts (like the menu items, widgets and other parts managed by Wordpress).
The alternative would be to code your design in plain HTML/CSS/JS and then transform these files in a WordPress theme. But I don't see this solution to be efficient / productive. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, html"
} |
esc_attr on get_post_meta
Simple question,
I see that some themes are using esc_attr or esc_html and url after they define varible with get_post_meta, while others are using it during variable definition. What would be best practice
1.
$portf_icon = get_post_meta($post->ID,'dt_portf_icon',true);
echo esc_html($portf_icon);
or
$portf_icon = esc_html(get_post_meta($post->ID,'dt_portf_icon',true));
echo $portf_icon;
Does it have any difference and which one would be best practices? | The best practice in the WordPress world is to "escape late" i.e. at the point of output. While the two examples are effectively the same, the first one would be more effective if that code is ever refactored and the value of $portf_icon changes between where it's first assigned & where it's output. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "post meta, sanitization"
} |
Avoid user registrations with specific email provider
I have been under a spam attack, someone is creating a lot of users daily, it could be a bot, all those users have the same email provider, is there any way in which I can avoid that anyone creates a user using a specific email provider. | See this hook: `register_post`
add_action('register_post', 'ban_email_2334', 10, 3);
function ban_email_2334( $username, $email, $errors ){
$result = array();
// check if email is from the provider you wish to ban
preg_match('/bannedprovider.com/i', $email, $result);
if( !empty( $result )){
$errors->add('spam_email', __( 'Some choicest abuses you might want to pass on' ));
}
return;
}
This will throw an error and prevent registration | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, user registration"
} |
How to give all CPT a folder automatically based on their slug
This is what I have now and working:
function get_custom_post_type_template($single_template) {
global $post;
if ($post->post_type == 'amazon') {
$single_template = TEMPLATEPATH . '/amazon/single.php';
}
return $single_template;
}
add_filter( 'single_template', 'get_custom_post_type_template' );
But I want something like this:
add_filter('single_template', 'my_single_template_folders_terms');
function my_single_template_folders_terms($template) {
global $wp_query;
foreach( get_post_type(array('public' => true, '_builtin' => false)) as $post_type ) {
if ( file_exists(TEMPLATEPATH . "/{$post_type->slug}/single.php") )
return TEMPLATEPATH . "/{$post_type->slug}/single.php";
}
return $template;
}
I got this error; Warning: Invalid argument supplied for foreach() | Your second function is wrong. `get_post_type($post)` excepts the current post object or post ID or any post object or ID given to it. You are using the arguments for `get_post_types( $args, $output, $operator )` for `get_post_type`, which fails the function which in turn gives you the error in your `foreach` loop.
To rectify your function, use something like this:
add_filter('single_template', 'my_single_template_folders_terms');
function my_single_template_folders_terms($template) {
global $post;
$post_type = get_post_type($post);
if ( file_exists(TEMPLATEPATH . "/{$post_type}/single.php") )
return TEMPLATEPATH . "/{$post_type}/single.php";
return $template;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, directory"
} |
how to display "Edit | Quick Edit | Trash | View" in custom WP_List_Table column?
I have removed "Post Title" in admin column, and created a custom column.
Is there any way to the display "Edit | Quick Edit | Trash | View" link? | Those links are hard-coded to display in the "title" column as part of class-wp-posts-list-table.php. Look at the `single_row()` method in that file, specifically the `case 'title'` to see how those links are constructed. You can probably re-use the same code in your plugin or theme as long as you comply with the GPL license WordPress uses. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "admin, columns, screen columns"
} |
301 Redirect Loop
I have wordpress site hosted on openshift say example.com. I am redirecting example.com to www.example.com (non www to www). I have created alias for www and non www version and updated my cname with app name.
I tried pointing non www cname record to www version and it was working except for homepage (same 301 redirect loop) so i reverted non www cname back to app url.
Now www version is serving but non www version is creating 301 redirect loop by redirecting to itself. My wordpress site url is www.example.com and i have not added any htaccess directives.
How can i properly redirect non www to www version. | I think there is some issue with openshift's php hosting. I found this thread on stackoverflow. So catch is you append port no after host. This .htaccess code **should work**.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) [R=301,L] | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "redirect, htaccess"
} |
I need a lightbox plugin that will apply to gallery
I have a gallery on my page, in this type of syntax:
[gallery ids="1588,1584,1582,1583,1581"]
I would like each image to open up in a lightbox. I've tried the Simple Lightbox plugin, which looks very good, but it doesn't take effect on my site. It requires the_content() to be run on my page template, but I looked at page.php, and I don't see that function being called. I'm using the Nevia theme.
I read SLB's directions, and I don't think I missed any steps. So I wonder if there is another similar plugin that I can use. After searching on Google, I found a lot of things that are somewhat like what I need, but I don't have time to try each one out. | Try this one: Responsive Lightbox by dFactory. It doesn't require the function the_content(), or make any mention of any required functions. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, lightbox"
} |
how to sort post in admin column by recently
i have created custom post type
my problem is:
in admin column, posts are sorted by ID
how can change it to date. In other words, i want to sort post by recently | You must add this part to function.php:
add_action( 'pre_get_posts', 'example_func', 1 );
function example_func( $query ) {
if ( is_admin() && $query->is_main_query() ) {
$query->set( 'order' , 'DESC' );
}
return $query;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "custom post types, sort"
} |
How to use the built in tooltip for form validation error messages in WP admin plugin?
I'm building a wordpress plugin that includes serveral menus in the wordpress backend (admin). I'd like to use as many existing parts as possible and make my menus look like the standard wordpress ones.
Wordpress already does quite nice form validation on its admin forms and I already reuse the `form-required` class to enforce required form fields. However, I also need some validations that require an error message. I found a very nice tooltip-style version when you try to enter letters for media size: !tooltip-style form validation error message in wordpress admin \(media settings\)
Can somebody provide a hint on how to reuse this from a custom jquery form validation script?
My form validation script does an ajax-request to find out if an email address is already taken. So using the number validation won't be enough, I need to put a custom error message inside the tooltip. | That's the standard html5 input validation pop up for chrome, you will have to create the pop up from scratch unless your inputs can make use of html5 form validation such as `type=email` or `required` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp admin, forms, validation, tooltip"
} |
How to convert raw url to hyperlink?
I have a custom field with raw urls and I want to convert them to hyperlinks. So I used this code:
<?php $text = get_post_meta( get_the_ID(), 'Links', TRUE );
echo make_clickable( $text ); ?>
The problem with this code is it doesn't work with urls that contains spaces in them. How can I make it work for urls with spaces? | URL-encode spaces beforehand:
make_clickable( str_replace( ' ', '%20', $text ) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, links"
} |
How to redirect on particular page in wordpress?
<?php
if($result_array['ACK']== 'Success'){
global $wpdb;
$wpdb->insert('wp_paypal_payment', array(
'amount' => $result_array['AMT'],
'post_id' => $_REQUEST['post_id'],
'firstname' => $_REQUEST['first_name'],
'lastname' => $_REQUEST['last_name']
));
wp_redirect( get_page_by_title( 'thank-you' ) );
}else{
header("Location :
}
?>
My query is working but I have no idea that how I simply redirect in my page and display any my page content data in wordpress. So please help me. | You should get ID of the page you're looking for:
$page = get_page_by_title('thank-you');
wp_redirect(get_permalink($page->ID));
exit;
It looks like you want to get page by slug. If that's the case, you should use this function instead.
Also, for Location header don't use space after "Location" string:
header("Location: | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "pages, redirect"
} |
external url for post thumbnail and title
I created a custom category template where I show thumbnails of the posts and a title as url, if you click on the thumbnail or the title you get redirected to the post but I would like to redirect to an external website when you click either on the image or the url.
Wordpress doesn't let me set an external URL. No clue how to takkle that, couldn't find the right plugin and I would like to learn some coding anyway. I am an absolute Beginner. | I use the "Page Links To" plugin. It adds an extra metabox to each post allowing you to send the post to a custom URL. Simple, but it works great. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "thumbnails"
} |
Install an external plugin within the current plugin
I'm trying to install an additional plugin, and all I have is the slug name of the plugin under api.wordpress.org. I've figured out that one could get the zip file's path (download_link) when going to <
What would be the rest? I wouldn't want to do the entire unzipping if there's a built-in function in WP that does that...? | This solution should do the job for you.
<
The solution is meant for theme developers to package to download, automatically install and activate multiple plugins that are either packaged with a theme, downloaded from the WordPress Plugin Repository or downloaded elsewhere on the internet (perhaps a private repository.
The code of the solution can be used to accomplish what you are trying to achieve. The code is also available on github at
Best of luck. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 5,
"tags": "plugins"
} |
Set Display Name to first and last name (phpmyadmin SQL Query)
I'm trying to change all the users Display Names to be their first and last name. I have looked into a number of plugins and wrote my own PHP to try and accomplish this however the site has over 50,000 registered users (I can imagine most are spam from my clients previous site) but because of this the PHP hangs and only gets to about 2000 before giving up.
So I thought that the next best thing would be to write an SQL statement from within PHPmyAdmin to perform the task, However pure SQL confuses the hell out of me and so far all I have been able to do is set the display name to be the users First name I'm not to sure how I would go about getting the Last name as well. Here is the statement that I used.
UPDATE wp_users, wp_usermeta
SET display_name = meta_value
WHERE ID = user_id
AND meta_key = 'first_name'
Any help would be appreciated. | I know this is an old question, but for anyone still looking how to achieve this, the following query should do the job:
UPDATE wp_users
INNER JOIN wp_usermeta AS fn_meta ON wp_users.ID = fn_meta.user_id AND fn_meta.meta_key = 'first_name'
INNER JOIN wp_usermeta AS ln_meta ON wp_users.ID = ln_meta.user_id AND ln_meta.meta_key = 'last_name'
SET wp_users.display_name = CONCAT(fn_meta.meta_value, ' ', ln_meta.meta_value)
Basically you need to add two user meta joins - one to retrieve first name and another for last name, since they are stored in separate rows.
I would highly recommend testing this on a testing/staging server before running it in production. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "database, users, mysql, phpmyadmin"
} |
Why the WP Core team does not allow filter_* functions?
This question is somehow related to this other question.
Provided that is seems we have a solution for the magic quotes issues, why the WP Core team does not allow them?
This is unclear to me and I couldn't find any official statement explaining this decision: just mentions sparse in some trac tickets and blog posts:
* Apparently the issue has been rones by @westonruter: <
* This post from @westonruter actually looks like to be positive: <
As far as I can see, filter_* functions are the best way (even better than WP core functions, in my opinion) to handle validation, filtering and sanitation. Also, they are part of PHPNG (therefore, PHP 7) and everywhere I can see posts saying to use these functions (here in SO, as well as elsewhere). | Because on the minimum version required it isn't always available since the SPL can be disabled on PHP 5.2 and below. The majority of installs running WordPress have it, but not all, and it's the same reason autoloaders and Iterators aren't used.
Moving to v5.3 as a minimum PHP would fix this however as the SPL cannot be disabled in 5.3+, but until that happens.. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "validation, sanitization, coding standards"
} |
Faster image upload on mobile
So, for my wordpress mobile site, there is a button to upload an image (either from camera or phone gallery).
However since the size of mobile images are well over 3 MB, it takes too long to upload them.
Is there a way to reduce the image size before the upload even happens? or to speed up the uploading process.
Thank you guys! | You could try this plugin to reduce file size before the upload. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "images"
} |
How to add different link on each Post
Hello Guys am creating a wordpress theme but how can i implement a download link on each post that is different from each other. | Sure you can . If you want to add one/many file in your post , then you have to create custom field . There is a plugin called ACF ,this will help you to do so very easily . Please have a look to the link below
Advance custom field file upload | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes"
} |
Exclude child comments in get_comments() or WP_Comment_Query?
How do I only get the first level of comments in get_comments() or WP_Comment_Query? I want to query the comments which have 'comment_parent' => 0, and exclude all the child comments.
$args = array(
'number' => 10,
'order' => 'DESC',
'status' => 'approve',
'meta_key' => 'comment_parent',
'meta_value' => 0
);
$comments = get_comments( $args ); | This should do the trick, I guess:
$args = array(
'number' => 10,
'order' => 'DESC',
'status' => 'approve',
'parent' => 0
);
$comments = get_comments( $args );
You can find full list of arguments in Codex. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "comments, query, wp comment query"
} |
Call function without having to wait on response
When submitting a form I want to call an additional function that will connect to a webservice. Because of the slow response time of that webservice, I don't want the page to keep loading untill the process is done.
Instead the action should be fired/called and run on the background.
What is the best way to achieve this? | Use the WordPress HTTP API with a low timeout & blocking disabled. It's what WordPress core does to spawn the cron API:
wp_remote_get(
$url,
array(
'timeout' => 0.01,
'blocking' => false,
'sslverify' => false,
)
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "functions"
} |
Custom theme being prompted for update because of similarly named theme
I've got a custom made theme named "Discovery 2014" on my site and it keeps getting flagged for an update because of a free theme named "Discovery" available via the theme repository. Definitely not my theme, of course. Is there anyway to disable this? I was thinking I might just crank up the version number to like 30 or something that the public theme will never reach. But is there a better or more proper way?
I could always re-name the theme (and going forward I will be using more uniquely identifiable names for themes), but then I'll have to set a ton of stuff back up again, won't I? | There is no intended way whatsoever in WordPress to opt out of updates. Even _not_ intended way is significantly convoluted and needs to intercept HTTP requests being made.
You can disable updates completely with `DISALLOW_FILE_MODS` constant.
If you have to retain update functionality for other stuff you will have to code it from scratch or use a third party implementation, such as Update Blocker (disclosure — was created by me). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes"
} |
How to add page under a custom post type?
I would like to add a page that uses a custom template (page-coffee-about.php), so it will appear under a custom post type called "coffee". The URL of the custom page should be domain.com/coffee/about/. I already have a URL for domain.com/coffee that uses archive-coffee.php.
I've searched and tried several different things (creating a coffee parent page, adding hierarchical => true to the register_post_type() for coffee, along with supports "page-attributes"), but I keep getting a page not found error.
Please note that I am running WordPress 3.7 and cannot upgrade!
Any help would be greatly appreciated. | "Page not found" means it is not a template problem, rather permalink issue. Try setting your permalink to default and than visit the page! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, urls, page template"
} |
date_query not returning some posts in date range
I'm getting some very strange results with the date_query parameter of get_posts. I have a post for which:
date('Y-m-d H:i', get_post_time('U', false, $postid))
returns:
2014-04-03 10:42
This post is returned fine from get_posts with these arguments:
$args = array(
'post_type' => 'post',
'cat' => 41,
'fields' => 'ids'
);
But _not_ with these:
$args = array(
'post_type' => 'post',
'date_query' => array(
'after' => '1980-01-01',
'before' => '2100-01-01',
),
'cat' => 41,
'fields' => 'ids',
);
Other posts seem to come back fine. What could be up? Does date_query query something different to get_post_time? | Your syntax is incorrect for your `date_query`. It should be an array of an array, not just an array.
I also suspect that your problem might be related to PHP and not Wordpress.
Your `before` date is invalid. PHP only supports dates between 13 December 1901 and 19 January 2038, so your dates need to between those two dates. For reference, see `date`
You would also want to include the 'inclusive' parameter and set it to `true` for exact matches
Your query should be something like
$args = array(
'post_type' => 'post',
'date_query' => array(
array(
'after' => '1980-01-01',
'before' => '2038-01-01',
'inclusive' => true,
),
),
'cat' => 41,
'fields' => 'ids',
); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "get posts"
} |
Migrate WooCommerce Orders
I need to export/import all WooCommerce orders from a clients old website to their new website. We basically took their website, redesigned it but the install and everything is the same - besides there being two versions and both are on different servers. We tried replacing postemta and posts but that messed up EVERYTHING, like the pages, menus, etc.
We are on a tight deadline (every moment is crucial) and we need help on this. We are aware of the plugins, but if there is a dirty way to do it we are open to it.
To reiterate: we need to move just the orders from one site to another without messing everything else up.
Thanks in advance! | The reason copying those messed up your site was probably because of id mismatches. That is, posts with the ids of the stuff you're importing already exists.
Regardless, since woocommerce stores orders as a custom post type, your safest bet here is probably the built in wordpress post import/export tool.
1\. In the wordpress backend for the old site select Tools->Export
2\. Choose "Orders"
3\. Download the export file.
4\. In the wordpress backend for the new site select Tools->Import
5\. Click "Wordpress" (install the plugin if you need to).
6\. Choose/Upload the file you created in step 3.
If you need to do this through SQL for some reason, the place to start will be with
`SELECT * from wp_posts WHERE post_type='shop_order'`
Then you'll need to export the result of that query and increment all of the IDs by whatever the auto increment value is on the new table. But that will give you a pretty messy table... | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "woocommerce offtopic, export"
} |
Missing 'Move to Trash' option from bulk select box
I seem to be missing the bulk select option for moving multiple items to the trash. This happens when all plugins are deactivated as well. Has anyone come across this before?
| I would imagine that your role does not have the capability to delete posts. Maybe try installing a Members plugin and take a look. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp admin, bulk, trash"
} |
Can A Post Meta Field Store multiple values that are not in an array?
I have a post_meta field that seems to be displaying multiple values, yet they do not seem to be in an array. Using debug bar, this is what I see inside of the '_custom_post_type_onomies_relationship' meta field.
!screenshot
I want to filter these id's to return titles instead. Because I am using Facet WP, I need the values to NOT be an array when done.
$item_array = get_post_meta( $post->id, '_custom_post_type_onomies_relationship' );
foreach ( $item_array as $item_id ) {
$title = get_the_title( $item_id );
$item_array[] = $title;
}
update_post_meta( $post->id, '_custom_post_type_onomies_relationship', $item_array );
This works just fine except that it is an array. What data type is that custom field before I filter it? How do I reproduce that data type?
Note: Before I filter it, the data type must not be an array because FacetWP can understand it. | Meta data keys do not have to be unique, you can have multiple rows of the same key, each containing singular values. If you use `get_post_meta` to fetch a key and don't set the 3rd argument to `true`, the function gets all the individual values and returns them as an array, which is not the same as getting a single value that is an array saved as a serialized string.
If you want to iterate over the returned array and save new values, you have to call `update_post_meta` for each item in the array, and set the 4th argument of the function, which is the old value of the particular row you'd like to update.
$item_array = get_post_meta( $post->id, '_custom_post_type_onomies_relationship' );
foreach ( $item_array as $item_id ) {
$title = get_the_title( $item_id );
update_post_meta( $post->id, '_custom_post_type_onomies_relationship', $title, $item_id );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "post meta, array, sanitization"
} |
How to make other computer in local network see my theme
I have made WordPress Theme and have 2 themes in WordPress.org repository. So, I do not hard code my themes and pretty well how to use WordPress Theme goes to online.
I use WAMP server with 127.0.0.1 and my local IP is 192.168.100.103. Everything is ok in my computer.
Other computer, try to see my theme. And, only the HTML, the rest (js and css) is not loaded. I have checked with firebug. Then i see the path is < It should be <
How to change the path? Or does any setting with WAMP? | Go to `Admin Panel > Settings > General` and replace `localhost` with your `ip-address` for `WordPress Address (URL)` and `Site Address (URL)` and see if it works. Also don't forget to put your WAMP server online. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 3,
"tags": "localhost"
} |
Filtering by multiple conditions in the loop
I'm trying to filter the posts in my index by multiple conditions.
So far I've tried with this:
<?php $query = new WP_Query(
array(
"post__not_in" =>get_option("sticky_posts"),
'paged' => get_query_var('paged'),
'&meta_key=Sortdate&orderby=meta_value&order=asc')
);
?>
With this piece of code, the first condition will be met, and it won't list posts that are sticky, but the last one will be ignored, ordering the posts by publishing date and not by the meta field "Sortdate".
On the other hand, if I do this:
<?php $query = new WP_Query(
'&meta_key=Sortdate&orderby=meta_value&order=asc')
?>
Then the order is correct, but I'm missing the other conditions.
What am I doing wrong? Any tips? | You cannot mix array syntax and string syntax in the same argument. If you start with array syntax, you should stick with that, the same applies if you start with string syntax, then you should stick with string syntax. Because you are using `post__not_in` which is an array, you should stick with array syntax
<?php $query = new WP_Query(
array(
"post__not_in" =>get_option("sticky_posts"),
'paged' => get_query_var('paged'),
'meta_key' => 'Sortdate',
'orderby' => 'meta_value',
'order' => 'ASC'
) );
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, loop, filters, post meta, order"
} |
replacing words to "..."
So, I have this post title that has a certain length (say 15 words).
When the browser width is reduced, the overflown words are placed to a next line by pushing everything down.
However, is there a way to replace the overflown words with "..." so that there is no pushing down on the other contents?
Thanks! | If you have a max-width on your element you could get around this with CSS like
text-overflow: ellipsis;
white-space: nowrap; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "functions"
} |
How can I selectively insert a header for my shop page in woocommerce?
I use a this line of code in my sites in order to change my header (and hence my css) depending on what template I'm using:
<?php include ('otherHeader.php'); ?>
however, with woocommerce that doesn't appear to be an option for shops. My client has asked specifically that I separate his products onto two separate shop pages, which look different. I've already managed to separate the store into two pages through the menu using product categories instead of the shop page, but is there some sort of code I can insert into my archive-product.php file so that it will check which page it's on, and choose it's header accordingly? | I've found the solution to the problem myself. for anyone out there, surround your header call with the conditional 'is_product_category( 'day' )'. you can read more about it here:
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, headers, woocommerce offtopic"
} |
Wordpress upload images not displaying
Hello I have a wordpress site and I upload images to media library but the images do not display. In wp-content/upload folder there are other folders like 2015/ and then in that folder there are folders with names 02 and 03 and o1.
Why none of my images are showing in the medialibrary. Image gets uploaded on this path like for instance this image was uploaded
<
but the image never displays ... what could be the quick solution I have also updated my wordpress to latest version but still the same problem.
Thanks people | For a quick solution you can download the WordPress plugin photo-gallery <
Once it's installed and activated you hover your mouse over Photo Gallery in your WordPress Dashboard and click Add Galleries/images.
Add a new picture or many pictures in a new gallery and save.
When it's done simply hover your mouse over Photo Gallery and click on Generate Shortcode, select the Gallery you created then click on Generate.
Last step, copy-paste the shortcode that the plugin generate and paste it in any post that you want then save your post.
Voilà :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql"
} |
When is a user's meta data table loaded?
Exactly when is a user's meta data loaded? I'm using many `get_user_meta()` calls for the **current user**. If **all** of a logged in user's meta data is loaded anyway, then this type of call is not a problem. | This page gives you a typical wordpress load <
You can see, the current user is available after the theme is setup but before init. If you are calling these functions within the theme then you will be fine. Otherwise make sure any functions that reference the current user are called using hooks that run after the `set_current_user` hook. The best hook to use will vary depending on the specifics of what you're trying to do. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "user meta"
} |
Shortcode for showing childpages
I found this code snippet that shows childpages only.
It works great, doing exactly what i intend it to do. I want to be able to place this around the site, but i cant place PHP inside the Rich-text editor. I want to convert it to a shortcode.
How do i convert this to a shortcode?
<?php
global $wp_query;
if( empty($wp_query->post->post_parent) ) {
$parent = $wp_query->post->ID;
} else {
$parent = $wp_query->post->post_parent;
} ?>
<?php if(wp_list_pages("title_li=&child_of=$parent&echo=0" )): ?>
<div>
<ul>
<?php wp_list_pages("title_li=&child_of=$parent" ); ?>
</ul>
</div>
<?php endif; ?> | Put this in your theme's functions.php, it will add the shortcode `[child_pages]`:
function wpsc_child_pages($atts){
global $wp_query;
$html = '';
if( empty($wp_query->post->post_parent) ) {
$parent = $wp_query->post->ID;
} else {
$parent = $wp_query->post->post_parent;
}
$pages = wp_list_pages("title_li=&child_of=$parent&echo=0");
if( $pages ){
$html .= "<div><ul>$pages</ul></div>";
}
return $html;
}
add_shortcode('child_pages', 'wpsc_child_pages');
If you want to pass the function variables (e.g. `[child_pages parent=3]`) you would access that variable using the passed `$atts` argument. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode"
} |
Filtering the default avatar list
I'm using the `avatar_defaults` filter hook to filter the default avatar list. For example:
function my_avatar_defaults( $avatar_defaults ) {
$avatar_defaults[' = __( 'Foo' );
return $avatar_defaults;
}
add_filter( 'avatar_defaults', 'my_avatar_defaults' );
This works because if I visit Settings > Discussion and then scroll down, I can see Foo has been added as a default avatar option. See the following screenshot for an example:
!Default avatar list of options
The problem is the `src` attribute of the image displayed next to Foo. It seems to be making a call to Gravatar. Here's an example of the source code I'm getting for the image next to Foo:
<img src=" />
How can I ensure the `src` attribute points to my image URL instead of the Gravatar URL (which seems to have my image's URL inside it)? | You are doing it correctly.
The call to gravatar.com passes the location of your custom image so that WP can load it. Take a look at the query string in the src, you'll see your image location. That's how it works. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "php, gravatar"
} |
How to order by multiple fields using standard query_posts?
In our `archive.php` we show all the items which match our selected category. This works absolutely fine.
Then we improved it by adding (just before the loop) a sort and upping the posts per page from the default 10, like so:
$posts = query_posts($query_string . '&orderby=title&order=asc&posts_per_page=99');
This works even better.
Now, however we want to sort by more than one field, say `menu_order` then `title`. I don't see a way to do this using this query_posts / querystring syntax we have in place. Code samples all involve firing up a new WP_Query, losing track of the query_string. What's the solution? | If you're altering the main query, always use `pre_get_posts` to alter query parameters _before_ the query is run and before the template is loaded. This will be the most efficient and will not break pagination. As of v4, `orderby` accepts an array of arguments, which gives you the ability to have different `order` for each if necessary:
function my_get_posts( $query ){
if( !is_admin() && $query->is_category() && $query->is_main_query() ){
$query->set( 'posts_per_page', -1 ); // show all posts
$query->set( 'orderby', array('menu_order' => 'ASC', 'title' => 'ASC') );
}
}
add_action( 'pre_get_posts', 'my_get_posts' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "loop, query posts"
} |
Echo custom post meta from options array
The code below comes from:
var_dump(get_post_custom($post->ID)).
How can I echo the value of artist_seo_description from my PHP script?
array(5) { ["_edit_last"]=> array(1) { [0]=> string(1) "1" } ["_edit_lock"]=> array(1) { [0]=> string(12) "1425587233:1" } ["photo-artist_tfuse_post_options"]=> array(1) { [0]=> string(1182) "a:4:{s:25:"photo-artist_slider_image";s:0:"";s:28:"photo-artist_slides_interval";s:4:"6000";s:22:"photo-artist_seo_title";s:21:"Crest Drive Residence";s:28:"photo-artist_seo_description";s:985:"This is the description field.";}" } ["_wp_old_slug"]=> array(1) { [0]=> string(22) "crest-drive-renovation" } ["photo-artist_post_viewed"]=> array(1) { [0]=> string(1) "0" } } | `get_post_custom` isn't a great function if you're trying to get values that are serialized, you have to unserialize them yourself.
A better function is `get_post_meta`:
$options = get_post_meta( $post->ID, 'photo-artist_tfuse_post_options', true );
echo $options['photo-artist_seo_description']; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, post meta"
} |
need help with '... read more' excerpt in functions.php
I have this to generate the link:
<a class="view-article" href="' . get_permalink($post->ID) . '">' . __('View Article', 'html5blank') . '</a>';
But I don't want it to open the post page. I want it to pop open my modal like this:
<href="#" data-toggle="modal" data-target="#modal-<?php the_ID(); ?>" class=""> view article</a>
I broke WP once and would like not to do it again. Thanks in advance. | Took me a couple of blind tries, but I got it.
**Before:**
<a class="view-article" href="' . get_permalink($post->ID) . '">' . __('View Article', 'html5blank') . '</a>';
**After:**
<a data-toggle="modal" data-target="#modal-' . $post->ID . ' " class="over">' . __('View Article', 'html5blank') . '</a>' | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, excerpt, read more"
} |
Plugin installation not possible / FTP credentials in WP-config
I have an issue with one of my Wordpress installations.
When I try to install a plugin, WP asks for my FTP credentials. I entered them but neither FTPs nor FTP are working - but the credentials are 100% correct.
I opened up the wp-config.php and pasted the configuration in the file.
When I now want to install a plugin I still see the screen where the FTP data must be entered, its greyed out with the info from the WP config file but with an error text that the connection to the FTP could not be established.
Does anybody know if this is server setting or what is wrong here?
Thanks. | define( 'FS_METHOD', 'direct' );
solved it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "ftp"
} |
Trying to retrieve random post, getting a page
I'm trying to retrieve a random post to link to on my site. I have the following code, but the only thing that it seems to retrieve and display is a link to the homepage. Any help would be appreciated!
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand',
'post_status' => 'publish',
);
$the_query = new WP_Query($args);
while ( have_posts() ) : the_post();
echo '<a href="';
echo the_permalink();
echo '" title="';
echo the_title();
echo '">';
echo the_title();
echo '</a>';
endwhile;
wp_reset_query(); | You need to specify the post type to be a post - try this for your $args instead:
$args = array(
'post_type' => 'post', // Specifying you want posts only
'posts_per_page' => 1,
'orderby' => 'rand',
'post_status' => 'publish',
);
And most importantly, you need to apply the $args to your query, so do this for the loop:
while ( $the_query->have_posts() ) : $the_query->the_post();
See this in the Codex. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query, loop"
} |
Difficult to create unique titles and meta description?
I have just made my first theme for WordPress and I have been searching for information or some kind of tutorial, about how to create some sort of very simple plugin to handle unique titles and meta description for the pages and blog posts.
Is this very complicated? Where can I find info about this?
Preciate some help and guidance to solve this and to be able to develop my skills and a SEO friendly theme.
I'm also curious why I can't use a real SEO plugin like WordPress SEO by Yoast? Despite that I can write a unique title and meta description for each page and blogpost, I just a get the same title on every page and blogpost when I'm viewing my site! Is something missing in my theme?
Thanks! | > Is something missing in my theme?
Most likely. If you're using WordPress 4.1, make sure there is **no** `<title />` in your `header.php` and add the following to your `functions.php`:
add_theme_support( 'title-tag' );
Otherwise, make sure the title tag looks like:
<title><?php wp_title( '' ) ?></title>
You should also have `<?php wp_head() ?>` within your `<head />`, this allows WordPress & other plugins to kick out all sorts of stuff to function correctly. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, seo"
} |
Adding a "Word" in php code
So, I know title is super confusing but I didn't know how to word it.
In the following code, the word "View:" is placed and displayed properly on the page.
<div class="myuserpropageview">View:<?php echo get_post_meta( $post->ID, 'pageview', true );?> </div>
In the following code, how can achieve the same thing? (where do I place "View:"?)
$output .= '<div class="dhvc-woo-view">';
$output .= get_post_meta($post->ID, 'pageview', true);
$output .= '</div>';
Thank you | any word (html) you put between the single quotes will be echoed when you echo `$output`. so you can do this:
$output .= '<div class="dhvc-woo-view">View: ';
$output .= get_post_meta($post->ID, 'pageview', true);
$output .= '</div>';
or
$output .= '<div class="dhvc-woo-view">';
$output .= 'View: ';
$output .= get_post_meta($post->ID, 'pageview', true);
$output .= '</div>';
it's the same. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
Post titles below the post format content
I've been trying to figure out this problem for a while now:
<article class="post">
<div class="entry-header">
<h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
</div> <!-- end entry-header -->
<div class="entry-content">
<?php the_content(); ?>
</div> <!-- end entry-content -->
</article>
This display the title, then the image (audio, video, gallery embed, etc.), then the post info. I am trying to get the Image, then the Title, and then the post info.
I made this picture for what I explained.
!enter image description here
How do I go about this? | I figured out that way to solve my problem. Just get post format then get the content by using `get_post_meta($post->ID, 'variable_name', true);`
Example:
<article class="post post-<?php echo $postformat; ?>">
<?php
if( $postformat == "video" ){
$embed_video_code = get_post_meta($post->ID, 'video_embed_code', true);
if ($embed_video_code) {
echo '<div class="ajax-video-wrapper">';
echo '<div class="ajax-video-container">';
echo $embed_video_code;
echo '</div>';
echo '</div>';
}
}
?>
</article> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "content, post formats"
} |
Getting Plugin to read all script files
In my pluging I created a file-1.php file which contains the plugin info and some functions for the plugin functionality, when the file was getting too long, I created a file-2.php file and put some functions there, my plan is to organise the plugin into several logical files, but the plugin could not process the functions in file-2.php, untill I `include("file-2.php")` in file-1.php, which is more or less having one long file-1.php
I thought plugins would be able to read functions from any file without the _include_ directive.
Does the plugin info written in the first file gives it special privilege/priority? | Plugins, like any other functions file in a theme are just extensions to your theme's functions.php file. Any file that extends the main functions.php has to be manually included into the main functions file. The reason for this is, only files and templates within Wordpress file structure gets auto laoded. There is no logic to regocnize and to include custom files or templates
The main plugin file of a plugin however is autoloaded and need not to be manually included, although it is just an extension to the main functions.php file of your theme. A plugin is identified by the header of the main plugin file, and it is this header that wordpress uses to identify the plugin and according to that auto loads the main plugin file.
Again, Wordpress only loads the main plugin file as it only knows this file. Any extension to the main plugin file is ignored as Wordpress don't recognize it. To get Wordpress to load any other files, you need to include them into the main plugin file | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development"
} |
Is it a good practice to disable wpautop for premium themes?
I am Developing a WordPress Theme which have some shortcodes to display content.
The problem I am having is, extra p elements are being added within shortcodes.
I can disable wpautop with filter, which fixes this issue but I am curious if its a good practice to disabe this default feature of wordpress.
Also, Is there any way to fix formatting with disabling wpautop ?
Thanks | I would say no, its bad practice to disable it.
The simple truth is disabling wpautop pretty much breaks the line spacing in the visual editor, and if your clients are going to want to use the visual editor, which most of them do.
> Also, Is there any way to fix formatting with disabling wpautop ?
Here is a good related post that might help: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, wp autop"
} |
get_post_types not working properly in admin
I'm trying to get all post types (custom & built_in) but it's only gives me only built_in ones in admin. I can get all of them in root (5 with builtins included) but in admin, i can only get 3.
I throught need a trigger an action or something but i couldn't find it.
$post_types = get_post_types( array( 'public' => true ), 'name' );
var_dump($post_types);
More info: I'll use it in reduxframework's config page (in "setSection" function).
PS: I don't want to get post_types with sql query, because i need empty post_types too.
Edit: it is not about just admin.
For reduxframework developers; you can't use any function which uses the `init` action flag. For reference: < | `register_post_type` is recommended to be used in `init` action hook. So, `get_post_types` should be used in an action after `init`. Hooking in `init` with a very high priority, 999 or greater, should also work in almost every situation but it is safer to use a later action hook.
Example:
add_action('wp_loaded', function(){
$post_types = get_post_types( array( 'public' => true ), 'names' );
var_dump($post_types);
});
In admin section you can use `admin_init`, which run after `init`:
add_action('admin_init', function(){
$post_types = get_post_types( array( 'public' => true ), 'names' );
var_dump($post_types);
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, admin, post type"
} |
How to auto add nofollow to links in custom field?
I have a custom field that contains links in them and I want to auto add nofollow to those links in that custom field only. How can I do this?
Example custom field value:
<a href="
I found a tutorial that auto adds nofollow to externals link < but it only applies to post content and not custom field. Anyone know a way to make it work with custom fields? | This is something you cannot change in the field it self, but in the template file. Copy and paste here the template file where this option is outputted.
Another way will be to add a javascript snippet to you `head`, if you have such option in you template.
Comment here and we'll see what the best solution is.
Update:
I think best solution for you is to use 2 different custom fields - one for the url (call it Links, but put only the url and not the full html link) and one for the link title (call it Links_title, and put just the text you want to be linked). Then put this code in your template to output it:
<a href="<?php echo( get_post_meta( $post->ID, "Links", true ) ); ?>" title=" <?php echo( get_post_meta( $post->ID, "Links_title", true ) ); ?>" rel="nofollow">
<?php echo( get_post_meta( $post->ID, "Links_title", true ) ); ?>
</a> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, custom field, links"
} |
How to avoid repeating similar properties for all tds of a table in a wordpress post
Consider the following table.
<table>
<tbody>
<tr>
<td style="text-align: right; direction: ltr;">1</td>
<td style="text-align: right; direction: ltr;">2</td>
<td style="text-align: right; direction: ltr;">3</td>
.
.
.
</tr>
<tr>
<td style="text-align: right; direction: ltr;">1</td>
<td style="text-align: right; direction: ltr;">2</td>
<td style="text-align: right; direction: ltr;">3</td>
.
.
.
</tr>
</tbody>
</table>
What can I do to avoid repeating the same properties for the all the tds. Is it possible to do so without using the css file? The problem I am facing is, in a wordpress post, one cannot use the `<head> or <style>` tags. | > ...there's no way to include the style in Wordpress posts, at all?
You need to add the `style` tag to the list of allowed post tags, and also ensure TinyMCE recognises it in the editor:
function wpse_180472_wp_kses_allowed_html( $tags, $context ) {
if ( $context === 'post' )
$tags['style'] = array();
return $tags;
}
add_filter( 'wp_kses_allowed_html', 'wpse_180472_wp_kses_allowed_html', 10, 2 );
function wpse_180472_tiny_mce_before_init( $init ) {
if ( isset( $init['extended_valid_elements'] ) )
$init['extended_valid_elements'] .= ',style';
else
$init['extended_valid_elements'] = 'style';
return $init;
}
add_filter( 'tiny_mce_before_init', 'wpse_180472_tiny_mce_before_init' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, html, table"
} |
Do rewrites added with add_rewrite_rule() persist after plugin deletion?
I am developing a Wordpress plugin and need to ad a rewrite url using `add_rewrite_rule()`.
That does work. But what happens when my plugin is deleted? Does Wordpress cleanup the htaccess or do I need to do that? How can I remove a url which was added using `add_rewrite_rule()`? | Let me say beforehand that when using `add_rewrite_rule()` nothing is written to the htaccess file. Rewrite rules are stored in the database and handled by WordPress internally on PHP level.
**TL;DR:** Rewrite rules do persist after plugin deletion, but probably not the way you'd expect it.
When using `add_rewrite_rule` these rules are added in the options table in the database. You then need to flush the rewrite rules via `flush_rewrite_rules()` (Visiting Settings > Permalinks and saving does the same) for them to come in effect.
Similarly when you remove your plugin that added the rewrite rules they stay in effect until the next flushing of the rewrite rules. So yes they persist, but they will disappear at some random point later on when the rewrite rules are flushed. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, url rewriting, htaccess, rewrite rules"
} |
How do I get the URL of a specific size featured image?
I am using `<?php wp_get_attachment_thumb_url( $attachment_id ); ?>` to get the url of a thumbnail for a post in Wordpress. However I would like to retrieve the URL of a specific size image. So for example when displaying the post thunmbnail normally you can specify a size, like: `<?php the_post_thumbnail( $size, $attr ); ?>`. Is it possible to do the same with wp_get_attachment_thumb_url.
Something like: `<?php wp_get_attachment_thumb_url( $attachment_id, $size ); ?>`? | You want `wp_get_attachment_image_src()`:
if ( $src = wp_get_attachment_image_src( $attachment_id, $size ) ) {
echo $src[0]; // URL
echo $src[1]; // Width
echo $src[2]; // Height
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 4,
"tags": "templates, post thumbnails, images"
} |
WooCommerce-like featured gallery
I want to create a gallery similar to what WooCommerce does using multiple "featured image"(s). I have searched and searched, but i cant seem to find any solution to this (not even a thread covering it).
I know how to use featured images in a post-type, but it can only have 1 value.
Can it look like WooCommerce featured gallery as well? (looking like the native featured image box) so that the user dont have to click "Add new field" for each image, but can simply open the media modal and mark the images he want to use? - again similar to WooCommerce's featured gallery.
Thanks. | I found a solution to this.
I am using the plugin (No UI) Metabox that has this feature by default.
This is the code i used to achieve my desired result:
add_filter( 'rwmb_meta_boxes', 'prefix_register_meta_boxes' );
function prefix_register_meta_boxes( $meta_boxes )
{
$prefix = 'rw_';
$meta_boxes[] = array(
'title' => 'Media',
'pages' => array( 'bestilling'),
'fields' => array(
array(
'name' => 'URL',
'id' => $prefix . 'url',
'type' => 'file_advanced',
),
)
);
return $meta_boxes;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "images, gallery"
} |
How do I change the scan depth for page template files?
I want to move my template files to a file sub-directory like `./tpl/page` but it seems to only scan one directory deep. Is there a way in my theme that I can set it to scan deeper? | Nope. Unortunatly 1 directory depth is hardcoded as second argument for `get_files` method in method `WP_Theme -> get_page_templates`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "themes, page template"
} |
Pagination re-direct to main page
This is a general question regarding pagination.
I have posts on the main page, but the pagination is redirected to main page.
For example, site.com/page/2 goes to site.com.
Is there a general setting in the backened which I can fix the redirect?
(otherwise, I am guessing it is from plugin setting).
Thanks | Generally, the static front page is not supposed to be paginated.
Can you fix it? Yes you can!
Take a look at those resources for a start:
* Codex: Pagination - static front page
* How to fix pagination for custom loops?
Much more information about this topic is available, if you search for it. Good luck! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pagination"
} |
Including 2 Negative Is_Template Conditionals in header.php
I want to set a conditional in `header.php` to wrap all of my templates, except `front-page.php` and `single-device.php`, in a bootstrap container element.
Writing one conditional achives what I want
if( !is_singular('device') ) {
echo '<div class="container">';
}
However, when including two conditionals, only the first conditional applies.
if( !is_singular('device') || !is_front_page() ) {
echo '<div class="container">';
}
Is the logic incorrect? | _(Expanding on Pieter's comment above, and explaining the logic behind it...)_
`if()` evaluates the conditions in the parentheses, and that evaluation results in either `TRUE` or `FALSE` for the sum total (which can change, depending on how the various conditions are combined).
In plain English, `if( !is_singular('device') || !is_front_page() )` means, "If it's _either_ true that this is not a single Device post, _or_ true that this is not the front page, then..."
Since a URL on a WordPress site isn't going to both be the front page and a single post (unless you've gone out of your way to configure it as such, I suppose), you probably want to use `&&` instead: `if( !is_singular('device') && !is_front_page() ){}`
In plain English, the latter `if` statement means, "If it's _both_ true that this is not a single Device post, _and_ true that this is not the front page, then..." | stackexchange-wordpress | {
"answer_score": -2,
"question_score": -1,
"tags": "templates, conditional tags"
} |
How can I display a specific number of post in a category via a url
I'm trying to link to a specific category in my blog but limit the number of posts that are listed.
I can link to the specific category via "www.example.com/?cat=6" and after looking around the web (wordpress.org and this site) I thought I could just limit the number of posts with "www.example.com/?cat=6&showposts=5" but...
"&showposts=5" isn't returning the results that I'm expecting, am I using "showposts" correctly? Is there something better?
If not how can I build my url to only show a specific number of posts?
While I have access to the theme and the loop, I would prefer not to edit that and not install some plugin, my feed is perfect, I'd just like to build a link for this one type of use case. | `showposts` is an alias of `posts_per_page`, which is a private query var, meaning it can't be set from the query string. You could register your own query var and map that to `posts_per_page` in a `pre_get_posts` action. This could go in your theme's `functions.php` and would work for any main query.
// add a new query var to the list of known query vars
function wpd_custom_posts_queryvar( $vars ){
$vars[] = 'wpd-num';
return $vars;
}
add_filter( 'query_vars', 'wpd_custom_posts_queryvar' );
// hook pre_get_posts and set posts_per_page
// if it's the main query and our custom query var is set
function wpd_custom_posts_number( $query ){
if( $query->is_main_query() && $query->get( 'wpd-num' ) ){
$query->set( 'posts_per_page', $query->get( 'wpd-num' ) );
}
}
add_action( 'pre_get_posts', 'wpd_custom_posts_number' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, wp query, categories, urls, variables"
} |
Using category slug in add_rewrite rule
I'm using this function ro rewrite URLs:
function archive_rewrite_rules(){
add_rewrite_rule(
'inspiracao/([^/]*)/([0-9]{4})/?$',
'index.php?post_type=post&cat=$matches[1]&year=$matches[2]',
'top'
);
}
add_action( 'init', 'archive_rewrite_rules' );
But is possible to use category slug instead category id? | You should be able to use
category_name=$matches[1]
instead of
cat=$matches[1]
Generally speaking, you can use any built-in public query variable and custom ones, after some additional work, see the `add_rewrite_rule()` codex entry for more information. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "url rewriting, actions, rewrite rules"
} |
Parsing session info between WordPress and non-WordPress
I have a Web App that resides in example.com (non-WordPress, completely independent databases, etc) and I have a WordPress website, website.example.com and example.com/website.
Users will never log into WordPress, but they will access the WordPress website, then log into the Web App.
The Web App stores sessions and on the Web App pages I display this to show that the user is logged in:
echo “<a href='#' class='dropdown-toggle' data-toggle='dropdown'>
Welcome, ".$_SESSION['full_name']." !</a>”;
How can I show this in WordPress if they change pages to the WordPress website? | Use javascript, loading from your app - example.com and save the relevant info in cookie. Then on the WordPress, again using javascript, loading from your app (this is important to be able to read cookie) to read value of that cookie and update the page accordingly. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "session"
} |
Changing the code format for wordpress
So I have the following code:
global $userpro;
$output .= '<div class="mainpageauthor">';
$output .= '<a href="'.$userpro->permalink($post->post_author).'">'.get_the_author_meta('display_name',$post->post_author).'</a>';
$output .= '</div>';
How would I change it to html php format? (I am not sure if I am asking it correctly). For example, I tried to change it but I am not sure if it is correct:
<div class="myrelatedauthor">
<a href="<?php $userpro->permalink($post->post_author); ?>"><?php echo get_the_author_meta('display_name', $post->post_author);?></a>
</div>
Did I do it right?
Thanks | First thing's first, we need to get our globals. If you're in The Loop you can remove the `global $post` in my code, if you're outside The Loop `$post` may not be what you expect it to be. We'll always need the `global $userpro` though.
<?php
global $userpro,
$post;
?>
<div class="myrelatedauthor">
<a href="<?php echo $userpro->permalink( $post->post_author ); ?>">
<?php echo get_the_author_meta( 'display_name', $post->post_author );?>
</a>
</div>
The key differences between your code and my code is that I include `global $post` and `global $userpro`. I also `echo` out the value returned from from `$userpro->permalink()`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "formatting"
} |
CTP - check for value inside objects
I have registered a CTP which can add a new plant and user can tick which months it can be planted (february, march and april for example). Now, I need to display it on the page but with all months listed starting from the first one. For example january: no, february: yes, march: yes, april: yes.. december: no.
The problem I am facing is that with `get_the_terms` i get an array with many objects, and I am not sure how to check if value (in any of the objects) is equal to the name of the month.
$months = array('january', 'february', 'march'....);
$terms = get_the_terms( $post->ID , 'myctp' );
foreach($months as $month) {
foreach($terms as $term){
if($month== $term->slug)
echo 'yes';
else
echo 'no';
}
}
This doesn't work good because of the nested foreach loop, it will double/triple... data for each month if more terms are present. | There's no need for two loops. Just iterate over the terms and use `in_array()`:
foreach ( $terms as $term ) {
if ( in_array( $term->slug, $months ) {
echo 'yes';
else
echo 'no';
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "terms"
} |
Unrestricted height thumbnails
I have set my default thumbnail size in settings > media, however as I see it you _Have_ to add a value. However, I'd like to specify a width, but allow for an unrestricted height. For instance, both these dimensions would be alright:
w: 120px h: 70px
w: 120px h: 240px
Doesn't Wordpress allow this behaviour? Or should we simply set the height value to a ridiculously high number? | According to `add_image_size()` you can do something like that with `width` but I imagine it works the same with `height`:
> **$width**
>
> (int) (optional) The post thumbnail width in pixels. **Set to 9999** to resize based on $height Default: 0
Really I think you would want to set it to something ridiculously high which 9999 should work for you. You could test this and use a plugin like Regenerate Thumbnails to try it out or revert your changes if it doesn't work. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post thumbnails, images"
} |
Parse error thrown by get_post_meta
in a custom plugin I am developing, I am getting this error as soon as I activate the plugin:
Parse error: syntax error, unexpected '[' in /home/site/public_html/wp-content/plugins/my_plugin/plugin.php on line 106
I have hunted down the exact line throwing the fatal error:
$gallery_pictures_id = get_post_meta( $product_id, '_product_image_gallery')[0];
It's worth noting that this line works both in local development and on a staging server.
Why is this happening? What is so weird about it? | This is known as array dereferencing and is only available in PHP 5.4+
To support older versions, you need to assign the array, and then access the index:
$data = get_post_meta( $product_id, '_product_image_gallery' );
$gallery_pictures_id = $data[0];
Having said that, in your case use the third argument "single":
$gallery_pictures_id = get_post_meta( $product_id, '_product_image_gallery', true ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": -1,
"tags": "post meta"
} |
Trying to get property of non-object in shortocde
I'm having error in shortcode that "Trying to get property of non-object" on line no 130
Here is code:
while ( $our_work->have_posts() ) { $our_work->the_post();
$termsArray = get_the_terms( $post->ID, "filter" ); //This is the line I'm getting error. which is line no 130.
$termsString = ""; //initialize the string that will contain the terms
foreach ( $termsArray as $term ) { // for each term
$termsString .= $term->slug.' '; //create a string that has all the slugs
}
........(content is here)
}
wp_reset_postdata();
filter is custom taxonomy. And I'm using isotope jquery plugin which is working fine in page but giving this error in shortcode. I dont know why this is giving error. Please help.Thanks. | You need to call `global $post` before using `$post->ID`, or better, use `get_the_ID()` instead. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "loop, filters, shortcode, taxonomy, array"
} |
Wordpress wp_get_attachment_thumb_url full
My code in index: (show all attachment by one post ID)
<?php query_posts('p=1498'); if (have_posts()) { while (have_posts()) { the_post(); ?>
<?php $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'orderby' => 'rand', 'post_mime_type' => 'image' ,'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) { ?>
<img src="<?php echo wp_get_attachment_thumb_url( $attachment->ID, $size = 'full' )?>" alt="<?php echo get_post_meta($attachment->ID, '_wp_attachment_image_alt', true) ?>" />
<?php }} ?>
<?php }} wp_reset_query(); ?>
but image src show it's: `thumbnail: ?
How to show image full as: `
Thanks | Try this in the foreach loop:
$thumb_url = wp_get_attachment_image_src( $attachment->ID, 'full' );
And this for the img src:
echo $thumb_url[0]; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "query posts, post thumbnails, attachments"
} |
Wordpress multisite, allow non super admins to create sites
I'm creating a wordpress multisite for at costumer to uses with his own customers. He need to be able to create a site when he get a new customer, and his customer should be able to control the the site.
So I want me as an superadmin, and my customer's customers to be the admin the site, so what I need is a role in between a light version of the superadmin.
I can't figure this out, i have tried different plugins fx: "User Role Editor", but no luck so fare.
Someone now how to make this work? | So I finally found the solution. If installed the: "Extended Super Admins" plugin.
And then I the user the Super Admin role, and used the plugin to add a custom role based on the super admin and then it is just check the boxed of the rights he **DON'T** need to have.
It was really that simple! | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "multisite, admin, user roles, multisite user management"
} |
How to get a page url by a page id?
I tried to use get_page_link('page-id') and get_permalink('page-id') but the error below occurred.
> **Fatal error:** Call to a member function get_page_permastruct() on null in ...
How can I get a page url knowing only its ID? | You're probably getting that error because WordPress doesn't have the $wp_rewrite global loaded yet for some reason. Either something deactivated it, or you're trying to run those functions before WordPress has a chance to load it.
If you're trying to do this in a plugin or in your theme's functions.php file, make sure you're inside a function that is hooked to after_setup_theme or a hook that runs sometime after. For example:
function get_url_of_page_id_165() {
return get_permalink( 165 );
}
add_action( 'after_setup_theme', 'get_url_of_page_id_165' ); | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 3,
"tags": "permalinks, pages, links, wp link pages"
} |
Rendering css to screen and debug problem
i got a website here that i am building up HERE
the right arrow, in chrome, is LOW as you can see here
but when i debug it with the debugger and check float on/off, it comeback to the place it should be...
so the question is, what is the problem ? the CSS, the browser, the debugger the system (mac?) or HTML... if need your light !... thanks in advance | Its an old bug in Chrome.
In order to solve your problem though - you just need to add this CSS (append to the one you already have in place):
.fleche {
float: none !important;
vertical-align: top;
}
With inline-blocks - you don't need floats to keep them on the same line. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "css, debug"
} |
200 return code on 'POST /wp-admin/admin-ajax.php' while NOT logged in
I noticed the following log entry:
111.22.3.444 - - [13/Mar/2015:08:31:00 +0100] "POST /wp-admin/admin-ajax.php HTTP/1.1" 200 618 " "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36"
It is my company website and guaranteed that nobody (including me) was logged in, or using the dashboard. Shouldn't a /wp-admin/.. POST return a 404 or 403 instead of a 200?
Any tips are welcome!
Kind regards,
Gerard. | `wp-admin/admin-ajax.php` is the script used by any plugin or theme using WP Ajax API and Ajax actions can be registered for non-logged in users. For example:
//For logged in users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
//For non-logged in users
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
There is no problem on that. See WP Ajax documentation for more information. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "ajax, security"
} |
Add field to 'Add User' admin page
How can I add an input field to the admin section Users -> Add New?
I want to add a field for a phone number, but don't want a plugin to do that. | Okay found the answer by poking around the code
A field can be added by doing the following:
add_action('user_new_form','myplugin_add_field');
function myplugin_add_field() {
// code to add field
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom field, wp admin"
} |
Embeding style into the header via the function.php
I'm trying to add the following hook into my functions.php file. The CSS style shows up when I view the source code but it also show the php code for the random background image generator. How can I get the php in that line to work within the hook?
Thanks
add_action('wp_head','hook_css');
function hook_css()
{
$output="
<style>
body {
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% 100%;
background: url('../images/backgrounds/bg<?php echo rand(1,4)?>.jpg') no-repeat top center;
}
</style>";
echo $output;
} | You are not escaping your PHP correctly. In this part `$output="... <?php` You could instead do it like this:
add_action('wp_head','hook_css');
function hook_css()
{
?> <!-- Closing the PHP here -->
<style>
body {
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% 100%;
background: url('../images/backgrounds/bg<?php echo rand(1,4); ?>.jpg') no-repeat top center;
}
</style>
<?php //Opening the PHP tag again
}
Or if you prefer to have it the way you do with the `$output` variable - Make sure to escape correctly around your rand() function. Like this: `...backgrounds/bg". rand(1,4) .".jpg` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "hooks"
} |
list posts from two categories on a page - plugin not working
I've installed this plugin: <
i've tried using the suggested code to list post which are in 2 categories:
[catlist id=64+60]
but I don't get anything listed :(
if I do
[catlist id=64]
or
[catlist id=60]
I see the lists of the things in each category but i want to show ONLY the things in BOTH categories
I'm using the shortcode on a page and trying to call a list of other pages (not posts) which have been categorized using the "Post Tags and Categories for Pages" plugin
am I doing something wrong? or is there any reason why this should not work for pages?
I event tried reverting to the 2014 theme but it still didn't work :(
any ideas? | I think the reason this is not working is because you're trying to combine two plugins that don't work well together. Probably the List Category Posts plugin doesn't have support for page categories.
You have two options now, explain what you're trying to do (I don't understand why you can use posts and categories) and maybe we can give you a better solution, or implement code which will return your pages from the categories you want. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, categories"
} |
How to work email subscribe in WordPress?
There are many website those are using new WordPress theme as email subscribe option, like the below image
<
and I wish I will add this subscribe option in my theme.I have styling idea but I haven't any WordPress functional idea how to working the subscribe option. I searched google but didn't got any information about it.
So I need informational article on it. | There are many WordPress plugins that let you manage your email subscription. But overall this is not recommended, mainly because it creates a **heavy load** on the server. What will inevitably create a problem with the hosting service.
In my experience, it is advisable to work with professional external services. For various reasons among which I highlight:
* They make sending mail (high load)
* They have good design tools
* They know a lot about how to make your mails do not fall as SPAM
These services have different forms of design that attach easily with WordPress themes. An example is **Mailchimp.com**. But there are others.
This article can help you with more information. I hope you find it useful.
WPBeginner - Why You Should Never Use WordPress to Send Newsletter Emails | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugins, theme development, themes, email"
} |
Remove built in wordpress login and use only google auth
I am using Google apps login plugin. I would like to keep this only as a login mechanism and remove the built in: **username/password** that appears below it.
How can I disable the wordpress built in authentication mechanism? by disable i mean disallow any manual forging of its login url request too. | To remove WP native username/password authentication use the code below. It can be added to the theme (functions.php), to a plugin, or mu-plugin. Just make sure you have another authentication module working before you disable WP native auth.
` remove_filter('authenticate', 'wp_authenticate_username_password', 20, 3); ` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "login, wp login form"
} |
Calling specific page with wp query
I'm making one page website and I added a custom field on "Page" post type that asks "Use this page as a section:" Yes or No(with dropdown). I called all pages on template-onepage.php(custom template) using wp query
<?php $args = array(
'post_type' => 'pages',
'order' => 'ASC'
);
$the_query = new WP_Query($args);
?>
<?php if (have_posts()) : while (the_query->have_posts()): the_query->the_posts ?>
<?php some content here ?>
<?php endwhile; endif; ?>
Now what I want is to call only those page that set "Use this page as a section" to yes.. How can I achieve it ??? Please help.. Thanks | You need to add a meta query, which will specifically select those posts that have both the meta key you want, and the desired value.
$args = array(
'post_type' => 'pages',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'use-this-page-as-a-section', // or whatever the key is
'value' => 'yes'
)
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, posts, wp query, custom field"
} |
Adding custom column to comments admin panel?
How do I add a new custom column to wordpress wp-admin/edit-comments.php page ? I tried this but did not work.
add_filter( 'manage_comments_custom_column', 'add_new_columns' );
function add_new_columns($columns){
$column_meta = array( 'reported' => 'Reported' );
$columns = array_slice( $columns, 0, 4, true ) + $column_meta + array_slice( $columns, 6, NULL, true );
return $columns;
} | The filter you're looking for is `manage_edit-comments_columns`. Here is a post detailing how to add custom columns to the edit comments section of the admin < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "filters, comments"
} |
set admin bar to visible for authors, contributors, moderators and admins
Is there any way that I can set the Toolbar visible to authors, editors and admins and off to everyone else? | Checking the capability of the users you can determine whether to show or not the admin bar.
add_action( 'after_setup_theme', 'remove_admin_bar' );
function remove_admin_bar() {
if( ! current_user_can( 'administrator' ) || ! current_user_can( 'editor' ) || ! current_user_can( 'author' ) ) {
show_admin_bar(false);
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "admin bar"
} |
Adding hero images to blog posts
I'm having some trouble finding the solution for my problem stated in the title. To describe it more clearly, then I would like to add some kind of functionality to the wordpress post section in the admin panel, where my boss or other co-workers can add both a thumbnail image for the listing of blog posts, but also a unique header image for that given post, when you click to the full post it should show the added header image for that given post. Is that possible and how? :)
Cheers! | You can use the Advanced Custom Fields plugin for that. Beside that, ACF provides you more field types you can use. And instead of showing the featured image in single.php, you can echo the one uploaded in your additional field. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "plugins, images, admin"
} |
Which template name to use for taxonomies but not their terms?
I can't figure out which template name to use to modify custom taxonomy archive page, but not the one for terms in that taxonomy.
My goal is to show terms list in custom taxonomy archive and in custom taxonomy terms - custom post types..
`{taxonomy}-{term}.php` is used to display custom taxonomy terms ( so there will be custom post types inside ) but i need so there would be terms list inside.
Hope my question in clear.
## Edit:
Just found out that I can't open that kind of page in wordpress at all.. So now question is how to make such page?
For ex. I have ct - `device`. So `/device/iphone` will show all posts in `iphone` term, but `/device/` should show all terms in device tax.
My problem is that `/device/` is readed as page slug, not tax in wordpress by default.
How to change that? | There is no such hierarchy in Wordpress, accessing a custom taxonomy directly simply `404`. This works for all taxonomies, build-in or not. There is unfortuantely no other work around to this but to create a page
You should create a custom page template with a custom query to list your taxonomy terms, something like the following
* Create a page template called `page-device.php`
* Use `get_terms()` to create your list, something like this: ( _Extend as needed, taken from the`get_terms()` page_)
$terms = get_terms( 'device' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<ul>';
foreach ( $terms as $term ) {
echo '<li>' . $term->name . '</li>';
}
echo '</ul>';
}
* Create a page in the back-end with slug `device`
Now, if you visit `mysite.com/device/`, you will see this page showing up with all your terms in the taxonomy `device` | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "custom taxonomy, templates, template hierarchy"
} |
Hide a certain category name without removing it?
I have a category called `feature` which I use to have a feature post in the homepage. The problem is I don't want the category name `feature` to appear in this posts, but I want the other categories to show up.
How could I do that? | To achieve this we need to use `get_the_category` here. I am going to use this code in several places, so it is more efficient to create a function
function exclude_cats($excludedcats = array()){
$categories = get_the_category();
$separator = ', ';
$output = '';
foreach($categories as $category) {
if ( !in_array($category->cat_ID, $excludedcats) ) {
$output .= 'term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.''.$separator;
}
}
echo trim($output, $separator);
}
All that I've done inside the function was to call `get_the_category` function, But I've excluded the categories I don't want to show their names to not show.
inside the index I've called the function like so `exclude_cats(array(11, 40, 53));` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "categories"
} |
How to get image extension from wp image editor object?
`get_extension` seems to be a protected method dunno why, seems to me there is no way to get file extension using image editor object... I know I can use `getimagesize` with php and be done with it but that would mean fetching the image a second time which would be nice to avoid | I tried using `generate_filename` yesterday but probably it was kind of late and I was trying and didnt manage to make it work, today I managed to workaround the problem without fetching the image another time like this:
$save_path = WP_CONTENT_DIR . '/tmp/' . $img_name . "-" . $nw . "x" . $nh;
$wp_img->save($save_path);
$img_name = basename($wp_img->generate_filename('suffix'));
$img_name = str_replace('-suffix', '', $img_name);
$img_url = content_url() . '/tmp/' . $img_name;
$filepath = WP_CONTENT_DIR . '/tmp/' . $img_name;
As you can see a suffix must be specified because currently the method adds a default suffix as the image size by default, and to retrieve the correct image filename + extension it must be removed afterwards. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "images"
} |
Enqueuing scripts and styles in custom plugins
I have a couple of questions regarding enqueuing scripts and styles in custom plugin code.
I've recently come across plugin code where scripts were enqueued hooing into the `template_redirect` action hook while scripts were enqueued using the `ss_css` (I guess this is a custom action) and `login_enqueue_scripts` action hooks.
My question, therefore, is:
What is the most appropriate hook to enqueue JS scripts and styles. Is it `wp_enqueue_scripts` as is the case in themes? Or should it be more purpose specific as in the scenario described above? In short, should enqueuing scripts and styles in plugins be governed by different rules? | Straight outta the Codex:
> `wp_enqueue_scripts` is the proper hook to use when enqueuing items that are meant to appear on the front end. Despite the name, it is used for enqueuing both scripts and styles.
So the simple answer to your question is yes, `wp_enqueue_scripts` is always the correct action for enqueuing scripts AND styles. This is so other themes/plugins can modify previously-enqueued files or other plugins (e.g. a minifier) can assume that all scripts/styles are loaded with that hook. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, wp enqueue script, wp enqueue style"
} |
Query post category & remove any post id
I have category_id=3 and have 10 post in category_id=3 with post_id= 1=>10
How to show list post category_id=3 with no post_id=1,3,5 value as
query_posts('cat=3& -p=1,3,5 &showposts=30 | If you are trying to omit posts 1,3,5 from category 3 on your blog, you can use the following code
$query = new WP_Query( array('cat' => 3, 'post_type' => 'post', 'post__not_in' => array(1,3,5) ) );
The query results will not show posts with ids 1,3,5 of category 3. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, categories, query, query posts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.