INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Trying to get property of non-object error with thumbnail
I'm trying to get the thumbnail of my featured image to display on my home.php (blog) page.
It is displaying fine, but when debugging mode is turned on, I get this error:
> Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/wpflat/wp-content/themes/wpflat/content-blog.php on line 2
My code is
<a href="<?php the_permalink();?>"><?php echo get_the_post_thumbnail($page->id, 'thumbnail'); ?></a>
How do I solve this issue? | I believe from your error that you are using this code inside the loop. You should be using `the_post_thumbnail()`. The code you are using is used outside the loop.
**EDIT**
It is always good practice to always first check if you have a thumbnail to display
So you should use
<?php if(has_post_thumbnail()): ?>
<a href="<?php the_permalink();?>">
<?php the_post_thumbnail( 'thumbnail'); ?>
</a>
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "errors"
} |
echo vs output variable
Someone once told me, that it is good for performance, not to open and close php tags and use echo all the time, like that:
<hgroup>
<h1><?php echo getHeading1(); ?></h1>
<h2><?php echo getHeading2(); ?></h2>
</hgroup>
Instead he uses an output variable and echoes it in the end.
$output .= '<hgroup>
<h1>' . getHeading1(); . '</h1>
<h2>' . getHeading2(); . '</h2>
</hgroup>';
echo $output;
Does that really make any difference? When do I use which method? | I believe this topic was addressed quite thoroughly here. I might add that within the WordPress community it is common syntax practice to default to echoing tags with an option or alternative/interior function to return the result instead. This I believe is driven by the level of code experience the average user within WordPress has and understanding a simple tag structure is "easier" than string concatenation of a php variable. The goal of extensibiltiy also drives this mentality by providing modular that can be "dropped" into a template in a similar vien of `add_action`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "php, optimization"
} |
Order posts by category name
Is there any way to order posts by category name?
I tried
$args = array(
'post_type' => 'dlm_download',
'posts_per_page' => 10,
'paged' => $paged,
'order_by'=> 'cat',
'order' => 'ASC'
);
But it does not really work, could please someone give me a hint? | I had the same struggle like you, thank i sat down and rethought the whole thing, what you actually need to is select all the categories, and pass the category id to it.
Since you use a dlm_download you will need to do the following, get the terms from the dlm_download_category
$cats = get_terms('dlm_download_category');
Loop trough the category and pass `query_posts` in it
so
foreach ($cats as $cat)
{
$args = array(
'post_type' => 'dlm_download',
'dlm_download_category' => $cat->slug,
);
query_posts($args);
if (have_posts()) :
while (have_posts()) : the_post();
// your stuff here
endwhile;
endif;
}
And there you go
PS: if you want to make it with `posts` not with `custom post`
Than `$cats = get_categories();`
and pass `'cat'` in to the argument.
Hope its clear and helps. Cheers | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "categories, order"
} |
Permission functions within wordpress
I'm currently developing a website and am exploring all possible options to restrict file viewing. I'm trying to find a way where I can load php files like my theme-options.php and cpt.php without them been displayed in the admin panel even to admin users e.g appearance > editor.
I'm leaning towards the answer having more to do with file permissions then any actually functions calling specific files and then providing restricted access to all users.
1.How can I restrict access to these files yet load them at the same time?
Thanks | The simplest way to hide them from the editor is to put them at least two directories deep. The editor only traverses one directory down when displaying files for editing. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, directory, permissions"
} |
How to optimize performance without transient?
I've built a widget to output some fancy content from an API. I realize today I added a transient system so everytime the widget is updated transient is deleted and everything is alright.
What I missed is that the generated content is actually different according URL. So my system is not appropriate, for now the content remains the same on each post.
How would you handle this? I think one transient per post is bad bad idea, isn't it?
I could delete the transient code but this increase page load. | I don't think a transient per post is a bad idea at all, and it's certainly more efficient than firing the API call on every load. Just be sure to give your transient name a unique name - maybe append the post ID to it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets, transient"
} |
comment files and s
I am building a custom template and would like to incorporate comments and replies using the standard WordPress core. What files and scripts do I need? I copied a comments.php file but the replies aren't working. Thanks for your help. | <
You can ignore the references to legacy stuff. That was posted 6 years ago, we're past the need for pre 2.7 support. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments, templates"
} |
delete_option() and update_option() returning false
I know that when `delete_option()` or `update_option()` fail to perform their respective database interactions, they return false. Does anyone know why they wouldn't be able to perform these actions?
It's only for specific options. Most options will work, however, a few options just seem to "die". They'll work fine for a while, then just stop working. Any ideas? | The `delete_option()` function will return false if the option does not exist.
The `update_option()` function will return false if the option already has the same value as what you're trying to update it to.
Both will also return false if the SQL query itself fails for whatever reason. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "database, options"
} |
WP FullCalendar Image Thumbs on Full Calendar
I’m trying to get WP FullCalendar to display the Event thumbnail in the associated cell on the Calendar. The #_EVENTIMAGE code works fine in the regular calendar, but when entering the shortcode into the "Event Title Format" under "Full Calendar Options" under General tab, the thumbnail just displays as the HTML and not the actual image.
Any help would be greatly appreciated | To display the Event thumbnail in the associated cell on the Calendar, we can do without using the 'WP FullCalendar' as follows.
1. First of all deactivate 'WP Full Calendar' (if already activated)
2. To add the formatting we want, go to Events > Settings > Formatting > Calendar and add this code:
3. #_EVENTIMAGE | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "calendar"
} |
Default Timezone setting in WordPress - is that global?
Despite the WordPress Options' Timezone setting for the whole WordPress installation, **is it necessary to declare the default timezone in all the date/time places in a WP theme/plugins?**
date_default_timezone_set('Asia/Dhaka');
echo date('d M Y - D - h:i A');
Suppose I'm handling with something where I'm checking whether the date&time is equals to **_TODAY_**. You know what "Today" means is a bit variable - variable to server time, variable to local time etc.
That's why I'm looking for a standard procedure to follow in WP projects, whether to set the default timezone each and every time (or do I call them always in the header?) or to avoid them as WordPress itself declared that already (just tune that before).
I'm just looking for a standard procedure - what to follow... | I think the safest way to handle it is to use the API to get the local time as set in WordPress settings-
$today = date( 'd M Y - D - h:i A', current_time( 'timestamp' ) );
EDIT- apparently `current_time` also accepts a PHP date string now as of version 3.9, so you can use that directly in place of `date`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "date time, timezones"
} |
Php conditional help needed
I am trying to add conditionals for authorship to show for posts on a specific author id. Would appreciate if someone could give the following a quick look over
<?php if is_author ('2') AND ( is_single() ) {?>
<link rel="author" href="
<?php }?> | This post is related to php so you should post it in stackoverflow but as you are a new user .i would help you
<?php if (is_author('2') && (is_single()) ) { ?>
<link rel="author" href="
<?php } ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, conditional content"
} |
Check whether attachment ID is associated with more than one post?
Is there a function to check whether an attachment ID (`=get_post_thumbnail_id(..)`) is associated with more than one post?
With "associated" I mean that a posts's meta value for the meta_key `_thumbnail_id` equals the attachment ID.
I know that `get_post_meta()` returns an empty array if it does not find anything, but I would have to somehow loop over all posts. | you can use following way
$attachment_id = 5; //put here you attachment id
$sql = "SELECT count(DISTINCT pm.post_id) FROM $wpdb->postmeta pm JOIN $wpdb->posts p ON (p.ID = pm.post_id) WHERE pm.meta_key = '_thumbnail_id' AND pm.meta_value = '$attachment_id' AND p.post_type = 'post' AND p.post_status = 'publish'";
$count = $wpdb->get_var($sql); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "attachments, meta query, post meta"
} |
store an array of all the terms existing
How can I store an array of all the terms existing? (for admin use)
$taxonomy = 'MYTAXONOMY';
$tax_terms = get_terms($taxonomy);
foreach ($tax_terms as $tax_term) {
echo $tax_term->slug ;
}
seems to only work from template files, but I would like to store this array in functions.php for using in a tinyMCE select box. | Not sure what the problem is, you're practically there! You can use your code anywhere (as long as it's after the `init` hook), not just in template files.
$terms = get_terms( 'MYTAXONOMY' );
$term_slugs = wp_list_pluck( $terms, 'slug' );
`wp_list_pluck()` is a very cool little function that will pluck a field out of an array of arrays/objects & return it as a single array:
print_r( $term_slugs ); // Array( 'slug_1', 'slug_2', ... ) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "terms"
} |
Split Media Queries in different files!
I woke up this morning with a thought. Is it a good idea to split the different media queries in different files, check the width of the page in functions.php and then with an IF call the "correct" using `wp_register_style` and `wp_enqueue_style`? | There are no functions in wordpress that checks or determine screen sizes. These are all browser related stuff that has got nothing to do with wordpress. There are jquery functions that can maybe work, but again, this is not wordpress related. `wp_is_mobile` can be used to load stuff conditionally for mobile phones, but then again, `wp_is_mobile` don't have the logic determining screen sizes, it also can't differentiate between things like mobile phones and tablets.
Your solution here is to do it old school, using media queries in your main stylesheet as done in all of the default themes shipped with wordpress.
Closing off, I would most probably think that if there was such functions to determine screen sizes in wordpress, that it would be completely overrated and useless and time wasting just to load something simple like a stylesheet | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, css, wp enqueue style, wp register style"
} |
echo variable containing html and the_permalink();
I'am trying to echo a vriable, but the permalink does not work as clickable button. The permalink just displayed outside the button.
Here is my code:
$perma = the_permalink();
$valid = '<button class="btn btn-success btn-wide" href="'.$perma.'">
Gegevens opgeslagen <span class="glyphicon glyphicon-ok"></span>
<a class="pull-right"><span class="label label-default">
<span class="glyphicon glyphicon-ok"></span></span></a></p>
</button>';
$id = get_the_ID();
if($id == '2440'){
if($current_user->google_play_gebruikersnaam != ""){
echo $valid;
} | You need to use `get_permalink()`, which will _return_ the URL as opposed to echo'ing it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, permalinks, html"
} |
Change the search results header from plugin
Hi I'm writing a plugin to include custom search results. I'm not really allowed to edit any theme pages, but the search results page in twentyfourteen's search.php seem hardcoded to me:
<header class="page-header">
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'twentyfourteen' ), get_search_query() ); ?></h1>
<?php if (function_exists("getGlossarySearchResults")) { echo getGlossarySearchResults(); } ?>
</header><!-- .page-header -->
I have to display the results before the normal search results. So is there any way modify the results output header from code? | No but I suggest you create a child theme, this will give you full control over the site without affecting the original theme... in there you can create a functions.php page and customize the search from there.
you can search for a child theme plugin that can create it for you, and some of them include editors... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, customization, search"
} |
"if parent category is" conditional?
I searched through the codex but couldn't find anything helpful. I tried the code below but it didn't work. The default sidebar still shows up for all category pages.
<?php
$ep_category = get_the_category();
if ($ep_category->category_parent == 'watch-isatv') {
include ('sidebar-isatv.php');
}
else {
get_sidebar();
}
?> | Your solution won't work, because `$ep_category->category_parent` is ID (integer) and not slug (string). So this comparison doesn't make any sense... ;)
One way to do this would be this function (from Codex):
if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
function post_is_in_descendant_category( $cats, $_post = null ) {
foreach ( (array) $cats as $cat ) {
// get_term_children() accepts integer ID only
$descendants = get_term_children( (int) $cat, 'category' );
if ( $descendants && in_category( $descendants, $_post ) )
return true;
}
return false;
}
}
After adding it to your theme, you can use it this way:
if ( in_category( 'watch-isatv' ) || post_is_in_descendant_category( 11 ) ) ... // where 11 is 'watch-isatv' category ID | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, conditional tags"
} |
media library not showing thumbnails after deleting full image
I am using a bit of code, that deletes the unneccessary full images after uploading and adding different sizes.
deleting function in functions.php:
add_filter( 'wp_generate_attachment_metadata', 'delete_fullsize_image' );
function delete_fullsize_image( $metadata )
{
$upload_dir = wp_upload_dir();
$full_image_path = trailingslashit( $upload_dir['basedir'] ) . $metadata['file'];
$deleted = unlink( $full_image_path );
return $metadata;
}
So, that works great, but the problem is I can not see any thumbnails in the media library anymore as they are generated by the full size image only, it seems. This makes it really complicated/hard to work with the uploaded images.
Is it somehow possible to "repair" this and and get those little thumbnails in the media library from another size (like medium, large or any custom named size)?
Thank you in advance, guys. | What is the need to remove the full size images? Are you dealing with storage space? If not, why give yourself the headache? Just let the full size images stay where they are. You don't have to use them. You'll probably find a situation where you want to use it anyways.
Also, I've never tried it, but you might be able to disable default image without deleting it by adding the following to your functions.php file:
update_option('full_size_w', '0');
update_option('full_size_h', '0');
You could also customize which image sizes display as an option in the editor as shown here. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "media, thumbnails, library"
} |
How To Get Search Term and Use in Function
I'm trying to write a function that will 'grab' the search term entered into the blog search form, and then hook the function to the `get_search_query` filter like this `add_filter('get_search_query','myFunction');` so that everytime a search is made, 'myFunction' runs and grabs the search term (or so I think), I have this line in myFunction to grab the search term
`$search_term = get_search_query();`
but it seems to be causing problem, the blog doesn't display, except I comment that particular line out. What is the right way to achieve the subject. Thanks.
Here is the code:
function myFunction(){
global $wpdb;
$search_term = get_search_query();
$table = $wpdb->prefix . "tableName";
$insert = "INSERT into $table(`serach_term`) VALUES ('$search_term')";
$wpdb->query($insert);
}
add_filter('get_search_query','myFunction'); | You're adding a filter to `get_search_query`, and within that function calling `get_search_query`, which runs your filter, which calls `get_search_query`, which runs your filter, which calls `get_search_query`, which runs your filter… do you see the problem here?
The search query is passed to the filter as an argument, so you don't need to fetch it-
function myFunction($search_term){
// now you can use $search_term directly in your code
}
add_filter('get_search_query','myFunction'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, hooks"
} |
Get the taxonomy of the post
How do I simply grab the taxonomy of a post using the post id? I have tried using the_terms and such but everything seems to require you know the taxonomy ahead of time. | > All I need is to find the taxonomy(ies) of post of a custom post type. It can output in any look or format and I can make it work
That being the case, what you need is `get_object_taxonomies()`
$taxonomies = get_object_taxonomies( 'post', 'objects' );
That will not give you the terms in the taxonomies. You will need to loop over `$taxonomies` and pull the terms out, if that is what you are trying to do. For example:
$taxonomies = get_object_taxonomies( 'post', 'objects' );
foreach ($taxonomies as $tax) {
var_dump(get_the_terms(1,$tax->name));
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom taxonomy, taxonomy"
} |
Shortcode / WP_Query in post changes context
We have a shortcode that causes WP_Query to be executed, retrieving an instance of a custom post type. In our single.php this changes the context (after the call to the_content()) from the original post (with the shortcode in it) to that of the custom post retrieved.
I spotted this because the comments template wasn't displaying, as the comment_status on the custom post is 'closed' - what we're interested in, however, is that the comment_status on the original post is 'open'.
Is this an error in the execution of our shortcode/custom post type, is there a way of doing this that won't mess up what happens in single.php?
Thanks,
Toby | You need to call `wp_reset_postdata()` after a secondary query to restore the global `$post` to its original context. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, wp query, shortcode"
} |
How can I manually upgrade translations?
I've recently upgraded a Wordpress site to the latest WP version (3.9). I also upgraded the themes and plug-ins that needed it.
Unfortunately, WP's automatic upgrade features are not compatible with the server this site is installed on, so I have to do it manually.
What bothers me is that I still have a red "1" on the Dashboard menu, telling me there's an update available. When I consult the details, everything is empty, except for the "Translations" section, at the bottom of the page.
How do I upgrade these manually? As I said, I can't just let WP do it automatically because it doesn't work.
I've checked the "languages" folder in "wp-content" and made sure it only contains the files from the new WP archive. I don't know where else to look.
Thanks in advance. | Sooo, apparently the problem was simply that I had forgotten to also upload the new `wp-content/languages` folder that came with the new WP version.
The official doc (at least in French) recommends _not_ to upload the `wp-content` folder during the upgrade process (because it contains all the personal files), which is why I had neglected that step.
Apparently, simply replacing the old `languages` folder with the new one is enough. WP now says that my translations are up to date. Problem solved. :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 8,
"tags": "updates, translation"
} |
Child Theme > Template
I incorrectly updated the Template variable in the style sheet of a Child theme. However, the site was still OK. The only indication I had was in the Admin section it said this theme did not exist.
So, my question is - is this variable actually used when rendering a page or is it just a hint for the control panel to notify the user? | That "Template" line... this one...
Template: twentyfourteen
... is a required field for child themes. That is what tells WordPress that this is a child and not a stand-alone theme, and also which theme to use as a parent. Files not replaced by the child theme are loaded from the parent.
Without that "Template" line you are bound to have problems but how many problems you have depends (I am speculating) on how much the child depends on the parent. If the child replaces only one or two parent files you may have a lot of trouble. If the child replaces nearly everything, you may not notice the problem. And of course a lot depends on which files are replaced and which should load from the parent.
Reference: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "child theme"
} |
Why is the generated POT file from WordPress.org not adding my plugin description to the POT file?
So I ran into this issue before and was able to get it fixed by using the get POT from the admin side of WordPress.org. However, with this plugin when I make the POT file it doesn't have the plugin description inside it. Any ideas why this would be happening?
The code for the plugin can be found here: <
You can see I added the Text Domain and Domain Path plugin headers as well.
Thanks for any help! | The makepot code being used on WordPress.org is a slightly older version that we have not updated yet, specifically with this fix: <
Basically, it's only looking in stripe.php for your main plugin lines, not searching for and then finding stripe-checkout.php.
This was fixed in the developer tools 7 weeks ago: <
But the change has not propagated to everywhere yet. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, localization"
} |
date_i18n() issue
I'm trying to use date_i18n() to display a localised date in my theme.
<?php echo date_i18n( 'F j, Y', strtotime( get_the_time( "Y-m-d" ) ) ); ?>
However, this always returns the English version of the month, rather than the French version. I'm using wordpress as a network. My primary site has the default WPLANG (so english), and I'm setting the second site to french by setting the WPLANG to fr_FR in site-settings.
Other translations on the page are working fine, so wordpress is aware that the language is different.
I downloaded the necessary .mo and .po files for French, but it doesn't have months in there, so I assume there's somewhere else these are set/used.
Any help would be appreciated as I've been stumped by this for hours. | `date_i18n()` gets month from `WP_Locale->get_month()`. Which in turn fills months using baseline translation function `__()`, nothing fancy.
Bottom line is — months _should_ be translated in po/mo files, you just got incomplete translation. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "theme development, multisite, multi language"
} |
Auto get_header and get_footer on every template?
Is there a way to automatically run `get_header()` at the beginning of template and `get_footer()` at the end of it?
Currently my code is too repetitive with those calls.
I've been looking for a way to do this, but I can't find it in Google. | Looking at `wp-includes/template-loader.php` … there seems to be a way:
if ( $template = apply_filters( 'template_include', $template ) )
include( $template );
You could hook into that filter, handle the including in a callback function and return `FALSE`.
Sample code, not tested:
add_filter( 'template_include', function( $template ) {
get_header();
include $template;
get_footer();
return FALSE;
}); | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 7,
"tags": "theme development, headers, footer"
} |
how to remove category from database
is there a way to remove the category from the database?
I just moving my old wordpress blog (that has the category in url), to new domain (without category).
I change everything except the category. Even i don't know where it is stored in database :(
## Update
**Problem is resolved, I added the answer below so that it will help to others.** | It is done through the following query:
delete from `wp_terms` where `term_id` in ( SELECT `term_id`
FROM `wp_term_taxonomy`
WHERE `taxonomy` = 'category' ) and `term_id` not like 1
This query deleted all the category except the default. Hope this helps to the others. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "categories, database"
} |
Static Text in Permalink
Can i have a static text in Permalink like this => /%post_id%/sometext/%postname%/
I tested this and works fine, but i am concerned whether it will bring some issues in future. So looking for some thoughts from people who have more experience in WordPress. | This is not a problem. Every `/` is already a static string. Avoid non-ASCII characters, dots (`.`) and `%`, restrict the string to lowercase letters a—z and _maybe_ numbers – but make sure the pagination rules do not conflict with it. A static string `/2/` might be read as page 2 by WordPress.
Besides that, you can use whatever you want. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "permalinks"
} |
Custom Post Type as invoice or order template
On homepage I would like to insert form that collects client details and saves it to wordpress backend.
I was thinking to use custom_post_type
register_post_type('invoices',
array(
'labels' => array(
'name' => __('Invoices'),
'singular_name' => __('Invoice')
),
'public' => true,
'has_archive' => false,
'supports' => array('title')
)
);
1. How I remove ability to publish? and view post / slug forms? This invoices won't be published on homepage. So is there a way to make `post_type` private? I thought `'public' => false` would do the trick, but this hides from dashboard.
2. I would like to add fields, like name/email/type of service. Is the only way to do this by adding add_meta_box?
3. How do I pass data from unauthenticated visitor on homepage to wordpress? | 1) To hide it from front, use following configuration in your register_post_type args
'exclude_from_search' => false,
'publicly_queryable' => false,
'show_in_nav_menus' => false,
2) If you look for a smoother approach, i would recommend using Advanced Custom Fields plugin
3) You can set up custom form and use wp_insert_post() | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom field"
} |
Can somebody explain this mediaelement and audio tags
I'm using this built in audio tag. It works for mp3 but with wma I just get this "Download file" link.
I read this: <
but setting type="audio/vma" does not fix the problem.
This is the link to some page that has the same problem as me: < | WMA isn't a standard format. It will only play natively in IE9 and up, and will only play in other browsers if they have Silverlight installed. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "media, audio"
} |
Restrict custom post type from appearing with ?post_types=
When appending the querystring post_types = "name of your post type", it displays all the posts. I am using a plugin that has its own custom post type which is restricted (only users that have purchased a membership can view it).. but today while messing around with searching, i discovered that post_types querystring. Is there a way to prevent this private custom type from showing up? are there other similar "magic" querystring in wordpress? | `register_post_type()` has quite a few related arguments, of which `publicly_queryable` controls precisely what you are describing.
However note that it will _completely_ kill the CPT on front end — individual posts, archives, even post previews.
If you want to do this conditionally you'll have to manage this with code from scratch, which might get very involved to do comprehensively. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, posts, security"
} |
Why is get_the_excerpt returning full content
I have my home page set to a static page with a custom page template. Here I want to show posts, but just the excerpts with a "Read more" link. I want to use the more tag, which is a part of wordpress so I hate the fact that this doesn't work! If I simplify the code that would be it:
while ( $q->have_posts() ) : $q->the_post();
$the_exc = get_the_excerpt();
echo $the_exc;
endwhile;
So how do I convince wordpress that on my home page I just want to show the excerpts (until the more tag). And this is like 75th time I'm dealing with this the_excerpt, the_content, issue. How do you guys do this? | Based on this...
> ... I just want to show the excerpts (until the more tag).
... it sounds like what you want is to show the post content up to the `<!--more-->` tag, rather than the excerpt proper which is hand-written into a special field. To do that, you need to use `the_content()`/`get_the_content()` rather than the `excerpt` cousin functions, and you need to have the `global` variable `$more` set correctly, but that is not hard to do.
$q = new WP_Query(array('post_type'=>'post'));
global $more;
while ( $q->have_posts() ) {
$q->the_post();
$more = 0;
$the_exc = get_the_content();
echo $the_exc;
}
The technique is explained in the Codex. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, the content, excerpt"
} |
GET Taxonomy ID
I have this line where "5" is the taxonomy ID.
`<?php echo function xyz (5,'product_cat'); ?>`
How can I change this to make it auto recognize always the taxonomy ID of the current page?
Tried with no success this:
`<?php echo function xyz (get_term_by('id','','product_cat);,'product_cat'); ?>`
How can I do this? Thanks. | If you're on a taxonomy term archive page, you can access the current ID via `get_queried_object_id()`:
echo function xyz( get_queried_object_id(), 'product_cat' );
You can also access the whole term object with `get_queried_object()`:
$this_term = get_queried_object();
echo $this_term->term_id;
echo $this_term->name;
echo $this_term->description;
echo $this_term->taxonomy;
echo $this_term->parent;
echo $this_term->count; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "taxonomy, terms, id"
} |
4th Network Site Database Errors?
4th site created but not available in the admin menu or the my sites screen.
So the my sites screen /wp-admin/my-sites.php only shows three, not the 4th.
The My Sites menu at the top also only shows 3, not the 4th.
If I click to My Sites>Network Admin>Sites then I see all 4 listed on this page wp-admin/network/sites.php and can acces the fourth site.
Why doesn't it show up in all the other menus? Can you help me find the root cause of the problem and fix it?
I had previously tried to delete the site, and then re-created the site, but the issue remains. I also turned off all plugins, but the issue remains. I'm afraid that there is a deeper problem which is perhaps database related. Can you help me solve it please? | Yeah, that was the problem. The site was configured with incorrect admin user information. The problem was solved by going to the user profiles and setting myself as a "super administrator" of the 4th site. Some how it had been created under a different user which was full of incorrect information. To make the site show up in your menu just go to "my sites" > "Sites" and you should see a list of all the sites.
On the right you can see which ones you are or are not listed as a user of. Find the ones that are missing your name, and hover your mouse over the "path" for that site on the left-hand side. You will see an edit button pop up, click it. On the new page you will see 4 tabs at the top, click "Users". From there you just add yourself as a user for the site as well (be sure to select your role as an "administrator". Then save. Your done, unless you want to remove an accidental user as well which is what I had to do, in which case edit their status however you see fit. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, database, errors, admin menu, network admin"
} |
Is there a real benefit in using wordpress optimized hosting?
I'm building a site for a client. This site often takes a long time to load initially, but is rather fast when loading the next page because of WP Super Cache plugin.
But still, the majority of people visiting a site for the first time will navigate away if the site doesn't load completely in < 3 seconds. So I'm having a bit of a problem here.
We are considering a new hoster. The budget is limited, so we prefer the (starter package) hosting of www.neostrada.nl, but they have a shared server, and it is not wordpress optimized.
**Is there a real benefit in using Wordpress optimized hosting likewww.bluehost.com/wordpress? Or are there any other things that can make a Wordpress site load faster on the first visit?** | It depends on what you need.
The software environment is the same you need for every other PHP site where you want to get an efficient workflow:
* up-to-date PHP (currently 5.5, so you can use Opcache) with at least 128 MB memory limit
* the same for MySQL
* web server with a rewrite engine
* regular backups
* SSH
* Git
You can get that everywhere for 5 €/month. In fact, I have seen more expensive “WP optimized” hostings where you could not even get PHP 5.4. Not acceptable, newer PHP versions are _much_ faster.
What does make a difference is the support: If you need a lot of support and there are people who know WordPress very well, this will be very beneficial. Good, fast support is worth some money. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "performance, vps, shared hosting"
} |
Featured image with link to post shortcode, image displaying above the post
I have created a shortcode to display the featured image linking to the post:
function ck13_post_image($atts){
extract(shortcode_atts(array(
'ck_img_size' => 'full'
), $atts));
$show_the_image .= '<a href="' . get_permalink() . '">' . the_post_thumbnail("$ck_img_size") . '</a>';
return $show_the_image;
}
//---------------------------------------------
function register_shortcodes(){
add_shortcode('show-post-img', 'ck13_post_image');
}
add_action( 'init', 'register_shortcodes');
But instead of displaying the image inside the post, the image is displayed above it.
The weird thing is that the link to the post is displayed correctly inside the post, just the image is above.
Did i make some mistake? How can i make this work? | `the_post_thumbnail` echoes its value, which doesn't work in variable assignment. Use `get_the_post_thumbnail` instead.
Most WordPress API functions follow this pattern, there are typically two versions - one which will `echo` the result and another with `get_` prepended which will `return` the result. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode, post thumbnails"
} |
Capability to prevent upload of files
I need the ability to allow users to insert media (images) into a page / post, but not allow them to upload the files.
The only capability I can see is 'upload_files', which allows a user to upload / insert files.
Is there a way to prevent upload of files but still show the media manager (via the 'Insert Media' button on the Edit screen) allowing users to insert the images?
My thought of how to approach this would be via jQuery - run a script when the capability is something like 'my_insert_media', which would hide the 'Upload' tab of the media uploader. Of course this could be worked around by disabling Javascript in the browser, but that's not a major concern for this project.
Any other suggestions, or holes in this approach?
Thanks, Dan | You can try with this:
function remove_media_tabs($strings) {
unset($strings["insertFromUrlTitle"]);
unset($strings["setFeaturedImageTitle"]);
unset($strings["createGalleryTitle"]);
unset($strings["uploadFilesTitle"]);
return $strings;
}
add_filter('media_view_strings','remove_media_tabs');
This will remove 'Upload file' and 'Insert from URL' links when you open insert media screen, so user will be able only to select images or whatever that is already in media library.
For more things you can do with unset, check in: wp-includes/media.php file. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "uploads, media, capabilities, media modal"
} |
Is there a way to run upgrade.php for one blog?
I just ran the auto update to verion 3.9 today, but am having problems with the "Network Update".
I seem to have a firewall or network problem with this error :
> Your server may not be able to connect to sites running on it. Error message: couldn't connect to host
Anyways, is there a way to run the database updates per blog ? Can I use a special URL ? Can I do it from shell command line ?
On an old forum post, someone suggested that update.php runs automatically the first time you log into your blog admin ( even if Network Update hasn't been run ). I wonder if that's true.
Thanks | WP CLI has a command that can upgrade the database:
wp core update-db
If that command doesn't upgrade the entire network, you can pass in the site you want upgraded as an additional parameter
e.g.
wp core update-db --site="
You can get WP CLI from here:
<
it's also available on github
You can install using:
curl -L > wp-cli.phar
It also comes with VVV | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "multisite, database, upgrade, network admin"
} |
Custom post type navigation on static page
I'm using the following code on a WP3.9 site to show a bunch of custom post types with pagination on a static page set as the frontpage:
$args = array(
'post_type' => 'movie'
);
$paged = (get_query_var('page')) ? get_query_var('page') : 1;
$wp_query = new WP_Query( array_merge( $args, array('paged' => $paged) ) );
The first page is showing the correct info, but when I go to **domain.com/page/n/** I get redirected to **domain.com**.
If I add the following code to the functions.php file:
function disable_redirect_canonical( $redirect_url ) {
$redirect_url = false;
return $redirect_url;
}
add_filter('redirect_canonical','disable_redirect_canonical');
Then I can go to **/page/3/ and greater** , but **/page/2/** still redirects to the main page.
I'm really lost about this and I'm not really sure where to look to fix this problem.
Any help would be appreciated | The culprit was the All in One SEO Pack plugin I'm using on the site. I had to disable the "Enable Advanced Options" in the "Custom Post Type Settings" section. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, pagination"
} |
Ajax Call in page theme not working?
Ok, i am VERY new to wordpress (2 Hours new). I am creating a page template, which works fine, but this is the issue i am having:
In the template.php file, i have this code:
<script type="text/javascript" src="
<script type="text/javascript">
function loadTweets() {$.getJSON(" function (json) {alert(json);});} setInterval(loadTweets(), 60000);
</script>
For some reason when i go to the URL in my browser, I get an Error 500. Same with my ajax call? How would i fix this?
I was told maybe a .htaccess file, but i dont think that would be an issue. For some reason this page is blocked. | 1. You shouldn't be including jQuery explicitly. WP ships with a copy and multiple copies tend to mess things up. See `wp_enqueue_script()`.
2. You shouldn't be trying to load PHP file inside a theme directly. It won't load WordPress environment that way (unless it tries to do so explicitly, which is usually very fragile and pretty much cannot be reliably done in public code).
3. Error 500 is unfortunately very not transparent thing. It is produced by your web server rather than WordPress and there is no insight into what might be causing it that can be gained on WP level. You'll have to look up details for error in your web server logs / ask hosting support to do that. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, templates, ajax, page template"
} |
Difference between is_user_logged_in and $_session['uname']
I am writing a condition to check if a user is logged in, not sure which of the below condition to use :
if(!is_user_logged_in()){
And
if(!isset($_SESSION['uname'])){
Basically need to check if any user is logged in. | The Core function for checking whether a user is logged in is `is_user_logged_in()`. You should use that if at all possible.
WordPress does not use sessions at all, by default, and never has so far as I can remember. When I try `var_dump($_SESSION);` I get an "Undefined variable" Notice exactly as I expected. I haven't explicitly tested with the latest release but I doubt it introduced such a radical change.
If your site uses sessions, it is not the Core doing it. There must be a plugin involved. If that plugin uses sessions as a part of a custom login system you may have to use `$_SESSION['uname']` but hopefully your plugin is written such that `is_user_logged_in()`, which is pluggable, works correctly with the custom login system. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, conditional tags"
} |
Hide plugin dashboard menu item for specific roles
I am writing a plugin and I am trying to only display the admin dashboard menu item to specific roles. I have this controlling snippet so far...
// Check User Role
global $current_user;
if( !empty($current_user->roles) ){
foreach ($current_user->roles as $key => $value) {
if( $value == 'administrator' ){
new myplugin_Wp_List_Table();
}
}
}
This isn't working for some reason, when i'm logged in as administrator it doesn't display the menu.
Anyone any ideas? | I think is a better strategy, that you add on the activation a new capability and add this capability to the Administrator role. This makes possible for installations with much different roles to the WP default to add this capability to other roles or for the requirement of a installation to add the view to another role.
### Add Cap to a Role
add_action( 'admin_init', 'fb_add_capabilities' );
function fb_add_capabilities() {
`$GLOBALS['wp_roles']->add_cap( 'administrator', '_your_custom_cap' );`
}
### Check for Cap
Inside your source can you check for this capabilty:
if ( ! current_user_can( '_debug_objects' ) )
return;
### Remove Cap
On the deactivation (Hook `register_deactivation_hook`) and uninstall (Hook `register_uninstall_hook`) of the plugin is it necessary, that you remove the cap. `remove_cap()`
### Example
A example in the wild can you finde in this plugin, file. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugin development, user roles"
} |
How to remove post redirects
I recently installed a plugin called "Q and A FAQ and Knowledge Base for WordPress"
Turns out it was lacking in the features I needed so I trashed every faq I had created and then deactivated the plugin.
I have since gone and created a post with the same name/url (i.e. /faqs) BUT when I access the /faqs URL is displays all the faq posts that I have previously deleted?
How can I make sure that nothing to do with faqs still shows up? How can I permanently remove the redirect to /faqs which displays the old faqs and make it show my new page? | Figured it out - It had also created a "Page" which was still using the /faqs slug. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, url rewriting, wp redirect"
} |
Bootstrap with Flexslider jQuery Issue
I'm building a Wordpress theme using Twitter Bootstrap.
I have registered and enqueued the bootstrap .js file (including others) and everything works fine. This is my code:
wp_register_script( 'wp-flat-bootstrap', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '', true );
However, I have just integrated the Flexslider by WooThemes and I have also registered and enqueued its .js file. This is my code:
wp_register_script( 'flexslider-jquery', ' '', true );
Whenever, I land on the page where the Flexslider appears the bootstrap .js's file stops working, which has its effect in that the menubar drop down stops working.
Does anybody know how I can use the two scripts together without having this issue? | The code you wrote is NOT including the flexslider code, it is only trying to include a google hosted copy of jquery.
wp_register_script( 'flexslider-jquery',
# this is just the Google Hosted version of jQuery
'
'', true );
You probably want something more like this:
wp_register_script( 'flexslider-jquery',
get_template_directory_uri() . '/js/jquery.flexslider-min.js',
array( 'jquery' ), false, true );
You'll need to put the flexslider code in the right directory of course, or adjust the above to match your site structure. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery"
} |
sort by name (slug) custom post type
What's wrong in this query ? the sortby=name doesn't change anything.
$the_query = 'posts_per_page=-1&sortby=name&order=ASC&post_type=mycustom&custom_cat=mycat';
// query is made
query_posts($the_query); | The "sort" query param is usually "orderby" not "sortby", to match the SQL `ORDER BY` clause.
Perhaps try:
$the_query = 'posts_per_page=-1&orderby=name&order=ASC&post_type=mycustom&custom_cat=mycat';
It's also possible that the value you are passing is incorrect, but without knowing the details of your custom post type there's not much else I can suggest. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, sort, slug"
} |
How to use mysql IN statement with wpdb update method?
I am using wpdb update method and wish to update records where the id is not found within multiple ids.
So if I wanted to update records where each had an id of `1` I would do for example:
$wpdb->update(
'wp_my_tables',
array(
'active' => 0
),
array( 'id' => 1 ),
array(
'%d'
),
array( '%d' )
);
But how would I edit that so it does NOT update values where the ids are for example `1,2,3` ? | Unfortunately update helper only handles such simple equals conditions:
$wheres[] = "`$field` = {$form}";
For more complex queries you'll have to form SQL yourself and use `wpdb->query()` method to run it as arbitrary query. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "plugin development, wpdb"
} |
Exclude pages from WordPress search result page
How can I exclude pages for logged-in members from WordPress search results? | Add this to your child themes functions file using a code editor like Notepad++.
You will need to change the page I.D's in the code to your own.
**Exclude Specific Pages From Search Results**
add_filter( 'pre_get_posts', 'exclude_pages_search_when_logged_in' );
function exclude_pages_search_when_logged_in($query) {
if ( $query->is_search && is_user_logged_in() )
$query->set( 'post__not_in', array( 1, 2, 3, 4, 5 ) );
return $query;
}
**Exclude All Pages From Search Results**
add_action('pre_get_posts','exclude_all_pages_search');
function exclude_all_pages_search($query) {
if (
! is_admin()
&& $query->is_main_query()
&& $query->is_search
&& is_user_logged_in()
)
$query->set( 'post_type', 'post' );
}
Source < | stackexchange-wordpress | {
"answer_score": 15,
"question_score": 4,
"tags": "search, membership"
} |
User-uploaded images without an account
What are folks doing in the way of allowing users to upload images, but not have an account in order to perform the upload? So I'm user Bill, and I come to your website. You're having a contest for user-submitted work desk photos, and I want to submit my desk picture for the contest. You, site Owner Jane, don't want me to have an account in order to upload a photo.
Ignore any logical inconsistencies in the example please, the goal is image upload without site account.
In the past I've just used something like Flickr or other image repositories, and let users post images there, sucking them in from there. My client doesn't want to do that if they don't have to.
Note: I am NOT looking for a plugin recommendation explicitly--what I'm looking for is a method for allowing this, whether that's custom PHP code or something else. | I've used Gravity Forms for this very purpose, it took about 3 minutes to set it up.
The only difference in my case being that visitors were submitting a document rather than an image, but you just specify the allowable file types when creating the upload form field (e.g. jpg, png).
All the major form plugins provide file upload functionality (Ninja Forms, Contact Form 7, etc.).
You might have some coding to do depending on what you then want to do with the uploaded images. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "images"
} |
Find which Permalink structure is the best
I have the following permalinks structure in mind for a new blog, now instead getting theoretical answers on which is best, i would like to find myself which is best in terms of speed. How can i find this? I tried using get_num_queries() but i find the results varying each time i access the blog.
Note: I am running a local XAMPP installation with WordPress on it and i am new to PHP, so any guidance is much appreciated.
/%postname%/
/%post_id%//%postname%/
/%post_id%/%postname%/
/%category%/%postname%/
I am expecting 5000 plus posts but pages wont exceed 10. Thought this might also help someone when replying back to my query. Thank You. | Any speed differences between the various permalink structures is negligible. I mean, we're talking likely milliseconds of difference. Forget speed, just go with the structure that makes the most sense semantically for your site. On another note, it makes sense to go with a structure that will make the most sense for your users. For example, it makes sense to go with /category/post_name if you have a lot of categories/posts, as it makes navigation easier for users. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks"
} |
Custom/separate categories for custom post type
How can I achieve a separate "data space" for the categories of my custom post type? I don't want the general post categories to appear in my custom post type and vice versa.
The `register_taxonomy` function seems to add a "tagging system" (bottom panel in the screen) to the post type but not the same small window the "real" categories have (upper panel in the screen).
!custom categories vs custom tags | You can use `register_taxonomy` to create a category-like custom taxonomy using the argument **'hierarchical'** set to true.
In Codex example see the first taxonomy registered ( _"Genres"_ ). | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "custom post types, categories, custom taxonomy"
} |
Conditional tag is_page with a custom post type
Accordingly to the is_page documentation, supplying the slug as an argument WP can tell me whether the current page is the one represented by the slug. Perhaps I am using the wrong slug? However I did try both the path used in the rewrite argument as well as the bit I consider to be the "slug" or in other words the element used to register the CPT.
Please find below a code snippet to let you understand:
'rewrite' => array( 'slug' => 'faqs/archivio' )
);
register_post_type( 'faqs', $args );
I did this a go using the slug used for a custom post type, but I wasn't able to get this working.
So two questions?
1. Is the is_page supposed to work in this case?
2. if not, what the best alternative?
Thanks Andrea | The creation of a custom post type have it inside the definition, a post type. Also is page only a default post type. If you register your custom post type, then check for this post type, not for a page.
### Conditional Tag `is_singular`
The function, conditional tag `is_singular()` main purpose is to check if viewing a singular post. However, it can also be used to check if viewing a singular post of a given post type by entering the `$post_type` parameter as shown in the following code snippet.
`is_singular( 'your_custom_post_type' );`
or different post types
`is_singular( array( 'your_custom_post_type_1', 'your_custom_post_type_2' ) );`
### Hint to debug
I use the plugin Debug Objects to debug topics in this context. Maybe this helps you also, often easier as read the code or codex. See the follow screenshot of the plugin, the result of the conditional tags, include `is_page()` and `is_single()` on a CPT. !enter image description here | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "functions, conditional tags, core"
} |
Defining the output of a Wordpress Att
I have this code where I'm trying to define how those attributes (ptid, ptle, pge ) will behave once the code runs. I would like to be able define them so to get them to execute functions before outputing the result.
// Add Shortcode
function formatage( $atts , $content = null ) {
// Attributes
extract( shortcode_atts(
array(
'ptid' => '',
'ptle' => '',
‘page’ => '',
), $atts )
);
// Code
return X
}
add_shortcode( 'p-fmt', 'formatage' );
p.s. anybody knows any good wiki about shortcodes? | I am not sure but do you want to get that attribute value to work on them ?
This is a way to do so
// Add Shortcode
function formatage( $atts , $content = null ) {
// Attributes
extract( shortcode_atts(
array(
'ptid' => '',
'ptle' => '',
‘page’ => '',
), $atts )
);
$ptid = $atts['ptid'];
$ptle = $atts['ptle'];
$page = $atts['page'];
if(!empty($ptid)){
//include your php file here
}else{
//do something else
}
// Code
return X
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode"
} |
Admin Top Bar Not Showing On Front End
i'm having problem with displaying admin top bar on my site. I googled and got some solution which i tried like
1) Checking wp_footer in footer.php
2) Checkbox ticked in user profile saying show toolbar will viewing site.
All done but no success. please can anyone point me in right direction. I'm using Classicraft theme.
I'm using wordpress 3.8.3
I have another wordpress installation on same server and can see admin bar their but not on this site. is this theme specific problem ?
Thanks in advance. | It certainly can be a theme related 'problem'. To prevent unexpected problems in a theme, I frequently disable the admin bar while working on it. Look in functions.php (or similar) for code that looks like this and remove it:
function my_function_admin_bar() {
return false;
}
add_filter('show_admin_bar', 'my_function_admin_bar'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "admin, admin bar"
} |
Confusion about arguments sent to add_image_size
Looking at the documentation for Cropping Thumbnails when adding new image-sizes makes me confused.
> Set the image size by cropping the image and defining a crop position:
>
> add_image_size( 'custom-size', 220, 220, array( top, left ) ); // Hard crop top left
>
> When setting a crop position, the first value in the array is the x axis crop position, the second is the y axis crop position.
>
> x_crop_position accepts 'left' 'center', or 'right'. y_crop_position accepts 'top', 'center', or 'bottom'.
By this `array(top, left)` wouldn't be "allowed" because top is only allowed by y-crop position ? | As @PieterGoosen said, your point is valid. A look into the source confirms that the codex description of add_image_size was wrong there. It was, because I changed it to be correct. That said, everyone can help improving the codex, you just need to register. You might want to take a look at Contributing to WordPress for a introduction on how to do that, the first section is about the documentation aka codex. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "images, cropping"
} |
is_single(); Question
If a page would contain this code:
`<?php if( !is_single('') ): ?><div id="navtoggle"></div><?php endif; ?>`
But regardless of it would show the div navtoggle, would that mean the code makes WP think the page is a `posts` page?
If not, how can I make WP only show navtoggle on the homepage? | You should have a look at using conditional tags in wordpress. `is_single()` is the conditional tag for a single page, ie single.php.
For homepage, `is_home()` or `is_front_page()` should be use, depending on whether a front page is set in settings or not. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, single"
} |
Strategies for coping with hyperagressive spambots?
A couple of my sites are getting slammed by a hyperagressive distributed spambot. It's just pure link spam. It all comes from one user name, but from a variety of IPs.
Akismet is catching the spam, so my sites aren't defaced. But it's affecting performance.
What is best practice, if any, for mitigating this?
**Edit** There are about 400 of these in 24 hours. They're coming from a rotating bunch of IP addresses. There are between five and ten hits from each address.
* 60.173.9.*, 60.173.10.* and 60.173.11.*
* 112.123.168.*
Both of these address ranges are assigned, according to apnic.net, to ISPs in China.
(I'm guessing malware-infested cybercafes, but who knows?)
Again, is there a best practice to deal with this junk? Or just let akismet do it? | One surprisingly useful solution to foil most spam-bots is to use a honeypot. Put an extra entry field into your comment forms, and then hide it with css. Normal users won't fill it in because they won't ever even see it. Based on that, you can safely assume that anytime an entry is made with that field filled, that it's a bot and you can just discard/mark it as spam. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "comments, security, spam"
} |
Use the_content outside the loop
I was trying to get first 100 words of the content in the header, and I use the following snippet to get the first 100 words in the loop, but is it possible to get the value outside the loop:
$cstring = get_the_content( '' );
$newcString = substr( $cstring, 0, 100 );
echo'<p>' . $newcString . '</p>'; | If you are trying to do it for the current page you are on you can just use this:
global $post;
$content = $post->post_content;`
This will get the content for the current post instead of having to set the ID specifically. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "loop, the content"
} |
Injecting a javascript banner code right before & after wordpress navigation menu
I am trying to develop a plugin to inject a javascript banner code right before and after the wordpress navigation menu but I am unable to find any solution to this problem. Does anyone have any idea?
I cannot append to a Div ID either since every wordpress theme uses different div id and class for navigation menu.
Thanks
Edit: Banner code is adsense javascript code. Wordpress does have wp_nav_menu functionality and i want to inject javascript before and after wp_nav_menu. | The Core menu system, which was not mentioned in the initial version of the question, does not have any "before" and "after" hooks that I can find. You could create a custom Walker that could include those hooks but it is going to be a theme problem, either way.
If that is not satisfactory, you will need to alter the DOM with Javascript. I don't know if that is even possible/viable for the code you want to include but if that is an option you need to hook code to `wp_enqueue_scripts` something like this: <
You can use `wp_localize_script()` to write data to the page that your script can use. For example: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "plugins"
} |
How to use shortcode of any plugin to show it visually where i want?
I don't know much about shortcode. I have a countdown plugin with this plugin i'm displaying 'countdown timer', i can post it with shortcode E.g `[countdown event="Event with hour & minutes" date="12 June" hour="18" minutes="54"]`. I tried to fetch it with `get_post_field('post_content', $post->ID)` but with this way I can not displaying the 'countdown timer' as visually, just fetch the lettering. Is it possible to show countdown plugin with shortcode where i want. Hope you can help. I really need it. | `get_post_field` alone does not render shortcodes. Try
echo do_shortcode( get_post_field( 'post_content', $post->ID) ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, posts, shortcode"
} |
Get email address of type Administrator
I am new wordpress, please help me. How can I get all the details of type Administrator. I have created 2 users with Role as Administrator, like `get_option( 'admin_email' );`.
I want the Email address of users of type Administrator. | You can use this function to get email of all the Administrator on a WordPress website
function get_administrator_email(){
$blogusers = get_users('role=Administrator');
//print_r($blogusers);
foreach ($blogusers as $user) {
echo $user->user_email;
}
} | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "admin, email"
} |
Custom post-type metabox position
I'm pretty new to Wordpress development, I'm learning about custom post types, custom taxonomies & meta boxes at the moment, following various tutorials online. So please forgive any mistakes!
I've got a custom post-type set up, and a meta box with input field too, yet I can't seem to set the permanent position of the meta box. Here's the code:
function add_discography_metaboxes() {
add_meta_box('meta_album_info', 'Album Information', 'meta_album_info', 'discography', 'normal', 'high');
}
I can drag the `Album Information` meta box from the main section to the side, is this cause of a problem with code? or can you drag a meta box anywhere even if the position is set? | Metaboxes are always draggable, that is the default behavior.
You can place the box content on another position, see this example. But you should be absolutely sure the user wants that. I don’t recommend it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, metabox"
} |
Capabilities Not Changing
I want editors to be able to list, add and edit users. I thought the following code would do it, but it doesn't work - no new User menu appears for any editors. Have I missed something?
function increase_editor_role(){
$role = get_role('editor');
$role->add_cap('list_users');
$role->add_cap('edit_users');
$role->add_cap('create_users');
}
add_action('admin_init', 'increase_editor_role'); | I believe your code is right. Try going to: 'wp-admin/users.php' manually to check if you have the privilege to do so. If my inkling is right, it's just the `$submenu` item that is hidden.
If you can access the list of users, try printing the global variable `$submenu` and see if 'users.php' is there. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "capabilities"
} |
Get Tag Slugs that start with a word
Is there a way to get all tags whose slug starts with a specific word? I tried to use the below code but doesn't output anything. What am i missing here? I am new to php so excuse if i am doing something totally wrong.
$auth = get_term_by('slug', 'author-', 'tag');
print "values".$auth; | I think its easier to get them all and filter the ones starting with author:
<?php
$tags = get_terms( 'tags', array(
'hide_empty' => 0
));
if ( !empty( $tags ) && !is_wp_error( $tags ) ): ?>
<ul>
<?php foreach ( $tags as $tag ): ?>
<?php if(strpos($tag->slug,'author-') !== false): ?>
<li><?php echo $tag->name; ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<?php endif; ?>
If you have lots of tags, you can use the transient api to store the results. I didn't tried this, but it should work fine. This will store the tags for 1 day:
<
* Also, you might want to store only the necessary info in the transient api, not the whole array of stuff, so only the name and the id would be fine, but you get the idea. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "tags"
} |
Checking if an attribute exists in a shortcode
I've written a small plugin that spits out html for a button. It works great, except for one thing: If the user doesn't specify an image, the image appears broken. Is there a way for me to check and see if the user has specified an image, and only print the image code if that's the case?
Here's my plugin code:
function button_shortcode($args) {
return "<a class=\"button\" href=\"" . $args["url"] . "\"><img alt=\"" . $args["bigtext"] . "\" class=\"alignleft\" src=\"" . $args["img"] . "\" /><small>" . $args["smalltext"] . "</small>" . $args["bigtext"] . "</a>";
}
add_shortcode("button", "button_shortcode");
Here's the shortcode:
`[button url=" img="/path/to/image.png" smalltext="Smaller Text" bigtext="Bigger Text"]` | Borek pointed in the right direction, here's my fine code*:
function button_shortcode($attributes, $content) {
if ($attributes["image"] != "") {
$img = "<img alt=\"" . $content . "\" class=\"alignleft\" src=\"" . $attributes["image"] . "\" />";
} else {
$img = "";
}
if ($attributes["intro"] != "") {
$intro = "<small>" . $attributes["intro"] . "</small>";
}
return "<a class=\"button\" href=\"" . $attributes["link"] . "\">" . $img . $intro . $content . "</a>";
}
add_shortcode("button", "button_shortcode");
*Note: I did change some of the attribute names and stuff as well, but that wasn't necessary. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 6,
"tags": "plugins, plugin development, shortcode, customization"
} |
Combine category AND custom taxonomy in permalink structure
It seems like this question has been asked not infrequently, but I still can't make heads of it. I followed the Rewrite API Guide to look at how to merge, but I want something like this:
Category = categories, built in. Food = custom taxonomy.
When I enter < to find all posts in that category and that foot type, similar to
I'll also have pages, which aren't attached to a "food" or category, and the permalink fails if i simply put %foood%/%category%/ into the permalink settings.
Does anyone have any recommendations? | What I ended up doing was setting up an endpoint for food, like so:
global $wp_rewrite;
$wp_rewrite->add_endpoint( 'food', EP_PERMALINK | EP_PAGES );
$wp_rewrite->flush_rules();
function printview_query_vars($vars)
{ array_push($vars, 'food');
return $vars;
}
add_filter('query_vars','printview_query_vars');
Then I'd get a url like ` and the wp_query would contain something like `food=>fruits/shelves`, which then i can parse myself into a custom query. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks"
} |
Show different time stamp based on time
What's the best way to show a time stamp based on different times? For example: if a post is under 24 hours, show _%% mins/hours ago_. If a post is over 24 hours, show _month/day/time_. If a post if over a year ago, show _month/day/year/time_.
I've done this so far:
<?php if(get_the_time('G') < 23) {
the_time('Y'); } else {
the_time('F j, Y at g:i a'); } ?> | Thanks for the responses! This is the solution:
<?php
if ( DAY_IN_SECONDS < ( $time = current_time( 'timestamp' ) ) - ( $time_post = get_the_time( 'U' ) ) )
echo human_time_diff( $time_post, $time ) . ' ago';
elseif ( WEEK_IN_SECONDS < ( $time - $time_post ) )
the_time( 'D / g:i a' );
elseif ( YEAR_IN_SECONDS < ( $time - $time_post ) )
the_time( 'F j / g:i a' );
else
the_time( 'F j, Y / g:i a' ); ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "date, date time"
} |
Cannot update custom database table row
I am trying to update a row in a custom database table by `$wpdb->update();`. In my opinion my code is right but for some reason my database row doesn't update.
Can anyone help me with this?
I want to update a the status of a transaction in the table wp_mollie_transactions where the `transaction_id` is equal to the `$order_id`, which I received from from my payment provider.
(Off course I made `$wpdb` global in this file)
// Update database
$wpdb->update( $wpdb->prefix . 'mollie_transactions',
array(
'status' => $payment->status
),
array(
'transaction_id' => $order_id
)
); | Before trying to write to the database, **always** validate the values you're putting in:
$fValid = true;
if ( !isset( $payment->status ) ) {
echo 'Error: Payment status is not set';
$fValid = false;
}
if ( !isset( $order_id ) ) {
echo 'Error: Order ID is not set';
$fValid = false;
}
if ( $fValid ) {
// Update database
$fSuccess = $wpdb->update( $wpdb->prefix . 'mollie_transactions',
array(
'status' => $payment->status
),
array(
'transaction_id' => $order_id
)
);
echo sprintf( 'Update %s where Payment Status was %s and Transaction ID was %s', $fSuccess? 'Succeeded':'Failed', $payment->status, $order_id );
}
Cheers. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "database, wpdb, globals"
} |
TwentyThirteen - Footer overlapping content
So, I'm designing a theme for a friend of mine, but there is a problem with the footer.
Assuming the very bottom of the browser window is 1000px, it seems that the page content ends at 1000px, and the footer sits between 900px - 1000px.
Thusly, the last 100px of content are cut off, and unreadable.
How can I move the bottom of the content to end at 900px, leaving room for the footer?
See here: <
Note the submit comment button is cut off.
* * *
I'm no expert by any means, and I hope what I've said makes sense. | This is because your footer is fixed which removes it from the normal page flow. You can add 50px padding-bottom to your #main div (or `.site-main` on line 790 of your style.css).
Overall this though isn't really a WordPress questions and more of a HTML / CSS Questions. Please visit Stack Overflow. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "content, footer"
} |
get_post_meta with WP_query
I know this is a convoluted loop (inherited from someone else), and this must be pretty simple: `the_permalink` and `the_title` display OK, but why doesn't my post meta `eventdatestart` echo?.
<?php
$queryObject = new WP_Query( 'post_type=events&posts_per_page=5' );
if ($queryObject->have_posts()) {
?>
<div id="wrapper"">
<h3>Events</h3>
<ul>
<?php
while ($queryObject->have_posts()) {
$queryObject->the_post();
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php echo get_post_meta(get_the_ID(), 'eventdatestart', true );?>
</li>
<?php
}
?>
</ul>
</div>
<?php
}
?> | I think you may need to add `global $post` after the loop starts based on a similar question found here.
<?php
while ($queryObject->have_posts()) {
$queryObject->the_post();
global $post;
?>
I wish I could explain more about why, but I didn't have time to investigate further. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "query, meta query, post meta"
} |
Does wordpress allow me to add a php file to the root directory to execute custom scripts?
Does wordpress allow me to add a php file to the root directory to execute custom scripts?
I need functionality similar to functions.php that you put into themes.
Are there any work arounds that don't involve modifying the config.php file? | > Does wordpress allow me to add a php file to the root directory to execute custom scripts?
WordPress can't prevent you from adding PHP files to the root directory, but there is no builtin functionality to load those files. You can load them yourself but if you are not careful they will load outside of WordPress context, which is a painful way to work.
What you want, almost certainly, is a plugin or a MU-Plugin. MU-Plugins work similar to what you are asking, if I understand you, but instead of placing your file in the site root you would place it in `wp-content/mu-plugins/`. It will be loaded automatically for all sites in the network and cannot be disabled except by deletion from the server. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, directory, automation"
} |
Child theme preview missing
I followed the beginner steps for creating a child theme. The child theme was created and it appears as an option on my Themes page. But unlike the other Themes on the page (including its parent), there is no preview. The other themes ("Twenty Twelve," "Twenty Thirteen," and "Twenty Fourteen") are all listed with an image preview. My child theme ("Twenty Fourteen Child") does not have any image. The child theme can be applied without issue.
This issue arises when I create child themes from other themes as well. Any ideas why this is happening and if I can resolve? | Unfortunately this isn't covered in that codex page. These previews of the themes aren't auto generated. You will need to take a screenshot of your theme, and upload that screenshot to your root folder as 'screenshot.png'. This screenshot will be automatically used then as a theme preview pic for your theme.
I quote from the Theme Development page in the codex about screenshots for theme preview pic
> Create a screenshot for your theme. The screenshot should be named screenshot.png, and should be placed in the top level directory. The screenshot should accurately show the theme design and saved in PNG format. The recommended image size is 880x660. The screenshot will only be shown as 387x290, but the over double-sized image allows for high-resolution viewing on HiDPI displays. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "child theme"
} |
How to get theme screenshot
I would need to get list of available themes with their screenshot. I tried to use `wp_get_themes` function, but it doesn't seem to be returnig screenshot.
What is the way to get screenshot for each available theme? | You can use `WP_Theme::get_screenshot()` method, which returns the screenshot url.
For example:
$themes = wp_get_themes();
foreach( $themes as $theme ){
echo '<img src="'.esc_url($theme->get_screenshot()).'" />';
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "themes"
} |
W3 total cache - white screen of death when trying to show certain taxonomies
I'm using plugin W3 Total cache and it worked excellent -until I added a custom "detail page" of a custom taxonomy (with a file called taxonomy-categorycourses.php) where the categorycourses is the taxonomy. I get the white screen of death-experience. I have turned errors on, but nothing shows up. I just get a blank page. I've google around and cannot find some satisfying answers. (The taxonomies shows up correctly when not cached , for example - when logged in).
**UPDATE**
I loved w3 total cache until know. This is a bug that shouldn't exist in the plugin, but it apprently does so I deleted it, and installed WP Super Cache and activated and then everything worked as it should. | I loved w3 total cache until know. This is a bug that really shouldn't exist in the plugin, but it apprently does so I deleted it, and installed WP Super Cache and activated and then everything worked as it should. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, plugin w3 total cache"
} |
Change site template from php
What is the argument to pass to switch theme, when I have the result of `wp_get_themes()`?
$args = array(
'allowed' => true
);
$themes = wp_get_themes( );
foreach ($themes as $theme) {
$argument_to_pass_to_switch_theme = ??????
} | If I understand your question, you should use this inside your `foreach`:
$argument_to_pass_to_switch_theme = $theme->get_stylesheet();
* * *
Just taking a look at the documentation:
The function `wp_get_themes()`...
> _"...returns an array of WP_Theme objects based on the argument."_
This class `WP_Theme` has a method `get_stylesheet()`, which...
> _"...returns a string with the directory name of the theme's "stylesheet" files, inside the theme root. If this is a child theme it is the directory from the child theme. "_
And the function `switch_theme()`...
> _"...accepts one argument: $stylesheet of the theme. ($stylesheet is the name of your folder slug."_ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "templates, switch theme"
} |
Target "admins" with different styles on the front end
I'll first explain what i'm trying to do. I am building an intranet for a client. They do not want employees to be able to edit their profiles or upload avatars, just "admins" should be able to do that. To disable this, i'm going to `display: none` the edit profile and upload avatar buttons by default. I want these to then show for logged in admins -- so they can edit profiles. I didn't see any body class added to logged in admin users, so I was thinking I could add a CSS file for logged in admin users that displayed the hidden div. I am also using WP Engine, I don't know if this is affected by their caching or not.
How can I accomplish this? | There are a couple of ways to do this:
1. With template overloads
Overload these files:
> \bp-templates\bp-legacy\buddypress\members\single\profile\edit.php
>
> \bp-templates\bp-legacy\buddypress\members\single\profile\change-avatar
At the top of the overload, do a `current_user_can()` check and then do or don't show the rest of the template.
1. Filter the button creation based on a `current_user_can()` check. See the filter in `bp_get_displayed_user_nav()` in 'bp-members\bp-members-template.php' | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "buddypress, admin css"
} |
Error establishing a database connection - Multi-site with subsite don't exisit
I have a multi site setup to which I have placed
define( 'NOBLOGREDIRECT', ' );
In the wp-config.php file
However when I visit a site which dose not exist (e.g. < I'm greeted with the following
> Error establishing a database connection
Instead of being redirected to the homepage as defined.
I have disabled all plugins and reverted back to the default .httaccess however this has not solved the issue.
How can I solve this and have a none existing subsites redirected to the appropriate location? | This problem was solved by
replacing
define('DOMAIN_CURRENT_SITE', '/');
with
define('DOMAIN_CURRENT_SITE', 'www.example.com'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, database, errors"
} |
Using xprofile_insert_field
I'm trying to add a xProfile to BuddyPress, but I don't know where but my snippet is not working. I have tried so many stuff, but I just can't get it right.
Hope you can help, here's the latest version of my snippet:
add_action('bp_init', 'field_xprofile_twitter');
function field_xprofile_twitter()
{
xprofile_insert_field( $xfield_args );
global $bp;
$xfield_args = array (
field_group_id => 1,
name => 'Twitter',
can_delete => false,
field_order => 1,
is_required => false,
type => 'textbox'
);
} | Your code does work. It's just that you are declaring $xfield_args after you have made the call xprofile_insert_field( $xfield_args );
it should look like this
add_action('bp_init', 'field_xprofile_twitter');
function field_xprofile_twitter()
{
global $bp;
$xfield_args = array (
field_group_id => 1,
name => 'Twitter',
can_delete => false,
field_order => 1,
is_required => false,
type => 'textbox'
);
xprofile_insert_field( $xfield_args );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "user meta, profiles"
} |
Remove "Get Shortlink" button in admin of custom post type
I want to remove completely this section under my title in my custom post type. (I don't need this because I use this only for content management).
!enter image description here
With this piece of code I can remove the permalink section:
add_filter('get_sample_permalink_html', 'myfunction', '',4);
function myfunction($return, $id, $new_title, $new_slug) {
global $post;
return ($post->post_type == 'mycustomposttype') ? '' : $return;
}
Now it looks like this but I want to remove the "Get Shortlink" button too.
!enter image description here
Is there another filter for doing that? And yes... with CSS it's easy but I think a hook would be a better solution :) | If you filter `pre_get_shortlink` and return anything but `false` WordPress will not create a shortlink with its own logic. If your return value is empty, the shortlink UI will not be printed.
Combining both leads us to:
add_filter( 'pre_get_shortlink', '__return_empty_string' );
If you want to restrict the filter to a specific post type, check the second parameter:
add_filter( 'pre_get_shortlink', function( $false, $post_id ) {
return 'page' === get_post_type( $post_id ) ? '' : $false;
}, 10, 2 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "custom post types, filters, wp admin, hooks, actions"
} |
Wordpress Tags in class
I have added tags to my Custom Post Type. Now I want to use them to create a isotope portfolio, I can load all tags with this code:
<?php $args = array( 'post_type' => 'portfolio', 'posts_per_page' => 24;
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="all <?php echo $tag->slug; ?>">
<?php echo the_post_thumbnail(); ?>
<p><?php the_title(); ?></p>
</div>
<?php endwhile; ?>
But now I want to add the all tags that from each portfolio item to the `class=""`. With `<div class="<?php $tag->slug; ?>">` I just get the last tag of all the tags that are used.
I know there are already a lot of posts about this problem, but every post I have found does not seem to work for me. | Where are you getting these tags from? Typically, to get a list of tags attached to a post, you'd do:
$some_tags = wp_get_post_tags( $post_id);
and then itterate through as such:
foreach($some_tags as $tag) {
do stuff
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop, tags, slug, post class"
} |
Change content layout based on menu hierarchy
I've tried googling this one but I can't seem to find the right keywords.
What I'm trying to do is to have the content of a landing page flow exactly like the hierarchy of the navigation menu.
For example, if I had `Home Features Pricing Blog Contact` as my menu, I'd like the content block to be in that order (in the same page). If I changed my menu to something like `Home Blog Pricing Features Contact`, the content block layout should change dynamically in that order as well.
Is there a tutorial/plugin out there (or if someone could explain how it's done) to do this?
Thanks in advance. | You can use `wp_get_nav_menu_items` to grab the menu in question,
then go through the array of items to output the content
function output_landing_page_content(){
//grab the menu items in order
$menu_items = wp_get_nav_menu_items( $your_menu_id, array( 'orderby' => 'menu_order' ) );
foreach ( (array) $menu_items as $key => $menu_item ):
//get post id of linked page/post
$postid = url_to_postid( $menu_item->url );
$your_menu_linked_post = get_post( $postid );
//format content
$your_content = apply_filters('the_content', $your_menu_linked_post->post_content);
//display each page/post content however you want (add in titles, author meta or whatever)
echo $your_content;
echo '<hr />';
endforeach;
}
just place your function in the template for your landing page | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development"
} |
List all blog categories
I have created a blog plugin. I have the blog category in my blog. I would like to get the list of all the blog categories and list it in my www.domain.com/blogs/ page. My blog category name is 'blogcategory' . I do not know how to use it in the `list-category` function.
I am a nooby to wordpress development. | Can I use the following code for my question.
<?php $args = array('taxonomy' => 'blogcategory'); ?>
<?php $tax_menu_items = get_categories( $args );
foreach ( $tax_menu_items as $tax_menu_item ):?>
<a href="<?php echo get_term_link($tax_menu_item,$tax_menu_item->taxonomy); ?>">
<?php echo $tax_menu_item->name; ?>
</a>
<?php endforeach; ?>
I found it from here
**Updated: I found the answer I was looking for**
<?php
$taxonomy = 'blogcategory';
$tax_terms = get_terms($taxonomy);
?>
<ul>
<?php
foreach ($tax_terms as $tax_term) {
echo '<li>' . '<a href="' . esc_attr(get_term_link($tax_term, $taxonomy)) . '" title="' . sprintf( __( "View all posts in %s" ), $tax_term->name ) . '" ' . '>' . $tax_term->name.'</a></li>';
}
?>
</ul> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "blog, categories"
} |
ERROR: Cookies are blocked or not supported by your browser
I'm getting this error while trying to log in:
> ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress.
Yet I have cookies enabled and not blocked. I've tried this on a few different browsers, and in the incognito/private modes of those browsers, too, and get the same messages. I've also tried clearing all cookies from the cache, pursuant to the instructions on Mozilla Support. What could be causing this, and how would I go about debugging this issue? | It turns out I had `DOMAIN_CURRENT_SITE` set incorrectly in `wp-config.php`. (This particular install was a copy of another server, and the domain hadn't fully been changed.) | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "cookies"
} |
Auto login user with link from Mail
I created (a sort of) automatic login to WordPress by sending newsletters from providers like Mail Chip. When the user clicks on a link in this newsletter, s/he should be able to automatically log into her/his account without having to enter the login information. I already have a portion of the script, but I do not know how to get links from having to send.
I have found this solution on StackOverflow, but I do not understand how to implement the solution in my site. | You can grab some ideas from this tutorial:
<
hope it helps. | stackexchange-wordpress | {
"answer_score": -3,
"question_score": 2,
"tags": "login"
} |
Is there a way to stop WP editor deleting <gcse:searchbox-only></gcse:searchbox-only>
I would like to paste my Google Custom Site Search code into the editor to appear on one of my pages.
It works when pasting into the "text" side, but get's turned into a NBSP if I flick to "visual"
Is there a way I can keep `<gcse:searchbox-only></gcse:searchbox-only>` in tact in the editor? | I would suggest a shortcode:
function gcse_wpse_143459($atts,$content) {
return '<gcse:searchbox-only></gcse:searchbox-only>';
}
add_shortcode('gcse','gcse_wpse_143459');
Then use `[gcse]` instead of trying to paste in an oddball html-ish tag. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "pages, editor, google"
} |
Show taxonomies from specific CPT
I want to show a simple list of taxonomies associated with my CPT. The taxonomies are "skills". I have the following code:
<h4>Skills</h4>
<?php $taxonomy = 'skill';
$taxonomy_terms = get_terms($taxonomy);
foreach ($taxonomy_terms as $term) {
echo '~ '.$term->name .'<br />';
} ?>
But it's spitting out ALL skills that are added to that CPT, not just the ones selected. I believe the taxonomy code is correct in the functions file because on my CPT listing in the dashboard, it shows the correctly selected skills associated with the corrosponding post. All help is greatly appreciated! | I found my own answer. Not sure why this different code works, but it does:
<h4>Skills</h4>
<?php
$terms = wp_get_post_terms($post->ID, 'skill');
$count = count($terms);
if ( $count > 0 ) {
foreach ( $terms as $term ) {
echo '~ ' . $term->name . "<br /> ";
}
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy, taxonomy"
} |
Performance disadvantge of second installation instead multisite feature?
Is there any (performance-)disadvantage when I run two installations of wordpress instead of using the multisite feature?
My question refers only to the difference of multisite / two installations. I'm aware of that there will be more load etc.
### Some explanations (when necessary)
I run a private blog on a vhost.
I want to run a different wordpress instance on the same host.
Both sites are completely independent of each other - means different themes, plugins etc.
The private blog is a single-user. The new site could have many users and will move onto a single vhost when it will be successful enough. | I have never benchmarked this but...
Since every HTTP request is a distinct request, the whole WordPress Core will load on every request either way, and a little bit more code loads for Multisite. So, it seems to me that two installs should run slightly better than a single multisite install, though I doubt you will actually notice the difference. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, performance"
} |
How to add class or id to shortcode HTML elements?
I have a row elements and 3 columns inside :
[row]
[one_third]1[/one_third]
[one_third]2[/one_third]
[one_third]3[/one_third]
[/row]
How can I add a custom class or id to [row] element ? I need to squeeze cols 1 and 3 closer to 2 by modifying their margins. | You could abandon the shortcodes and use HTML.
<div class="row full-width whatever">
[one_third]1[/one_third]
[one_third]2[/one_third]
[one_third]3[/one_third]
</div>
OR
you could easily just wrap all of your code in another div and target the [row] element through CSS:
<div class="your_special_wrapper">
[row]
[one_third]1[/one_third]
[one_third]2[/one_third]
[one_third]3[/one_third]
[/row]
</div>
<style>
.your_special_wrapper div{ /*whatever css you need*/ }
</style> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "shortcode, columns, post class"
} |
How to print the output of the get_num_queries function from frontend to backend?
I'm trying to develop a simple plugin and figure out how to display the number of queries executed in frontend, to an admin page (plugin options page), using get_num_queries() function.
I've added the following code to my plugin's function file and works well showing (in my footer) the number of queries processed to create the frontend page:
function get_queries() {
$get_queries ='';
$get_queries .= get_num_queries();
$get_queries .= ' queries';
echo $get_queries;
}
add_action('wp_footer', 'get_queries', 999);
If I use `echo get_queries();` in the place where I want to display the value in my plugin page, it display the number of queries processed in the plugin options page, not from frontend.
My question is: how to print the number of queries processed to create the frontend page in my plugin options page? | Each HTTP request is a new one so you will need to save the data to the database. You can't just "pass" the data from the front to the back end.
function get_queries_wpse_143544() {
$dbq = get_num_queries();
update_option('page_queries',$dbq);
}
add_action('wp_footer', 'get_queries_wpse_143544', 999);
Then retrieve the data with `get_option`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "admin, query"
} |
How to perform a frontend HTTP call with AJAX when plugin save the new settings?
I use a function to "pass" the data with get_num_queries from the front to the back end (to a plugin options page).
function get_queries_wpse_143544() {
$dbq = get_num_queries();
update_option('page_queries',$dbq);
}
add_action('wp_footer', 'get_queries_wpse_143544', 999);
(*thanks to @s_ha_dum for the function)
The problem is retrieving the data with `get_option` will not display any data until the front end page is not visited at least once.
My question is obviously: how to perform a hidden frontend HTTP call with AJAX after clicking "Save Settings" button so that the `get_option` to display the value from the above function after the options page will be reloaded?
Thank you! | With that code in place, all you should need to do is poke the page with `wp_remote_get()` as your backend page loads, and before you need to retrieve the option value. By doing this, you avoid the possibility that no visiter has visited the page. Your request will be that visitor.
The function is fairly self-explanatory:
$response = wp_remote_get( $url, $args ) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "ajax, options"
} |
Add link at the end of wp_nav_menu
I need to add a conditional menu item such as "/at" or "/de" or "/ch" in the `wp_nav_menu`. Since the link is conditional (based on the country the website is being viewed), it can't be added from the backend but instead has to be hardcoded.
How do I add this new conditional link at the end of what the `wp_nav_menu` is populating? Thank you. | This is what worked for me (based on this).. hope it will be helpful for others too..
add_filter( 'wp_nav_menu_items','primary_navigation', 10, 2 );
function primary_navigation( $items, $args ) {
if( $args->theme_location == 'primary_navigation' ) {
if ( ! isset( $_SESSION['menu_country'] ) ) {
$country = json_decode( file_get_contents(
" . esc_url( $_SERVER['REMOTE_ADDR'] )
) );
$_SESSION['menu_country'] = strtolower( $country->country_code );
}
$items .= '<li class="menu-produkte"><a href="/' .
esc_url( $_SESSION['menu_country'] ) .'/shop">Produkte</a></li>';
}
return $items;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "menus"
} |
Allowing style tag in TinyMCE editor
In cases i want to add individual styles for an element its easy i just add inline styles inside p tags, because _wp_add_global_attributes has style attribute....
but when i want to add tag itslef to target/select multiple elements TinyMCE editor removes it entirely... so I got inside core and found filter tiny_mce_before_init but i don't know how to add style tag to allowed tags array!!!!!!! | There are some things to try in this stackoverflow thread. The one I'm trying:
add_filter('tiny_mce_before_init', 'vsl2014_filter_tiny_mce_before_init');
function vsl2014_filter_tiny_mce_before_init( $options ) {
if ( ! isset( $options['extended_valid_elements'] ) ) {
$options['extended_valid_elements'] = 'style';
} else {
$options['extended_valid_elements'] .= ',style';
}
if ( ! isset( $options['valid_children'] ) ) {
$options['valid_children'] = '+body[style]';
} else {
$options['valid_children'] .= ',+body[style]';
}
if ( ! isset( $options['custom_elements'] ) ) {
$options['custom_elements'] = 'style';
} else {
$options['custom_elements'] .= ',style';
}
return $options;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "tinymce, editor"
} |
How to get any tag ID
I want to exclude a certain tag from my home page not a category only post that hold the tag for example "olive";
I found a function for that which is like this
function exclude_tag($query) {
if ( $query->is_home) {
$query-> set('tag__not_in',array(x));
}
return $query;
}
add_filter('pre_get_posts','exclude_tag');
Whereas X is the ID of the tag I want to exclude. How can I find that ID? | In your admin, go to Posts > Tags and then click edit for the tag you're after - the URL in your browser address bar will look like:
See the part where `tag_ID=X` \- that X is your tag ID. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp query, functions, filters, tags, id"
} |
Multiple content sections on a custom post
I have a custom post type called Case Studies, which I am then pulling out and displaying all on one page. Each Case Study has a few standard sections, and I want a separate editor for each section.
For pages with multiple sections, I have been using MultiEdit, which works fine. However, it only works on pages so it isn't an option for this.
How would I do this for my custom post type? Or am I approaching the problem wrong? | You can use Advanced Custom Fields to Achieve this.
Check it out here
You can add custom fields with full editor capabilities and specific fields like images, text, number, links, etc. You can also show these fields only for your custom post type by creating a field group and setting the 'show only if' to your custom post type.
It's a very versatile and handy plugin and I use it on all my projects. Makes it easier to manage and update custom fields with almost no coding. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types"
} |
is it good to use Wordpress in the same url extension in terms of seo?
i have got a website and i want to add a Wordpress blog to it for additional (fresh) content and of course, better SEO. i'm new to Wordpress but i found out that the pages created by it are stored in the database so it's almost impossible to link to any of those pages, so it's confusing for me because i don't know that when Google crawls my domain will it also crawl database-stored wordpress pages and if it does, is this any good for SEO ranking of my whole site?
i just wanna know using the wordpress blog like "www.website.com/en/blog" will have the same SEO impact as making a blog using Dreamweaver, which has separate HTML pages that can be linked to. (apart from marking-up content)
Thanks | It is true that WordPress stores your page/post content in a database. Every CMS does this, however. Googlebot crawls links so it will see the public or front-end version of the page that WordPress produces at each URL. WordPress will serve up the page content from the database along with the theme/template/css rules in effect on that page.
Bottom line: how you see the final output of your WordPress pages is how Google will crawl them, essentially. Googlebot is not using a browser, for example so it interprets your page differently.
Name your posts with good, descriptive titles and personally I would recommend using the "post name" style for Permalinks. This gives you good keyword-rich URLs.
WP admin > Settings > Permalinks
WordPress is very SEO friendly right out of the box and on-page SEO is a breeze. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "seo"
} |
How to display milliseconds instead of seconds using timer_stop function?
I'm trying to display milliseconds instead of seconds using timer_stop wordpress function. Currently I have
$sbp_speed = timer_stop(0,2);
That display the time like `1.56` s and I need to display the time like `455.1 ms`
Thank you! | You can just multiply it by 1000:
$sbp_speed = 1000 * ( float ) timer_stop( 0, 4 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "functions"
} |
For one linked image per post, override that link with a permalink when on the main page
Is there an existing plugin that allows a person to, in a post, put a link on an image, but when the post is shown as part of the main-page list, have that image link to the post's permalink instead.
If not, can you point me in the right direction to custom code this myself? (What files to edit, what WP functions already exist that might help me...) I have a decent grasp of functional/procedural PHP, but have only the slightest experience editing WP code.
I am using WordPress 3.9 and the theme "Twenty Ten"
Feel free to re-tag this question. I am not familiar enough with WP or WP.SE to know what tags are best. | My solution was to work in the twentyten theme folder, the file "loop.php"
Around line 145 I did this:
<?php $content = get_the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'twentyten' ) );
//
//
//
$doc = new DOMDocument();
$doc->loadHTML($content);
$finder = new DomXPath($doc);
$classname = "post-main-image";
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
foreach($nodes as $node){
$node->setAttribute('href',get_the_permalink());
}
echo $doc->saveHTML();
?>
Then in the edit post screen, I simply type "post-main-image" in the "Link CSS Class" form field and update. I would expect something similar to work in other themes as well. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, permalinks"
} |
Why is my plugin version 0.1?
If you look at the changelog, it says my version number is 1.0.0.
If you look at the button to download, it says 0.1.
Also, if you hover over it (or click it), the url says 1.0.0, and the svn repository also only has the tag 1.0.0.
I'm just wondering how to change the version number on the button, and in the `compatibility` section, and in the developers tab under current version.
Here's the link to the plugin: <
Here's the svn tags directory: < | Your version number in your plugin header.
leaflet-map.php:
<?php
/*
Plugin Name: Leaflet Map
Plugin URI:
Description: A plugin for creating a Leaflet JS map with a shortcode.
Version: 0.1
Author: Benjamin J DeLong
Author URI:
License: GPL2
*/ | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugin development"
} |
List Taxonomy terms along with their posts
I am trying to make a list of all my posts in a custom post type by the taxonomy term e.g.
Term name 1 \- post 1 \- post 2 \- post 3
Term name 2 \- post 1 \- post 2 \- post 3
Term name 3 \- post 1 \- post 2 \- post 3
I have found the function which lists the terms (get_terms) but can't work out a way to list the terms but also list the posts.
Any help is appreciated | Sorted via `get_terms` and `WP_Query`
<?php
$terms = get_terms("county");
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
$my_query = new WP_Query('post_type=venues&posts_per_page=-1&county='.$term->name);
while ($my_query->have_posts()) : $my_query->the_post();
echo '<h2>'.$term->name.'</h2>';
echo '<ul>';
echo '<li>'.get_the_title().'</li>';
echo '<li>'.get_the_content().'</li>';
echo '</ul>';
endwhile; wp_reset_query();
}
}
?>
I first get a list of the terms (using `get_terms`) and then querying the posts via `WP_Query` using the taxonomy option | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, terms"
} |
Use default value of wp_customizer in theme_mod output?
Is there a way to output the default value of a `wp_customize` text field type using the `echo get_theme_mod ();` without actually going in the Theme Customizer, modifying something and then saving it?
I just read on another stackexchange question that the `get_theme_mod` will only show something after you save it in Theme Customizer. Not being able to output the default value of a `wp_customize` setting seems to defy the purpose of using a default value.
So, back to the question: is there a way to automatically display the default value of a `wp_customize` setting in front-end? | Sadly not - all your customize controls are hooked onto `customize_register`, so they'll only ever come into play when customising the theme for the first time.
`get_theme_mod()` takes a second argument for a "default" value - yes, it means two instances of data in your code, but it's a half-solution.
I guess a more DRY approach would be a coupling of globals & helper functions:
$my_theme_defaults = array(
'foo' => 'bar',
'baz' => 'boo',
);
function my_theme_customize( $wp_customize ) {
global $my_theme_defaults;
$wp_customize->add_setting(
'foo',
array(
'default' => $my_theme_defaults['foo'],
)
);
}
function my_theme_mod( $name ) {
global $my_theme_defaults;
echo get_theme_mod( $name, $my_theme_defaults[ $name ] );
} | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 8,
"tags": "theme customizer, get theme mod"
} |
How to flush rewrite rules on the activation of any plugin
I created a function in functions.php that adds some rewrite rules:
function add_rewrite_rules() {
add_rewrite_rule('events/page/([0-9])*/?', 'index.php?pagename=events&paged=$matches[1]', 'top');
[...]
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
I would like to execute it every time _any_ plugin is activated, so if the new rules get overwritten I can restore them automatically. Is it possible?
Thank you. | 1. Add your rewrite rules on the `init` action hook.
2. In your personal activation function, both a) add the rewrite rules and b) flush the rewrite rules. One time. This is the only time you need to flush the rules.
Alternatively, if your rewrite rules can change through user input, then you need to flush them when the rules change, not at any other time. You still need to add them on `init` though. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "rewrite rules"
} |
Different customer login form than administrator login form?
I've recently installed Woocommerce. I have realized that the administrator can access the back-end through the same login form presented to the customers. This, to me, presents a huge security risk.
I thought of a couple of solutions, but I do not know the code that would help me implement them:
* How can I prevent the administrators from logging in through the customer login page? (if statement on login from the customer login form that would check the role of the user and prevent login if the user is an admin)
* How can I present a login form so that only the customers can login through? (use a default or native login form set only for customers) | Although users have access to go to /wp-admin/, they will not have access to do anything on there. There is no security risk involved to being able to have access /wp-admin/ for WooCommerce users.
If you'd like however, you can setup an Apache protected directory with a password to /wp-admin/ that requires an additional user and pass to get to that URL. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "admin, user roles, woocommerce offtopic, wp login form"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.