qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
219,357 | <p>For a redirect in CF7, on_sent_ok: "location.replace('<a href="https://www.mywebsite.com/pageid" rel="nofollow">https://www.mywebsite.com/pageid</a>')" works well in the additional settings but I need to make my website more portable. I would like to use a function to call base_url() or home_url(). Instead of writing out <a href="http://www.mywebsite.com/pageid" rel="nofollow">http://www.mywebsite.com/pageid</a>, I would rather use on_sent_ok: "function('pageid')."</p>
<p>I have tried adding a JS to the page template:</p>
<pre><code><script type="text/javascript">
function PgRedirect($pageid) {
var url=''
url= "<?php echo home_url($pageid)?>";
window.location = url;
</script>
</code></pre>
<p>This does not work. I have tried adding a function to functions.php:</p>
<pre><code>function wpcf7_pg_redirect($pageid){
wp_redirect(home_url($pageid));
exit();
}
add_action('wpcf7_mail_sent', 'wpcf7_pg_redirect');
</code></pre>
<p>This does not work either. I am not sure what I am missing here. Any tips would be appreciated.</p>
| [
{
"answer_id": 219359,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to get the URL of any type of post, including pages, you should use <a href=\"https://developer.w... | 2016/03/01 | [
"https://wordpress.stackexchange.com/questions/219357",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82889/"
] | For a redirect in CF7, on\_sent\_ok: "location.replace('<https://www.mywebsite.com/pageid>')" works well in the additional settings but I need to make my website more portable. I would like to use a function to call base\_url() or home\_url(). Instead of writing out <http://www.mywebsite.com/pageid>, I would rather use on\_sent\_ok: "function('pageid')."
I have tried adding a JS to the page template:
```
<script type="text/javascript">
function PgRedirect($pageid) {
var url=''
url= "<?php echo home_url($pageid)?>";
window.location = url;
</script>
```
This does not work. I have tried adding a function to functions.php:
```
function wpcf7_pg_redirect($pageid){
wp_redirect(home_url($pageid));
exit();
}
add_action('wpcf7_mail_sent', 'wpcf7_pg_redirect');
```
This does not work either. I am not sure what I am missing here. Any tips would be appreciated. | If you need to get the URL of any type of post, including pages, you should use [`get_permalink()`](https://developer.wordpress.org/reference/functions/get_permalink/) function, which returns the canonical URL of the post/page taken care of WordPress permalink configuration.
Using `home_url()` or `base_url()` to get a page permalink is bad idea because you can not be sure if you are getting the caninical URL of the page. Also, `home_url($pageid)` is wrong, `home_url()` accepts a path to be appended to the home url bu a page ID is not a path.
So, use `get_permalink()`:
```
echo get_permalink( $pageid );
```
If you are going to print it within inline JavaScript, you should use also [`esc_js()`](https://codex.wordpress.org/Function_Reference/esc_js) to escape the string. Or, if you are going to use it for a redirection, [esc\_url\_raw()](https://codex.wordpress.org/Function_Reference/esc_url_raw):
```
function wpcf7_pg_redirect($pageid){
wp_redirect( esc_url_raw( get_permalink( $pageid ) ) );
exit();
}
add_action('wpcf7_mail_sent', 'wpcf7_pg_redirect');
```
Or, if you want it to work with the ajax request (filter suggested by @userauser):
```
add_filter('wpcf7_ajax_json_echo', 'cf7_custom_redirect_uri', 10, 2);
function cf7_custom_redirect_uri($items, $result) {
if ( $some_condition_is_true ) {
$redirect_to = get_permalink( $pageid );
$items['onSentOk'] = "location.replace('{" . esc_js( $redirect_to ) . "}')";
}
}
``` |
219,365 | <p>I bought a wordpress theme and I am not able to display the category link and name.</p>
<pre><code><div class="item-info">';
if($show_aut!='0'){
$author = get_author_posts_url( get_the_author_meta( 'ID' ) );
$html .='<span class="item-author"><a href="'.$author.'"title="'.get_the_author().'">'.get_the_author().'</a></span>';}
//DISPLAY CATEGORY LINK AND NAME
if($show_sub_aut!='0'){
$subaut = get_the_category();
$html .= '<span class="item-sub-aut"><a href="'.$subaut.'" title="'.get_category_link().'">'.get_category_link().'</a></span>';}
if($show_date!='0'){
$html .= '<span class="item-date">'.get_the_time(get_option('date_format')).'</span>';}
$html .= '</div>
</div>';
</code></pre>
| [
{
"answer_id": 219359,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to get the URL of any type of post, including pages, you should use <a href=\"https://developer.w... | 2016/03/01 | [
"https://wordpress.stackexchange.com/questions/219365",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89777/"
] | I bought a wordpress theme and I am not able to display the category link and name.
```
<div class="item-info">';
if($show_aut!='0'){
$author = get_author_posts_url( get_the_author_meta( 'ID' ) );
$html .='<span class="item-author"><a href="'.$author.'"title="'.get_the_author().'">'.get_the_author().'</a></span>';}
//DISPLAY CATEGORY LINK AND NAME
if($show_sub_aut!='0'){
$subaut = get_the_category();
$html .= '<span class="item-sub-aut"><a href="'.$subaut.'" title="'.get_category_link().'">'.get_category_link().'</a></span>';}
if($show_date!='0'){
$html .= '<span class="item-date">'.get_the_time(get_option('date_format')).'</span>';}
$html .= '</div>
</div>';
``` | If you need to get the URL of any type of post, including pages, you should use [`get_permalink()`](https://developer.wordpress.org/reference/functions/get_permalink/) function, which returns the canonical URL of the post/page taken care of WordPress permalink configuration.
Using `home_url()` or `base_url()` to get a page permalink is bad idea because you can not be sure if you are getting the caninical URL of the page. Also, `home_url($pageid)` is wrong, `home_url()` accepts a path to be appended to the home url bu a page ID is not a path.
So, use `get_permalink()`:
```
echo get_permalink( $pageid );
```
If you are going to print it within inline JavaScript, you should use also [`esc_js()`](https://codex.wordpress.org/Function_Reference/esc_js) to escape the string. Or, if you are going to use it for a redirection, [esc\_url\_raw()](https://codex.wordpress.org/Function_Reference/esc_url_raw):
```
function wpcf7_pg_redirect($pageid){
wp_redirect( esc_url_raw( get_permalink( $pageid ) ) );
exit();
}
add_action('wpcf7_mail_sent', 'wpcf7_pg_redirect');
```
Or, if you want it to work with the ajax request (filter suggested by @userauser):
```
add_filter('wpcf7_ajax_json_echo', 'cf7_custom_redirect_uri', 10, 2);
function cf7_custom_redirect_uri($items, $result) {
if ( $some_condition_is_true ) {
$redirect_to = get_permalink( $pageid );
$items['onSentOk'] = "location.replace('{" . esc_js( $redirect_to ) . "}')";
}
}
``` |
219,381 | <p>I'm working on a WordPress site and I use the following code to show posts in two columns on archive and category pages:</p>
<pre><code><div id="post-<?php the_ID(); ?>" <?php post_class( 0 === ++$GLOBALS['wpdb']->current_post % 2 ? 'grid col-340 fit' : 'grid col-340' ); ?>>
</code></pre>
<p>With debug set to "true" I got the following notice:</p>
<blockquote>
<p>Notice: Undefined property: wpdb::$current_post in D:\beta\www.beta.dev\wp-includes\wp-db.php on line 684</p>
</blockquote>
<p>What can be wrong with this code? I noticed that this notice appeared with WordPress version 4+</p>
<p>Any help will be greatly appreciated. Thanks.</p>
| [
{
"answer_id": 219383,
"author": "user3114253",
"author_id": 76325,
"author_profile": "https://wordpress.stackexchange.com/users/76325",
"pm_score": -1,
"selected": false,
"text": "<p>use <code>get_the_ID()</code> to get the current post id </p>\n\n<pre><code><?php echo get_the_ID(); ... | 2016/03/01 | [
"https://wordpress.stackexchange.com/questions/219381",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33903/"
] | I'm working on a WordPress site and I use the following code to show posts in two columns on archive and category pages:
```
<div id="post-<?php the_ID(); ?>" <?php post_class( 0 === ++$GLOBALS['wpdb']->current_post % 2 ? 'grid col-340 fit' : 'grid col-340' ); ?>>
```
With debug set to "true" I got the following notice:
>
> Notice: Undefined property: wpdb::$current\_post in D:\beta\www.beta.dev\wp-includes\wp-db.php on line 684
>
>
>
What can be wrong with this code? I noticed that this notice appeared with WordPress version 4+
Any help will be greatly appreciated. Thanks. | There are problems with this part:
```
++$GLOBALS['wpdb']->current_post
```
There's no `current_post` property of the `wpdb` class, here you're most likely confusing the `wpdb` class with the `WP_Query` class.
Also we wouldn't want in general to modify the `current_post` property of the global `WP_Query`, it could surely "bite us" if we mess with the globals ;-)
Note that the `current_post` property of `WP_Query` is already doing the counting for us with `$this->current_post++`; inside `next_post()`, that's called within `the_post()`. See [here](https://github.com/WordPress/WordPress/blob/5a7a3bb9245ca84467d36c7a1a96129c0dbd10af/wp-includes/query.php#L3846). So there's no need to increase it manually (++) within the loop.
Here's an example using the `post_class` filter, with the help of a *static* variable:
```
add_filter( 'post_class', function( $classes )
{
static $instance = 0;
if( in_the_loop() )
$classes[] = ( 0 === $instance++ % 2 ) ? 'even' : 'odd';
return $classes;
} );
```
where we target post classes in the main query loop. Just remember to modify the even/odd classes and other restrictions to your needs.
Using the `post_class` filter could mean better re-usability for our template parts.
Update
------
It looks like you're using the first version of @toscho's one-liner [answer](https://wordpress.stackexchange.com/a/44976/26350), creating a custom `current_post` property (for counting) of the global `wpdb` object. He suggested then to use the prefixed custom property, like `wpse_post_counter`. But it looks like it needs an initialization to avoid the PHP notice.
@kaiser did post a great answer [here](https://wordpress.stackexchange.com/a/44908/26350) that uses the `current_post` property of the global `$wp_query` (probably not the global `$wpdb`).
Since I gave a [promise here](https://wordpress.stackexchange.com/questions/218474/display-different-smiley-when-entering/218496#comment319921_218496), regarding *anonymous* functions and *global* variables, I should rewrite it to: See my [edit here](https://wordpress.stackexchange.com/a/44908/26350)
- where we use the `use` keyword to pass on the global `$wp_query` object. |
219,391 | <p>I wish that my 'custom post type archive page' would point to Page.</p>
<p>The situations is as follows:</p>
<p>I have <code>Page</code> in Wordpress with permalink <code>http://myurl.com/galleries</code>. This page shows list of posts with custom post type = <code>vmgallery</code>. I have custom logic for this page that is working fine. </p>
<p>From another view, this page works like "custom post type archive page", because it displays all posts for given custom post type vmgallery. Currently, if user goes to <a href="http://myurl.com/vmgallery/" rel="nofollow">http://myurl.com/vmgallery/</a> wordpress is loading archive page (archive.php), instead, I wish <code>http://myurl.com/galleries</code> page is loaded. </p>
<p>How to achieve this?</p>
| [
{
"answer_id": 219392,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 5,
"selected": true,
"text": "<p>You have multiple options here.</p>\n\n<p><strong>1. Define post type archive slug on post type registration</st... | 2016/03/01 | [
"https://wordpress.stackexchange.com/questions/219391",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35268/"
] | I wish that my 'custom post type archive page' would point to Page.
The situations is as follows:
I have `Page` in Wordpress with permalink `http://myurl.com/galleries`. This page shows list of posts with custom post type = `vmgallery`. I have custom logic for this page that is working fine.
From another view, this page works like "custom post type archive page", because it displays all posts for given custom post type vmgallery. Currently, if user goes to <http://myurl.com/vmgallery/> wordpress is loading archive page (archive.php), instead, I wish `http://myurl.com/galleries` page is loaded.
How to achieve this? | You have multiple options here.
**1. Define post type archive slug on post type registration**
By setting `'has_archive' => 'galleries'` you can define custom post type archive slug.
Check [documentation](https://codex.wordpress.org/Function_Reference/register_post_type#has_archive).
Then you can delete your page "galleries" then add & customize the `archive-post_type.php`
**2. Disable default archive for post type**
Disable the archive by setting `'has_archive' => false` then keep the page for the post type archive.
**3. Redirect archive requests to your page**
You can permanent redirect default archive request to your page.
```
function archive_to_custom_archive() {
if( is_post_type_archive( 'post_slug' ) ) {
wp_redirect( home_url( '/galleries/' ), 301 );
exit();
}
}
add_action( 'template_redirect', 'archive_to_custom_archive' );
```
>
> I will say the first method is good!
>
>
> |
219,410 | <p>I'm making a website and it seems that product sku is hidden from product page. I have found how to add it to the catalog (shop) page but I need it to show inside the product page.</p>
<p>So far, by altering the single-product.php, I managed to add it at the end of the page (something we do not want) or before the title on the top left of the page (something we also do not want).</p>
<p>I found no way to add it before the price and below the title of the product.</p>
<p>The code of the themes' single-product.php: </p>
<pre><code> <?php
/**
* Single Product title
*
* This template can be overridden by copying it to yourtheme/woocommerce/single-product/title.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you (the theme developer).
* will need to copy the new files to your theme to maintain compatibility. We try to do this.
* as little as possible, but it does happen. When this occurs the version of the template file will.
* be bumped and the readme will list any important changes.
*
* @see http://docs.woothemes.com/document/template-structure/
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
?>
<?php echo '<div class="sku">' . $product->sku . '</div>'; ?>
</code></pre>
<p>I added the last line.</p>
<p>However, on the theme/woocommerce/single-product/meta.php I can see that sku should be displayed, which is not:</p>
<pre><code><?php
/**
* Single Product Meta
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $post, $product;
?>
<div class="product_meta">
<?php if ( $product->is_type( array( 'simple', 'variable' ) ) && get_option('woocommerce_enable_sku') == 'yes' && $product->get_sku() ) : ?>
<span itemprop="productID" class="sku"><?php _e('SKU:','qns' ); ?> <?php echo $product->get_sku(); ?>.</span>
<?php endif; ?>
<?php echo $product->get_categories( ', ', ' <span class="posted_in">'.__('Category:','qns' ).' ', '.</span>'); ?>
<?php echo $product->get_tags( ', ', ' <span class="tagged_as">'.__('Tags:','qns' ).' ', '.</span>'); ?>
</div>
</code></pre>
<p>Any ideas of how I can show the product SKU number inside the product page?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 219427,
"author": "Joe Dooley",
"author_id": 81789,
"author_profile": "https://wordpress.stackexchange.com/users/81789",
"pm_score": 4,
"selected": true,
"text": "<p>Add this to your functions.php</p>\n\n<pre><code>add_action( 'woocommerce_single_product_summary', 'dev_des... | 2016/03/01 | [
"https://wordpress.stackexchange.com/questions/219410",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89804/"
] | I'm making a website and it seems that product sku is hidden from product page. I have found how to add it to the catalog (shop) page but I need it to show inside the product page.
So far, by altering the single-product.php, I managed to add it at the end of the page (something we do not want) or before the title on the top left of the page (something we also do not want).
I found no way to add it before the price and below the title of the product.
The code of the themes' single-product.php:
```
<?php
/**
* Single Product title
*
* This template can be overridden by copying it to yourtheme/woocommerce/single-product/title.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you (the theme developer).
* will need to copy the new files to your theme to maintain compatibility. We try to do this.
* as little as possible, but it does happen. When this occurs the version of the template file will.
* be bumped and the readme will list any important changes.
*
* @see http://docs.woothemes.com/document/template-structure/
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
?>
<?php echo '<div class="sku">' . $product->sku . '</div>'; ?>
```
I added the last line.
However, on the theme/woocommerce/single-product/meta.php I can see that sku should be displayed, which is not:
```
<?php
/**
* Single Product Meta
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $post, $product;
?>
<div class="product_meta">
<?php if ( $product->is_type( array( 'simple', 'variable' ) ) && get_option('woocommerce_enable_sku') == 'yes' && $product->get_sku() ) : ?>
<span itemprop="productID" class="sku"><?php _e('SKU:','qns' ); ?> <?php echo $product->get_sku(); ?>.</span>
<?php endif; ?>
<?php echo $product->get_categories( ', ', ' <span class="posted_in">'.__('Category:','qns' ).' ', '.</span>'); ?>
<?php echo $product->get_tags( ', ', ' <span class="tagged_as">'.__('Tags:','qns' ).' ', '.</span>'); ?>
</div>
```
Any ideas of how I can show the product SKU number inside the product page?
Thanks in advance. | Add this to your functions.php
```
add_action( 'woocommerce_single_product_summary', 'dev_designs_show_sku', 5 );
function dev_designs_show_sku(){
global $product;
echo 'SKU: ' . $product->get_sku();
}
```
This will output the product SKU below the product title. See image below. The product SKU is VERTEX-SLVR.
[](https://i.stack.imgur.com/kG2GJ.png) |
219,454 | <p>I'm using a dynamic CSS file with PHP extention.</p>
<pre><code>wp_enqueue_style('css', get_template_directory_uri().'/inc/css.php');
</code></pre>
<p>The output:</p>
<pre><code><link rel='stylesheet' id='dynamic-css' href='PATH/inc/css.php?ver=4.4.2' type='text/css' media='all' />
</code></pre>
<p>I'm also using a cache plugin (WP Super Cache).</p>
<p>My question is, is this CSS file cached as PHP or CSS?</p>
| [
{
"answer_id": 220596,
"author": "iantsch",
"author_id": 90220,
"author_profile": "https://wordpress.stackexchange.com/users/90220",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know what you do in your <code>css.php</code> to handle your php cache, but i guess not much. If you ... | 2016/03/02 | [
"https://wordpress.stackexchange.com/questions/219454",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62214/"
] | I'm using a dynamic CSS file with PHP extention.
```
wp_enqueue_style('css', get_template_directory_uri().'/inc/css.php');
```
The output:
```
<link rel='stylesheet' id='dynamic-css' href='PATH/inc/css.php?ver=4.4.2' type='text/css' media='all' />
```
I'm also using a cache plugin (WP Super Cache).
My question is, is this CSS file cached as PHP or CSS? | A great deal of this will depend on your server configuration, but:
Will WP Super Cache cache the css.php output?
---------------------------------------------
Extremely unlikely. If your file simply generates CSS from a few variables, then no.
If however it bootstraps and loads WordPress, then it 'might' cache some things, but I doubt it will work as you expect, or that it will do a full page cache. Here the word 'might' is a stretch at best
Will Other Caching Plugins Cache it?
------------------------------------
Switching to another caching plugin will not change things
Will the Server cache it? Or the Browser?
-----------------------------------------
That depends on the headers sent, and at this point we've moved beyond the scope of WordPress and this stack exchange. The answer is entirely dependent on your setup, and is impossible to answer without making this question useless to other people, or having intimate knowledge of your system
Is What I'm Doing Safe?
-----------------------
No.
If your file bootstraps WordPress, then it will work even when the plugin or theme is disabled, acting as a potential security hole. This is even more true of AJAX endpoints and form handlers. WordPress is a CMS, and all requests should be routed through it. An AJAX API is provided already, and there are rewrite rules and query variables that you can add and detect to output CSS and other things.
If however your `css.php` outputs PHP after doing a small amount of math etc, then you should eliminate it, and simply use a build process to generate a css file. You can use less or sass or some other system to generate the CSS, but it doesn't need distributing to your server |
219,471 | <p>I have a little problem.</p>
<p>This is my page structure:</p>
<pre><code>Ancestor
Parent
Child 1
Child 2
Child 3
Child 4
</code></pre>
<p>What i try to do is when i'm on Child 4 i want to show Child 2. </p>
<p>And when i'm on Child 2 i want to show Parent. </p>
<p>But i can't figure out how to do this.
The code that i use is this:</p>
<pre><code>function wpb_list_child_pages_popup() {
global $post;
if ( is_page() && $post->post_parent )
$childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' );
else
$childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' );
if ( $childpages ) {
$string = '<ul id="child-menu">' . $childpages . '</ul>';
}
return $string;
}
add_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup');
</code></pre>
| [
{
"answer_id": 219482,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": true,
"text": "<p>You need to look at <code>get_ancestors()</code> to get the top level parent of a page. Just a note, for... | 2016/03/02 | [
"https://wordpress.stackexchange.com/questions/219471",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44597/"
] | I have a little problem.
This is my page structure:
```
Ancestor
Parent
Child 1
Child 2
Child 3
Child 4
```
What i try to do is when i'm on Child 4 i want to show Child 2.
And when i'm on Child 2 i want to show Parent.
But i can't figure out how to do this.
The code that i use is this:
```
function wpb_list_child_pages_popup() {
global $post;
if ( is_page() && $post->post_parent )
$childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' );
else
$childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' );
if ( $childpages ) {
$string = '<ul id="child-menu">' . $childpages . '</ul>';
}
return $string;
}
add_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup');
``` | You need to look at `get_ancestors()` to get the top level parent of a page. Just a note, for reliability, use `get_queried_object()` (*or even better `$GLOBALS['wp_the_query']->get_queried_object()`*) to get the current post/page object on singular pages, `$post` can be quite unreliable
You can try the following in your shortcode:
```
$post = $GLOBALS['wp_the_query']->get_queried_object();
// Make sure the current page is not top level
if ( 0 === (int) $post->post_parent ) {
$parent = $post->ID;
} else {
$ancestors = get_ancestors( $post->ID, $post->post_type );
$parent = end( $ancestors );
}
```
`$parent` will now always hold the top level parent of any given page
EDIT - from comments
--------------------
If you need to get the page two levels higher than the current one, you can still use the same approach, but insted of using the last ID from `get\_ancestors (*which is the top level parent*), we need to adjust this to get the second entry
Lets modify the code above slightly
```
$post = $GLOBALS['wp_the_query']->get_queried_object();
// Make sure the current page is not top level
if ( 0 === (int) $post->post_parent ) {
$parent = $post->ID;
} else {
$ancestors = get_ancestors( $post->ID, $post->post_type );
// Check if $ancestors have at least two key/value pairs
if ( 1 == count( $ancestors ) ) {
$parent = $post->post_parent;
} esle {
$parent = $ancestors[1]; // Gets the parent two levels higher
}
}
```
LAST EDIT - full code
---------------------
```
function wpb_list_child_pages_popup()
{
// Define our $string variable
$string = '';
// Make sure this is a page
if ( !is_page() )
return $string;
$post = $GLOBALS['wp_the_query']->get_queried_object();
// Make sure the current page is not top level
if ( 0 === (int) $post->post_parent ) {
$parent = $post->ID;
} else {
$ancestors = get_ancestors( $post->ID, $post->post_type );
// Check if $ancestors have at least two key/value pairs
if ( 1 == count( $ancestors ) ) {
$parent = $post->post_parent;
} else {
$parent = $ancestors[1]; // Gets the parent two levels higher
}
}
$childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $parent . '&echo=0' );
$string .= '<ul id="child-menu">' . $childpages . '</ul>';
return $string;
}
add_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup');
``` |
219,483 | <p>I am adding a <code>#section</code> as a custom link to my menu, because I want to scroll to that section when I click on that link. When I'm on the home page, this works fine (the section is on the home page), but when I'm not, and I click on it nothing happens, because it treats the link as just <code>#section</code>.</p>
<p>That is, when I'm on second page:</p>
<pre><code>http://127.0.0.1/second-page
</code></pre>
<p>and I click on the <code>#section</code> link in the menu, it tries to do</p>
<pre><code>http://127.0.0.1/second-page/#section
</code></pre>
<p>instead of </p>
<pre><code>http://127.0.0.1/#section
</code></pre>
<p>Now, the site is still in development, so it's set via IP address. But that shouldn't matter. The issue is that I've tried to set the custom link in the wordpress backend as</p>
<pre><code>http://127.0.0.1/#section
</code></pre>
<p>and while in the backend this looks like that, on my menu on the front end I only see</p>
<pre><code><a href="#section">Section</a>
</code></pre>
<p>The menu walker that controls the menu output looks like this:</p>
<pre><code><?php
// Allow HTML descriptions in WordPress Menu
remove_filter( 'nav_menu_description', 'strip_tags' );
function my_plugin_wp_setup_nav_menu_item( $menu_item ) {
if ( isset( $menu_item->post_type ) ) {
if ( 'nav_menu_item' == $menu_item->post_type ) {
$menu_item->description = apply_filters( 'nav_menu_description', $menu_item->post_content );
}
}
return $menu_item;
}
add_filter( 'wp_setup_nav_menu_item', 'my_plugin_wp_setup_nav_menu_item' );
// Menu without icons
class my_walker_nav_menu extends Walker_Nav_Menu {
public function display_element($el, &$children, $max_depth, $depth = 0, $args, &$output){
$id = $this->db_fields['id'];
if(isset($children[$el->$id])){
$el->classes[] = 'has_children';
}
parent::display_element($el, $children, $max_depth, $depth, $args, $output);
}
// add classes to ul sub-menus
function start_lvl( &$output, $depth = 0, $args = array() ) {
// depth dependent classes
$indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent
$display_depth = ( $depth + 1); // because it counts the first submenu as 0
$classes = array(
'navi',
( $display_depth ==1 ? 'first' : '' ),
( $display_depth >=2 ? 'navi' : '' ),
'menu-depth-' . $display_depth
);
$class_names = implode( ' ', $classes );
// build html
$output .= "\n" . $indent . '<ul class="' . esc_attr($class_names) . '">' . "\n";
}
// add main/sub classes to li's and links
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
global $wp_query;
$indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent
static $is_first;
$is_first++;
// depth dependent classes
$depth_classes = array(
( $depth == 0 ? 'main-menu-item' : '' ),
( $depth >=2 ? 'navi' : '' ),
( $is_first ==1 ? 'menu-first' : '' ),
'menu-item-depth-' . $depth
);
$depth_class_names = esc_attr( implode( ' ', $depth_classes ) );
// passed classes
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );
$is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false;
$use_desc = (strpos($class_names,'use_desc') !== false) ? true : false;
$no_title = (strpos($class_names,'no_title') !== false) ? true : false;
if(!$is_mega_menu){
$class_names .= ' normal_menu_item';
}
// build html
$output .= $indent . '<li id="nav-menu-item-'. esc_attr($item->ID) . '" class="' . esc_attr($depth_class_names) . ' ' . esc_attr($class_names) . '">';
// link attributes
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . (($item->url[0] == "#" && !is_front_page()) ? home_url('/') : '') . esc_attr($item->url) .'"' : '';
$attributes .= ' class="menu-link '.((strpos($item->url,'#') === false) ? '' : 'scroll').' ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"';
$html_output = ($use_desc) ? '<div class="description_menu_item">'.$item->description.'</div>' : '';
$item_output = (!$no_title) ? '<a ' . $attributes . '><span>' . apply_filters( 'the_title', $item->title, $item->ID ) . '</span></a>'.$html_output : $html_output;
// build html
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ).(($is_mega_menu)?'<div class="sf-mega"><div class="sf-mega-inner clearfix">':'');
}
function end_el( &$output, $item, $depth = 0, $args = array() ) {
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );
$is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false;
$output .= (($is_mega_menu)?'</div></div>':'') . "</li>\n";
}
}
</code></pre>
<p>The anchor is controlled with this line:</p>
<pre><code>$attributes .= ! empty( $item->url ) ? ' href="' . (($item->url[0] == "#" && !is_front_page()) ? home_url('/') : '') . esc_attr($item->url) .'"' : '';
</code></pre>
<p>It even says that if the url has <code>#</code> in it, and if it's not front page, that it should add a <code>home_url()</code> to it.</p>
<p>Without this I cannot scroll to the section on the first page from other pages. </p>
<p>Why is it doing this? Because the address is IP instead of www?</p>
<p><strong>ANSWER</strong></p>
<p>Apparently I didn't call the walker instance in my <code>wp_nav_menu()</code>. <em>feels dumb</em></p>
<p>It works now. Sorry for not checking this sooner.</p>
| [
{
"answer_id": 219482,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": true,
"text": "<p>You need to look at <code>get_ancestors()</code> to get the top level parent of a page. Just a note, for... | 2016/03/02 | [
"https://wordpress.stackexchange.com/questions/219483",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58895/"
] | I am adding a `#section` as a custom link to my menu, because I want to scroll to that section when I click on that link. When I'm on the home page, this works fine (the section is on the home page), but when I'm not, and I click on it nothing happens, because it treats the link as just `#section`.
That is, when I'm on second page:
```
http://127.0.0.1/second-page
```
and I click on the `#section` link in the menu, it tries to do
```
http://127.0.0.1/second-page/#section
```
instead of
```
http://127.0.0.1/#section
```
Now, the site is still in development, so it's set via IP address. But that shouldn't matter. The issue is that I've tried to set the custom link in the wordpress backend as
```
http://127.0.0.1/#section
```
and while in the backend this looks like that, on my menu on the front end I only see
```
<a href="#section">Section</a>
```
The menu walker that controls the menu output looks like this:
```
<?php
// Allow HTML descriptions in WordPress Menu
remove_filter( 'nav_menu_description', 'strip_tags' );
function my_plugin_wp_setup_nav_menu_item( $menu_item ) {
if ( isset( $menu_item->post_type ) ) {
if ( 'nav_menu_item' == $menu_item->post_type ) {
$menu_item->description = apply_filters( 'nav_menu_description', $menu_item->post_content );
}
}
return $menu_item;
}
add_filter( 'wp_setup_nav_menu_item', 'my_plugin_wp_setup_nav_menu_item' );
// Menu without icons
class my_walker_nav_menu extends Walker_Nav_Menu {
public function display_element($el, &$children, $max_depth, $depth = 0, $args, &$output){
$id = $this->db_fields['id'];
if(isset($children[$el->$id])){
$el->classes[] = 'has_children';
}
parent::display_element($el, $children, $max_depth, $depth, $args, $output);
}
// add classes to ul sub-menus
function start_lvl( &$output, $depth = 0, $args = array() ) {
// depth dependent classes
$indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent
$display_depth = ( $depth + 1); // because it counts the first submenu as 0
$classes = array(
'navi',
( $display_depth ==1 ? 'first' : '' ),
( $display_depth >=2 ? 'navi' : '' ),
'menu-depth-' . $display_depth
);
$class_names = implode( ' ', $classes );
// build html
$output .= "\n" . $indent . '<ul class="' . esc_attr($class_names) . '">' . "\n";
}
// add main/sub classes to li's and links
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
global $wp_query;
$indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent
static $is_first;
$is_first++;
// depth dependent classes
$depth_classes = array(
( $depth == 0 ? 'main-menu-item' : '' ),
( $depth >=2 ? 'navi' : '' ),
( $is_first ==1 ? 'menu-first' : '' ),
'menu-item-depth-' . $depth
);
$depth_class_names = esc_attr( implode( ' ', $depth_classes ) );
// passed classes
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );
$is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false;
$use_desc = (strpos($class_names,'use_desc') !== false) ? true : false;
$no_title = (strpos($class_names,'no_title') !== false) ? true : false;
if(!$is_mega_menu){
$class_names .= ' normal_menu_item';
}
// build html
$output .= $indent . '<li id="nav-menu-item-'. esc_attr($item->ID) . '" class="' . esc_attr($depth_class_names) . ' ' . esc_attr($class_names) . '">';
// link attributes
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . (($item->url[0] == "#" && !is_front_page()) ? home_url('/') : '') . esc_attr($item->url) .'"' : '';
$attributes .= ' class="menu-link '.((strpos($item->url,'#') === false) ? '' : 'scroll').' ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"';
$html_output = ($use_desc) ? '<div class="description_menu_item">'.$item->description.'</div>' : '';
$item_output = (!$no_title) ? '<a ' . $attributes . '><span>' . apply_filters( 'the_title', $item->title, $item->ID ) . '</span></a>'.$html_output : $html_output;
// build html
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ).(($is_mega_menu)?'<div class="sf-mega"><div class="sf-mega-inner clearfix">':'');
}
function end_el( &$output, $item, $depth = 0, $args = array() ) {
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );
$is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false;
$output .= (($is_mega_menu)?'</div></div>':'') . "</li>\n";
}
}
```
The anchor is controlled with this line:
```
$attributes .= ! empty( $item->url ) ? ' href="' . (($item->url[0] == "#" && !is_front_page()) ? home_url('/') : '') . esc_attr($item->url) .'"' : '';
```
It even says that if the url has `#` in it, and if it's not front page, that it should add a `home_url()` to it.
Without this I cannot scroll to the section on the first page from other pages.
Why is it doing this? Because the address is IP instead of www?
**ANSWER**
Apparently I didn't call the walker instance in my `wp_nav_menu()`. *feels dumb*
It works now. Sorry for not checking this sooner. | You need to look at `get_ancestors()` to get the top level parent of a page. Just a note, for reliability, use `get_queried_object()` (*or even better `$GLOBALS['wp_the_query']->get_queried_object()`*) to get the current post/page object on singular pages, `$post` can be quite unreliable
You can try the following in your shortcode:
```
$post = $GLOBALS['wp_the_query']->get_queried_object();
// Make sure the current page is not top level
if ( 0 === (int) $post->post_parent ) {
$parent = $post->ID;
} else {
$ancestors = get_ancestors( $post->ID, $post->post_type );
$parent = end( $ancestors );
}
```
`$parent` will now always hold the top level parent of any given page
EDIT - from comments
--------------------
If you need to get the page two levels higher than the current one, you can still use the same approach, but insted of using the last ID from `get\_ancestors (*which is the top level parent*), we need to adjust this to get the second entry
Lets modify the code above slightly
```
$post = $GLOBALS['wp_the_query']->get_queried_object();
// Make sure the current page is not top level
if ( 0 === (int) $post->post_parent ) {
$parent = $post->ID;
} else {
$ancestors = get_ancestors( $post->ID, $post->post_type );
// Check if $ancestors have at least two key/value pairs
if ( 1 == count( $ancestors ) ) {
$parent = $post->post_parent;
} esle {
$parent = $ancestors[1]; // Gets the parent two levels higher
}
}
```
LAST EDIT - full code
---------------------
```
function wpb_list_child_pages_popup()
{
// Define our $string variable
$string = '';
// Make sure this is a page
if ( !is_page() )
return $string;
$post = $GLOBALS['wp_the_query']->get_queried_object();
// Make sure the current page is not top level
if ( 0 === (int) $post->post_parent ) {
$parent = $post->ID;
} else {
$ancestors = get_ancestors( $post->ID, $post->post_type );
// Check if $ancestors have at least two key/value pairs
if ( 1 == count( $ancestors ) ) {
$parent = $post->post_parent;
} else {
$parent = $ancestors[1]; // Gets the parent two levels higher
}
}
$childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $parent . '&echo=0' );
$string .= '<ul id="child-menu">' . $childpages . '</ul>';
return $string;
}
add_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup');
``` |
219,531 | <p>Hi I have created two custom fields - both of them should be required, but when I fill out username and correct email, the error messages are skipped and user gets registered. If there is an error in username or email, it writes the messages correctly. Could anybody give me a helping hand?</p>
<pre><code>//1. Add a new form element...
add_action( 'register_form', 'myplugin_register_form' );
function myplugin_register_form() {
$first_name = ( ! empty( $_POST['first_name'] ) ) ? trim( $_POST['first_name'] ) : '';
?>
<p>
<label for="first_name"><?php _e( 'Jméno a příjmení', 'faveaplus' ) ?><br />
<input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr( wp_unslash( $first_name ) ); ?>" size="25" /></label>
</p>
<p>
<label for="subscribe">
<input type="checkbox" name="subscribe" value="1" />
Prohlašuji, že jsem pracovník ve zdravotnictví s oprávněním předepisovat nebo vydávat humánní léčivé přípravky (lékař nebo farmaceut).
</label>
</p>
<?php
}
//2. Add validation. In this case, we make sure first_name is required.
add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );
function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {
if ( empty( $_POST['first_name'] ) || ! empty( $_POST['first_name'] ) && trim( $_POST['first_name'] ) == '' ) {
$errors->add( 'first_name_error', __( '<strong>CHYBA</strong>: Musíte uvést své jméno a příjmení.', 'faveaplus' ) );
}
if ($_POST['subscribe'] != "checked") {
$errors->add( 'subscribe_error', __( '<strong>CHYBA</strong>: Musíte prohlásit, že jste pracovník ve zdravotnictví', 'faveaplus' ) );
}
return $errors;
}
</code></pre>
| [
{
"answer_id": 219535,
"author": "locomo",
"author_id": 42754,
"author_profile": "https://wordpress.stackexchange.com/users/42754",
"pm_score": 1,
"selected": false,
"text": "<p>the value of the checkbox wouldn't be \"checked\" - it should equal whatever you put in the \"value\" attribut... | 2016/03/02 | [
"https://wordpress.stackexchange.com/questions/219531",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64771/"
] | Hi I have created two custom fields - both of them should be required, but when I fill out username and correct email, the error messages are skipped and user gets registered. If there is an error in username or email, it writes the messages correctly. Could anybody give me a helping hand?
```
//1. Add a new form element...
add_action( 'register_form', 'myplugin_register_form' );
function myplugin_register_form() {
$first_name = ( ! empty( $_POST['first_name'] ) ) ? trim( $_POST['first_name'] ) : '';
?>
<p>
<label for="first_name"><?php _e( 'Jméno a příjmení', 'faveaplus' ) ?><br />
<input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr( wp_unslash( $first_name ) ); ?>" size="25" /></label>
</p>
<p>
<label for="subscribe">
<input type="checkbox" name="subscribe" value="1" />
Prohlašuji, že jsem pracovník ve zdravotnictví s oprávněním předepisovat nebo vydávat humánní léčivé přípravky (lékař nebo farmaceut).
</label>
</p>
<?php
}
//2. Add validation. In this case, we make sure first_name is required.
add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );
function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {
if ( empty( $_POST['first_name'] ) || ! empty( $_POST['first_name'] ) && trim( $_POST['first_name'] ) == '' ) {
$errors->add( 'first_name_error', __( '<strong>CHYBA</strong>: Musíte uvést své jméno a příjmení.', 'faveaplus' ) );
}
if ($_POST['subscribe'] != "checked") {
$errors->add( 'subscribe_error', __( '<strong>CHYBA</strong>: Musíte prohlásit, že jste pracovník ve zdravotnictví', 'faveaplus' ) );
}
return $errors;
}
``` | I've found my answer - unfortunatelly I've forgotten to mention that I'm using **at same time the plugin New User Approve** and that's what has been causing the problem of accepting before firing errors. Finally, thanks to @locomo I have google the right thing.
Answer found here: <https://wordpress.org/support/topic/registration_errors-filter-problem>
>
> The new user is created in send\_approval\_email(). This function is
> called using the register\_post action hook. Unfortunately,
> register\_post fires before registration\_errors so there is no way to
> validate data.
>
>
>
**The solution:**
replace this code (adding the validation):
```
add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );
```
with following
```
add_filter( 'register_post', 'myplugin_registration_errors', 9, 3 );
```
two changes have been made: `registration_errors` become `register_post` and `10` has been changed to `9` to have it fired at the right time. |
219,567 | <p>I am try to hide the metabox fields with empty value like</p>
<pre>
$Product_Brennwert = get_post_meta(get_the_ID(), 'Product_Brennwert', true);
if ( ! empty ( $Product_Brennwert ) ) {
echo 'Brennwert
'. $Product_power . '
';
}
</pre>
<p>now i am try to add this in my php file but no idea how to add this in table can some on help me to do this?</p>
<p>part of my php file
<a href="http://pastebin.com/etJHPb0u" rel="nofollow">Single.PHP </a></p>
| [
{
"answer_id": 219536,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>The two overarching advantages are:</p>\n\n<ol>\n<li>You can (eventually) do all admin tasks without the admin int... | 2016/03/03 | [
"https://wordpress.stackexchange.com/questions/219567",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24876/"
] | I am try to hide the metabox fields with empty value like
```
$Product_Brennwert = get_post_meta(get_the_ID(), 'Product_Brennwert', true);
if ( ! empty ( $Product_Brennwert ) ) {
echo 'Brennwert
'. $Product_power . '
';
}
```
now i am try to add this in my php file but no idea how to add this in table can some on help me to do this?
part of my php file
[Single.PHP](http://pastebin.com/etJHPb0u) | At its current state, it is a badly engineered feature that do not have any real advantage for a competent developer.
The basic idea, as it stands at the time this answer is written, is to expose WordPress core functionality as JSON REST API. This will enable decoupling of the WordPress "business" logic from the UI and enable creating different full or partial UIs to manage and extract information from wordpress. This by itself is not a revolution, but an evolution. just a replacement of the XML-RPC API which by itself kinda streamlines the HTTP based for submission API.
As with any evolution, at each step you might ask yourself, what advantage do you get from the former state, and the answer is probably "not much", but hopefully the steps do accumulate to a big difference.
So why the negative preface to this answer? Because my experience as software developer is that it is rarely possible to design a generic API that is actually useful without having concrete use cases to answer to. A concrete use case here can be replacing the XML-RPC API for automated wordpress management, but any front end related has to be site specific and since there is a huge performance penalty for every request sent from the client to the server you can not just aggregate use of different API to get the result you want in a way in which the users will remain happy. This means that for front end, for non trivial usage, there will still be very little difference in development effort between using the AJAX route and the REST-API route. |
219,568 | <p>I would like to have 0 to 5, and "n/a" as possible values, however this code will output "n/a" when I want it to output a zero. How can I get it to output "0"?</p>
<p>("n/a" is the placeholder if no value is set.)</p>
<pre><code>Difficulty: <?php if(get_field('difficulty')) { echo the_field('difficulty');} else { echo "n/a"; } ?>
</code></pre>
| [
{
"answer_id": 219570,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": -1,
"selected": true,
"text": "<p>In PHP, <code>0 == false == [] == '' == null</code>. A simple check to check if a variable or condition... | 2016/03/03 | [
"https://wordpress.stackexchange.com/questions/219568",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87385/"
] | I would like to have 0 to 5, and "n/a" as possible values, however this code will output "n/a" when I want it to output a zero. How can I get it to output "0"?
("n/a" is the placeholder if no value is set.)
```
Difficulty: <?php if(get_field('difficulty')) { echo the_field('difficulty');} else { echo "n/a"; } ?>
``` | In PHP, `0 == false == [] == '' == null`. A simple check to check if a variable or condition has a value will return `false` if the value is equal to 0.
For `0` to return true as a valid value, you would need to make use of strict comparison by using the identical (*`===`*) operator. Just remember, if you use `===`, not only the value must match, but the type as well, otherwise the condition will return false. If your values are a string, you should use `'0'`, if they are integer values (*which I doubt as custom field values are strings as single values*), you should use `0`.
You can do the following check
```
$difficulty = get_field( 'difficulty' );
if ( $difficulty // Check if we have a valid value
|| '0' === $difficulty // This assumes '0' to be string, if integer, change to 0
) {
$value = $difficulty;
} else {
$value = 'n/a';
}
echo 'Difficulty: ' . $value;
``` |
219,583 | <p>I have a custom form that allows users to make posts and also upload images with it.
The images are saved in <code>wp_posts</code> as post_type = <code>attachment</code> with a <code>guid</code> to show the image.</p>
<p>Now I have created a grid created with php which shows all main pictures of my posts. However, since I call the guid's of the images it loads very slow when the pictures are large.</p>
<p>I know that there is some smaller thumbnail that should get saved with each image upload, but I cannot find these files in the database.</p>
<p>I tried showing them with all of the following ways:</p>
<pre><code>//test with ID of the post:
get_the_post_thumbnail('17547');
get_the_post_thumbnail(17547, 'thumbnail');
get_the_post_thumbnail(17547, 'medium');
//test with ID of the attachment:
wp_get_attachment_image(17548, 'medium' );
wp_get_attachment_image_src(17548, 'medium' );
</code></pre>
<p>The two different numbers are because i tried the post ID and the attachement ID. But all of the above functions don't show me anything in the DOM...</p>
<p><strong>I think that maybe the way I save the pictures doesn't allows me to use this function.</strong> But I don't know what I'm doing wrong! Does anyone know where I can look or how I can show these thumbnails?</p>
<p>This is how my photo grid is made:<br>
<strong>①</strong> First I get a list of ID's based on what the user searches:</p>
<pre><code>$allluca01 = $wpdb->get_results("
SELECT wpp.ID, post_title
FROM wp_posts AS wpp
WHERE post_type = 'post'
".$plus_other_search_conditions."
GROUP BY wpp.ID
");
</code></pre>
<p><strong>②</strong> Then I get the guid of the image. I have the attachment id saved as metavalue to a metakey called image01 (linked to post_id).</p>
<pre><code>foreach($sqlsearchquery as $results){
$resultid = $results->ID;
$getpicture = $wpdb->get_results("
SELECT guid AS pic
FROM wp_posts
LEFT JOIN wp_postmeta ON ID = meta_value
WHERE post_id = '$resultid' AND meta_key = 'item_image01'
");
<div class="grid_item_img" style="background-image:url('<? echo $getpicture[0]->pic; ?>')">
</code></pre>
<p>As you can see I attain the <strong>guid</strong> and then I use it in my grid. <strong>I just want to obtain a guid of a smaller size of my media</strong> so I can have the grid load faster. Does anyone know how to do that?</p>
| [
{
"answer_id": 219587,
"author": "Prasad Nevase",
"author_id": 62283,
"author_profile": "https://wordpress.stackexchange.com/users/62283",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure how you have implemented the image upload in custom form. If you have followed standard w... | 2016/03/03 | [
"https://wordpress.stackexchange.com/questions/219583",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87968/"
] | I have a custom form that allows users to make posts and also upload images with it.
The images are saved in `wp_posts` as post\_type = `attachment` with a `guid` to show the image.
Now I have created a grid created with php which shows all main pictures of my posts. However, since I call the guid's of the images it loads very slow when the pictures are large.
I know that there is some smaller thumbnail that should get saved with each image upload, but I cannot find these files in the database.
I tried showing them with all of the following ways:
```
//test with ID of the post:
get_the_post_thumbnail('17547');
get_the_post_thumbnail(17547, 'thumbnail');
get_the_post_thumbnail(17547, 'medium');
//test with ID of the attachment:
wp_get_attachment_image(17548, 'medium' );
wp_get_attachment_image_src(17548, 'medium' );
```
The two different numbers are because i tried the post ID and the attachement ID. But all of the above functions don't show me anything in the DOM...
**I think that maybe the way I save the pictures doesn't allows me to use this function.** But I don't know what I'm doing wrong! Does anyone know where I can look or how I can show these thumbnails?
This is how my photo grid is made:
**①** First I get a list of ID's based on what the user searches:
```
$allluca01 = $wpdb->get_results("
SELECT wpp.ID, post_title
FROM wp_posts AS wpp
WHERE post_type = 'post'
".$plus_other_search_conditions."
GROUP BY wpp.ID
");
```
**②** Then I get the guid of the image. I have the attachment id saved as metavalue to a metakey called image01 (linked to post\_id).
```
foreach($sqlsearchquery as $results){
$resultid = $results->ID;
$getpicture = $wpdb->get_results("
SELECT guid AS pic
FROM wp_posts
LEFT JOIN wp_postmeta ON ID = meta_value
WHERE post_id = '$resultid' AND meta_key = 'item_image01'
");
<div class="grid_item_img" style="background-image:url('<? echo $getpicture[0]->pic; ?>')">
```
As you can see I attain the **guid** and then I use it in my grid. **I just want to obtain a guid of a smaller size of my media** so I can have the grid load faster. Does anyone know how to do that? | You can use several functions to get the URL of a image of any of the intermediate sizes created by WordPress (thumbnail, medium, large, full, or any other [custom size](https://developer.wordpress.org/reference/functions/add_image_size/)).
You can use `get_the_post_thumbnail()`/`the_post_thumbnail()`: use this function if you want **to get a `<img>` element of the featured image of a post (aka "post thumbnail")**. For example, to get the featured image, medium szie, of the post with ID 78:
```
$featured_image = get_the_post_thumbanil( 78, 'medium' );
echo $featured_image;
```
If you are within the loop, you can display the post thumbnail, medium size, of the current post as follow:
```
// Don't need echo
the_post_thumbnail( 'medium' );
```
If no image size is set, `get_the_post_thumbanil()`/`the_post_thumbnail()` use `post-thumbnail`, which is [the size registered for the post thumbanil](https://codex.wordpress.org/Function_Reference/set_post_thumbnail_size) (featured image).
If you want **to get a `<img>` element of any image**, not the post thumbnail (featured image), use `wp_get_attachment_image()`. For example, if the attachement has ID of 7898 and you want to get medium size `<img>`:
```
echo wp_get_attachment_image( 7898, 'medium' );
```
You can also use `wp_get_attachment_image_src()` if you only want to get the URL of any image (but not a `<img>` element):
```
$image_url = wp_get_attachment_image_src( $id_of_the_attachment, $size );
```
For example, if the attachement has ID of 7898 and you want to get medium size URL:
```
$image_url = wp_get_attachment_image_src( 7898, 'medium' );
```
In you custom query, you could select the attachment ID instead of the `guid` and use this attachment ID with `wp_get_attachment_image()` and `wp_get_attachment_image_src()`.
Anyway, **you should avoid that custom SQL queries**. You are missing important WordPress hooks and several functions, template tags, filters on content, embeds, etc, won't wrok. If you want to work with WordPress posts within WordPress, the best choice is to use [`get_posts()`](https://codex.wordpress.org/Class_Reference/WP_Query) o or a new instance of [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query).
Now, **to directly answer your question**: the attachment files, including the intermediate sizes of images, are stored in `wp-content/uploads` folder. The database keeps information of the attachement post type, but the files are not in database. |
219,613 | <p>I'm making a page for settings API using Codestar Framework, and loading fields using their <a href="http://codestarframework.com/documentation/#configuration" rel="nofollow">filterable configure</a> - <strong>question is not related to Codestar</strong>. In one of such dropdown field, I need to load all the posts from a custom post type that are added within 30 days. To make the things nice and clean I made a custom function:</p>
<pre><code><?php
/**
* Get posts of last 30 days only.
*
* @return array Array of posts.
* --------------------------------------------------------------------------
*/
function pre_get_active_posts_of_30_days() {
//admin-only function
if( !is_admin() )
return;
global $project_prefix; //set a project prefix (i.e. pre_)
$latest_posts = new WP_Query(
array(
'post_type' => 'cpt',
'post_status' => 'publish',
'posts_per_page' => -1,
'date_query' => array(
array(
'after' => '30 days ago',
'inclusive' => true,
),
)
)
);
$posts_this_month = array();
if( $latest_posts->have_posts() ) : while( $latest_posts->have_posts() ) : $latest_posts->the_post();
$validity_type = get_post_meta( get_the_ID(), "{$project_prefix}validity_type", true );
if( $validity_type && 'validity date' === $validity_type ) {
$validity = get_post_meta( get_the_ID(), "{$project_prefix}validity", true );
$tag = days_until( $validity ) .' days left'; //custom function
} else if( $validity_type && 'validity stock' === $validity_type ) {
$tag = 'Stock';
} else {
$tag = '...';
}
$posts_this_month[get_the_ID()] = get_the_title() .' ['. $tag .']';
endwhile; endif; wp_reset_postdata();
return $posts_this_month;
}
</code></pre>
<p>Question is not even with the function.</p>
<p>I want to do the query <strong>only on that particular top_level_custom-settings-api page</strong>. The function is loading on every page load of admin. I tried using <code>get_current_screen()</code> but this function's giving me not found fatal error.</p>
<h3>Edit</h3>
<p>No @bonger, I remembered that. I tried your code in this way:</p>
<pre><code>add_action('current_screen', 'current_screen_callback');
function current_screen_callback($screen) {
if( is_object($screen) && $screen->id == 'top_level_custom-settings-api' ) {
add_action( 'admin_init', 'pre_get_active_posts_of_30_days' );
}
}
</code></pre>
<p>The code does work well, but it doesn't control my function loading only on that particular page. I checked the query on other pages, the query is there too. And I tried changing the conditional to something wrong, like <code>$screen->id == 'top_level_-api'</code>, it still works that way. :(</p>
<p>I'm afraid, I know I have a serious lack in behind-the-scene action and filter things. Would love to have a good read for that too.</p>
| [
{
"answer_id": 220258,
"author": "Adam",
"author_id": 13418,
"author_profile": "https://wordpress.stackexchange.com/users/13418",
"pm_score": 2,
"selected": false,
"text": "<p>It's worthwhile pointing out that using <code>admin_init</code> within the <code>current_screen</code> filter is... | 2016/03/03 | [
"https://wordpress.stackexchange.com/questions/219613",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22728/"
] | I'm making a page for settings API using Codestar Framework, and loading fields using their [filterable configure](http://codestarframework.com/documentation/#configuration) - **question is not related to Codestar**. In one of such dropdown field, I need to load all the posts from a custom post type that are added within 30 days. To make the things nice and clean I made a custom function:
```
<?php
/**
* Get posts of last 30 days only.
*
* @return array Array of posts.
* --------------------------------------------------------------------------
*/
function pre_get_active_posts_of_30_days() {
//admin-only function
if( !is_admin() )
return;
global $project_prefix; //set a project prefix (i.e. pre_)
$latest_posts = new WP_Query(
array(
'post_type' => 'cpt',
'post_status' => 'publish',
'posts_per_page' => -1,
'date_query' => array(
array(
'after' => '30 days ago',
'inclusive' => true,
),
)
)
);
$posts_this_month = array();
if( $latest_posts->have_posts() ) : while( $latest_posts->have_posts() ) : $latest_posts->the_post();
$validity_type = get_post_meta( get_the_ID(), "{$project_prefix}validity_type", true );
if( $validity_type && 'validity date' === $validity_type ) {
$validity = get_post_meta( get_the_ID(), "{$project_prefix}validity", true );
$tag = days_until( $validity ) .' days left'; //custom function
} else if( $validity_type && 'validity stock' === $validity_type ) {
$tag = 'Stock';
} else {
$tag = '...';
}
$posts_this_month[get_the_ID()] = get_the_title() .' ['. $tag .']';
endwhile; endif; wp_reset_postdata();
return $posts_this_month;
}
```
Question is not even with the function.
I want to do the query **only on that particular top\_level\_custom-settings-api page**. The function is loading on every page load of admin. I tried using `get_current_screen()` but this function's giving me not found fatal error.
### Edit
No @bonger, I remembered that. I tried your code in this way:
```
add_action('current_screen', 'current_screen_callback');
function current_screen_callback($screen) {
if( is_object($screen) && $screen->id == 'top_level_custom-settings-api' ) {
add_action( 'admin_init', 'pre_get_active_posts_of_30_days' );
}
}
```
The code does work well, but it doesn't control my function loading only on that particular page. I checked the query on other pages, the query is there too. And I tried changing the conditional to something wrong, like `$screen->id == 'top_level_-api'`, it still works that way. :(
I'm afraid, I know I have a serious lack in behind-the-scene action and filter things. Would love to have a good read for that too. | It's worthwhile pointing out that using `admin_init` within the `current_screen` filter is too late because `admin_init` has already fired.
Instead do:
```
add_action('current_screen', 'current_screen_callback');
function current_screen_callback($screen) {
if( is_object($screen) && $screen->id === 'top_level_custom-settings-api' ) {
add_filter('top_level_screen', '__return_true');
}
}
```
Elsewhere in your `top_level_page_callback` callback responsible for executing the query:
```
function top_level_page_callback() {
$active_posts = null;
if ( ($is_top_level = apply_filters('top_level_screen', false)) ) {
$active_posts = pre_get_active_posts_of_30_days();
}
//etc...
}
```
That's one way to do it...
Or you could use, `add_action('load-top_level_custom-settings-api', 'callback');`
Other than the `current_screen` hook, where else were you trying to call `pre_get_active_posts_of_30_days()` from? Because you had to have been calling it in a global scope of some sort for it to be running on all pages and not just the target page. |
219,629 | <p>I'm writing a web/db application. My clients would like authentication based on whether the user is logged into WordPress.</p>
<p>Assuming this application is hosted from within <code>/wordpress</code> I would like to be able to:</p>
<ol>
<li><p>Determine who, if anyone, is logged into WordPress</p>
<p>Seems as if it should be possible via <code>wp_get_current_user()</code> but I can't find any documentation detailing which include files need to be included to make that work. Including <code>/wp-includes/plugin.php</code> and <code>pluggable.php</code> results in a <code>class WP_User not found</code> error from <code>wp_get_current_user()</code>. I presume some required include files are not included, but which?</p></li>
<li><p>Read WordPress cookies</p>
<p>Seems to require knowledge of the hash that was used when they were created - how is this gettable?</p></li>
</ol>
<p><strong>Additional Information:</strong> The clients are a group of over 300 artists who want </p>
<ul>
<li>a website managed in WordPress and </li>
<li>a system to manage exhibition submissions, </li>
<li>a member database, </li>
<li>rotas,</li>
<li>user roles</li>
<li>catalogue production</li>
<li>detailed business rules/validation, permissions etc</li>
</ul>
<p>It boils down to various m:n relationships. So a separate system providing 'club admin' alongside WordPress for the public-facing website, seemed a better fit than WordPress with endless plugins with uncertain futures. The group, understandably, desires SSO. OAuth or similar is not an option since we're restricted to a single shared hosting (cPanel) account.</p>
<p><strong>UPDATE - simple solution found - see my answer below</strong></p>
| [
{
"answer_id": 220258,
"author": "Adam",
"author_id": 13418,
"author_profile": "https://wordpress.stackexchange.com/users/13418",
"pm_score": 2,
"selected": false,
"text": "<p>It's worthwhile pointing out that using <code>admin_init</code> within the <code>current_screen</code> filter is... | 2016/03/03 | [
"https://wordpress.stackexchange.com/questions/219629",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89934/"
] | I'm writing a web/db application. My clients would like authentication based on whether the user is logged into WordPress.
Assuming this application is hosted from within `/wordpress` I would like to be able to:
1. Determine who, if anyone, is logged into WordPress
Seems as if it should be possible via `wp_get_current_user()` but I can't find any documentation detailing which include files need to be included to make that work. Including `/wp-includes/plugin.php` and `pluggable.php` results in a `class WP_User not found` error from `wp_get_current_user()`. I presume some required include files are not included, but which?
2. Read WordPress cookies
Seems to require knowledge of the hash that was used when they were created - how is this gettable?
**Additional Information:** The clients are a group of over 300 artists who want
* a website managed in WordPress and
* a system to manage exhibition submissions,
* a member database,
* rotas,
* user roles
* catalogue production
* detailed business rules/validation, permissions etc
It boils down to various m:n relationships. So a separate system providing 'club admin' alongside WordPress for the public-facing website, seemed a better fit than WordPress with endless plugins with uncertain futures. The group, understandably, desires SSO. OAuth or similar is not an option since we're restricted to a single shared hosting (cPanel) account.
**UPDATE - simple solution found - see my answer below** | It's worthwhile pointing out that using `admin_init` within the `current_screen` filter is too late because `admin_init` has already fired.
Instead do:
```
add_action('current_screen', 'current_screen_callback');
function current_screen_callback($screen) {
if( is_object($screen) && $screen->id === 'top_level_custom-settings-api' ) {
add_filter('top_level_screen', '__return_true');
}
}
```
Elsewhere in your `top_level_page_callback` callback responsible for executing the query:
```
function top_level_page_callback() {
$active_posts = null;
if ( ($is_top_level = apply_filters('top_level_screen', false)) ) {
$active_posts = pre_get_active_posts_of_30_days();
}
//etc...
}
```
That's one way to do it...
Or you could use, `add_action('load-top_level_custom-settings-api', 'callback');`
Other than the `current_screen` hook, where else were you trying to call `pre_get_active_posts_of_30_days()` from? Because you had to have been calling it in a global scope of some sort for it to be running on all pages and not just the target page. |
219,643 | <p>What is a best way to eliminate xmlrpc.php file from WordPress when you don't need it?</p>
| [
{
"answer_id": 219646,
"author": "Jorin van Vilsteren",
"author_id": 68062,
"author_profile": "https://wordpress.stackexchange.com/users/68062",
"pm_score": 3,
"selected": false,
"text": "<p>We are using the htaccess file to protect it from hackers.</p>\n\n<pre><code># BEGIN protect xmlr... | 2016/03/03 | [
"https://wordpress.stackexchange.com/questions/219643",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88606/"
] | What is a best way to eliminate xmlrpc.php file from WordPress when you don't need it? | Since WordPress 3.5 this option (*`XML-RPC`*) is enabled by default, and the ability to turn it off from WordPress `dashboard` is gone.
Add this code snippet for use in `functions.php`:
```
// Disable use XML-RPC
add_filter( 'xmlrpc_enabled', '__return_false' );
// Disable X-Pingback to header
add_filter( 'wp_headers', 'disable_x_pingback' );
function disable_x_pingback( $headers ) {
unset( $headers['X-Pingback'] );
return $headers;
}
```
Although it does what it says, it can get intensive when a site is under attack by hitting it.
You may better off using following code snippet in your `.htaccess` file.
```
# Block WordPress xmlrpc.php requests
<Files xmlrpc.php>
order allow,deny
deny from all
</Files>
```
Or use this to disable access to the `xmlrpc.php` file from NGINX server block.
```
# nginx block xmlrpc.php requests
location /xmlrpc.php {
deny all;
}
```
>
> Be aware that disabling also can have impact on logins through mobile. If I am correct WordPress mobile app does need this.
>
> See [Codex](https://codex.wordpress.org/XML-RPC_WordPress_API) for more information about the use of `XML-RPC`.
>
>
>
> * *Please make always a backup of the file(s) before edit/add.*
>
>
>
---
**Edit/Update**
@Prosti, -You are absolutely correct- about the options which `RESTful API` will offer for WordPress!
I forgot to mention this. It should already have been integrated into core (*WordPress version 4.1*) which was not possible at that time. But as it seems, will be core in WordPress 4.5 .
The alternative for the moment is this plugin: [WordPress REST API (Version 2)](https://wordpress.org/plugins/rest-api/)
You can use it till `Restful API` is also core for WordPress.
**Target date for release of WordPress 4.5. (April 12, 2016 (+3w))**
>
> For those who are interested in `RESTful`, on [Stackoverflow](https://stackoverflow.com/a/671132/1370973) is a very nice community wiki.
>
>
> |
219,658 | <p>I made 2 plugins (Plugin A and plugin B/custom post type.) which some of the the module on Plugin A need to call taxonomy from PLUGIN B.
Everything works fine when both plugin active, but when the Plugin B deactivate, I got this notice:</p>
<blockquote>
<p>Notice: Trying to get property of non-object in D:\MYWEB\InstantWP_4.3.1\iwpserver\htdocs\wordpress\wp-content\plugins\NYPLUGIN\myplugin.php on line 50</p>
</blockquote>
<p>Line 50 looks like this:</p>
<pre><code>$option_value_event[] .= $cat->name;
</code></pre>
<p>Here the code:</p>
<pre><code> //Get all EVENT categories
$args = array(
'type' => 'post',
'child_of' => 0,
'parent' => '',
'orderby' => 'date',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'catevent',
'pad_counts' => false
);
$categories_event = get_categories($args);
$option_value_event = array();
//Extract all EVENT categories
foreach ( $categories_event as $cat ){
$option_value_event[] .= $cat->name;
}
</code></pre>
<p>Sometime my user dont want to use Plugin B. Is there any way to deactivate PLUGIN B without break PLUGIN A?</p>
<p>Is there a quick fix to resolve these error?</p>
<p>Really appreciate for any help</p>
<p>Thank you</p>
| [
{
"answer_id": 219661,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 0,
"selected": false,
"text": "<p>Well, a simple solution is to check if whatever is returned is empty. Always throw in these conditionals to... | 2016/03/03 | [
"https://wordpress.stackexchange.com/questions/219658",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89109/"
] | I made 2 plugins (Plugin A and plugin B/custom post type.) which some of the the module on Plugin A need to call taxonomy from PLUGIN B.
Everything works fine when both plugin active, but when the Plugin B deactivate, I got this notice:
>
> Notice: Trying to get property of non-object in D:\MYWEB\InstantWP\_4.3.1\iwpserver\htdocs\wordpress\wp-content\plugins\NYPLUGIN\myplugin.php on line 50
>
>
>
Line 50 looks like this:
```
$option_value_event[] .= $cat->name;
```
Here the code:
```
//Get all EVENT categories
$args = array(
'type' => 'post',
'child_of' => 0,
'parent' => '',
'orderby' => 'date',
'order' => 'ASC',
'hide_empty' => 1,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'catevent',
'pad_counts' => false
);
$categories_event = get_categories($args);
$option_value_event = array();
//Extract all EVENT categories
foreach ( $categories_event as $cat ){
$option_value_event[] .= $cat->name;
}
```
Sometime my user dont want to use Plugin B. Is there any way to deactivate PLUGIN B without break PLUGIN A?
Is there a quick fix to resolve these error?
Really appreciate for any help
Thank you | You will either need to do two things
* Check for an empty array **AND** a `WP_Error` object
* Check if the taxonomy exists (*which `get_categories()` and `get_terms()` already does*) before your execute your code and still check for an empty array
FEW NOTES TO CONSIDER
---------------------
* [`get_categories()`](https://developer.wordpress.org/reference/functions/get_categories/) uses `get_terms()`, you you could use [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/)
* You do not need to set arguments if you use it's default values
* `date` is not a valid value for `orderby` in `get_terms()`. Valid values are `name`, `slug`, `term_group`, `term_id`, `id`, `description` and `count`
* The `type` parameter in `get_categories()` does not relate to the post type, but to the taxonomy type. This parameter used to accept `link` as value and where used before the introduction of custom taxonomies in WordPress 3.0. Before WordPress 3.0, you could set `type` to `link` to return terms from the `link_category` taxonomy. This parameter was depreciated in WordPress 3.0 in favor of the `taxonomy` parameter
SOLUTION
--------
```
//Get all EVENT categories
$categories_event = get_terms( 'catevent' );
$option_value_event = array();
// Check for empty array and WP_Error
if ( $categories_event
&& !is_wp_error( $categories_event )
) {
//Extract all EVENT categories
foreach ( $categories_event as $cat ){
$option_value_event[] = $cat->name;
}
}
```
EDIT
----
I cannot see why the above code would not work. You can try the following as a test
```
if ( taxonomy_exists( 'catevent' ) ) {
//Get all EVENT categories
$categories_event = get_terms( 'catevent' );
$option_value_event = array();
// Check for empty array and WP_Error
if ( $categories_event
&& !is_wp_error( $categories_event )
) {
//Extract all EVENT categories
foreach ( $categories_event as $cat ){
$option_value_event[] = $cat->name;
}
}
}
```
That should work, if not, then you have a serious error somewhere in one of your plugins |
219,686 | <p>How can I get a list of all users that are in WordPress by their role or capabilities?</p>
<p>For example: </p>
<ul>
<li>Display <code>all subscribers list</code> in WordPress.</li>
<li>Display <code>all authors list</code> in WordPress.</li>
<li>Display <code>all editors list</code> in WordPress.</li>
</ul>
| [
{
"answer_id": 219687,
"author": "Raja Usman Mehmood",
"author_id": 75825,
"author_profile": "https://wordpress.stackexchange.com/users/75825",
"pm_score": 6,
"selected": true,
"text": "<p>There may be some different way to do that, but most proper way to do that is following.</p>\n\n<pr... | 2016/03/04 | [
"https://wordpress.stackexchange.com/questions/219686",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75825/"
] | How can I get a list of all users that are in WordPress by their role or capabilities?
For example:
* Display `all subscribers list` in WordPress.
* Display `all authors list` in WordPress.
* Display `all editors list` in WordPress. | There may be some different way to do that, but most proper way to do that is following.
```
<?php
$args = array(
'role' => 'Your desired role goes here.',
'orderby' => 'user_nicename',
'order' => 'ASC'
);
$users = get_users( $args );
echo '<ul>';
foreach ( $users as $user ) {
echo '<li>' . esc_html( $user->display_name ) . '[' . esc_html( $user->user_email ) . ']</li>';
}
echo '</ul>';
?>
``` |
219,745 | <p>I've got the following error messages on the themecheck plugin in my WordPress theme. </p>
<blockquote>
<p>REQUIRED: The theme uses the register_taxonomy() function, which is plugin-territory functionality. <br>
REQUIRED: The theme uses the register_post_type() function, which is plugin-territory functionality. <br>
WARNING: The theme uses the add_shortcode() function. Custom post-content shortcodes are plugin-territory functionality.</p>
</blockquote>
<p>I declared the <code>register_taxonomy()</code> and <code>register_post_type()</code> function in <code>after_setup_theme</code> hook. <br>
My <code>register_taxonomy()</code> function is:</p>
<pre><code>register_taxonomy('project_cat', 'project', array(
'public' => true,
'hierarchical' => true,
'labels' => array(
'name' => 'Categories',
)
));
</code></pre>
<p>And one of my <code>register_post_type()</code> function is:</p>
<pre><code>register_post_type('service', array(
'public' => true,
'supports' => array('title', 'thumbnail', 'editor'),
'labels' => array(
'name' => esc_html__('Services', 'textdomain'),
'add_new_item' => esc_html__('Add Service', 'textdomain'),
'add_new' => esc_html__('Add Service', 'textdomain')
)
));
</code></pre>
<p>How can I fix those issues?</p>
| [
{
"answer_id": 219687,
"author": "Raja Usman Mehmood",
"author_id": 75825,
"author_profile": "https://wordpress.stackexchange.com/users/75825",
"pm_score": 6,
"selected": true,
"text": "<p>There may be some different way to do that, but most proper way to do that is following.</p>\n\n<pr... | 2016/03/04 | [
"https://wordpress.stackexchange.com/questions/219745",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81042/"
] | I've got the following error messages on the themecheck plugin in my WordPress theme.
>
> REQUIRED: The theme uses the register\_taxonomy() function, which is plugin-territory functionality.
>
> REQUIRED: The theme uses the register\_post\_type() function, which is plugin-territory functionality.
>
> WARNING: The theme uses the add\_shortcode() function. Custom post-content shortcodes are plugin-territory functionality.
>
>
>
I declared the `register_taxonomy()` and `register_post_type()` function in `after_setup_theme` hook.
My `register_taxonomy()` function is:
```
register_taxonomy('project_cat', 'project', array(
'public' => true,
'hierarchical' => true,
'labels' => array(
'name' => 'Categories',
)
));
```
And one of my `register_post_type()` function is:
```
register_post_type('service', array(
'public' => true,
'supports' => array('title', 'thumbnail', 'editor'),
'labels' => array(
'name' => esc_html__('Services', 'textdomain'),
'add_new_item' => esc_html__('Add Service', 'textdomain'),
'add_new' => esc_html__('Add Service', 'textdomain')
)
));
```
How can I fix those issues? | There may be some different way to do that, but most proper way to do that is following.
```
<?php
$args = array(
'role' => 'Your desired role goes here.',
'orderby' => 'user_nicename',
'order' => 'ASC'
);
$users = get_users( $args );
echo '<ul>';
foreach ( $users as $user ) {
echo '<li>' . esc_html( $user->display_name ) . '[' . esc_html( $user->user_email ) . ']</li>';
}
echo '</ul>';
?>
``` |
219,810 | <p>I've internationalised my plugin and am now looking at how best to load the plugin's translated strings. I'm including myplugin/languages/myplugin.pot with my plugin but am not planning to distribute .po or .mo files.</p>
<p><strong>My question:</strong></p>
<p>Is it my job as a plugin author to use a function such as <code>load_plugin_textdomain()</code> to load translated strings or is this the job of my plugin's end user?</p>
<p><strong>The reason why I'm asking:</strong></p>
<p>If I were to use <code>load_plugin_textdomain()</code>, passing a third argument like in the example below will load myplugin{$locale}.mo from myplugin/languages. However, the plugin end-user will need to supply this myplugin{$locale}.mo file but, of course, when I issue a plugin update, that myplugin{$locale}.mo file will be overwritten.</p>
<pre><code>function myplugin_load_textdomain() {
load_plugin_textdomain( 'myplugin', false, plugin_basename( dirname( __FILE__ ) ) . '/languages' );
}
add_action( 'plugins_loaded', 'myplugin_load_textdomain' );
</code></pre>
<p>Ref: <a href="https://codex.wordpress.org/Function_Reference/load_plugin_textdomain" rel="nofollow">https://codex.wordpress.org/Function_Reference/load_plugin_textdomain</a></p>
| [
{
"answer_id": 219812,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": false,
"text": "<p>You need to:</p>\n\n<ul>\n<li>Call to <code>load_plugin_textdomain()</code>. (<a href=\"https://developer.wor... | 2016/03/05 | [
"https://wordpress.stackexchange.com/questions/219810",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22599/"
] | I've internationalised my plugin and am now looking at how best to load the plugin's translated strings. I'm including myplugin/languages/myplugin.pot with my plugin but am not planning to distribute .po or .mo files.
**My question:**
Is it my job as a plugin author to use a function such as `load_plugin_textdomain()` to load translated strings or is this the job of my plugin's end user?
**The reason why I'm asking:**
If I were to use `load_plugin_textdomain()`, passing a third argument like in the example below will load myplugin{$locale}.mo from myplugin/languages. However, the plugin end-user will need to supply this myplugin{$locale}.mo file but, of course, when I issue a plugin update, that myplugin{$locale}.mo file will be overwritten.
```
function myplugin_load_textdomain() {
load_plugin_textdomain( 'myplugin', false, plugin_basename( dirname( __FILE__ ) ) . '/languages' );
}
add_action( 'plugins_loaded', 'myplugin_load_textdomain' );
```
Ref: <https://codex.wordpress.org/Function_Reference/load_plugin_textdomain> | **EDIT - apparently this is all wrong so please disregard.**
You can use the `WP_LANG_DIR` constant to load translations from the update-safe languages directory first, and fall back to your plugin languages directory for any plugin-supplied translations. The default location is `wp-content/languages`, and users can set `WP_LANG_DIR` themselves in `wp-config.php`. When you load translations from multiple sources, the first found instance will be used, so user translations will always override any plugin-supplied translations, and allow users to do partial translations without translating all strings.
```
function your_plugin_load_plugin_textdomain(){
$domain = 'your-plugin';
$locale = apply_filters( 'plugin_locale', get_locale(), $domain );
// wp-content/languages/your-plugin/your-plugin-de_DE.mo
load_textdomain( $domain, trailingslashit( WP_LANG_DIR ) . $domain . '/' . $domain . '-' . $locale . '.mo' );
// wp-content/plugins/your-plugin/languages/your-plugin-de_DE.mo
load_plugin_textdomain( $domain, FALSE, basename( dirname( __FILE__ ) ) . '/languages/' );
}
add_action( 'init', 'your_plugin_load_plugin_textdomain' );
``` |
219,828 | <p>Is it possible to communicate with a plugin from an outside source?</p>
<p>I have an apache web server set up with wordpress running, and I would like to have automated input from a script trigger an action in a plugin.</p>
<p>I thought at first I might just be able to make a plugin that listens on a socket for input and uses hooks to call the right functions from other plugins. This just caused the website to never load completely.</p>
<p>Is it possible? Am I just missing something?</p>
<p>Edit: If anyone needs clarification let me know and I will do my best to explain differently. I realized that it might not be clear where the outside input would be coming from. It would be completely seperate from what is happening on the website, more like a bash script run locally on the server.</p>
<p>Edit2: My question might be a duplicate of <a href="https://wordpress.stackexchange.com/questions/130169/setting-up-an-api-listening-page">Setting up an API "listening" page</a>, but I'm not restricted to just an HTTP post.</p>
<p>Edit3: I also realized the plugin I was using might help:(plugin.php)</p>
<pre><code>$address = 'localhost';
$port = 8888;
if(( $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false ) {
error_log("socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n");
}
if(socket_bind($sock, $address, $port) === false ){
error_log("socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n");
}
if(socket_listen($sock, 5) === false){
error_log("socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n");
}
socket_set_nonblock($sock);
do{
if(($msgsock = socket_accept($sock)) === false ){
error_log("socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n");
}
else{
do{
if( false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))){
error_log("socket_read() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n");
}
//Do things with buf
socket_close($msg_socket);
} while(true);
}
break;
} while(true);
socket_close($sock);
</code></pre>
<p>Right now it doesn't do anything except for wait for a connection and read 2048 bytes, but when it goes to socket_accept it gets an error "Success".</p>
| [
{
"answer_id": 219812,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": false,
"text": "<p>You need to:</p>\n\n<ul>\n<li>Call to <code>load_plugin_textdomain()</code>. (<a href=\"https://developer.wor... | 2016/03/05 | [
"https://wordpress.stackexchange.com/questions/219828",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90060/"
] | Is it possible to communicate with a plugin from an outside source?
I have an apache web server set up with wordpress running, and I would like to have automated input from a script trigger an action in a plugin.
I thought at first I might just be able to make a plugin that listens on a socket for input and uses hooks to call the right functions from other plugins. This just caused the website to never load completely.
Is it possible? Am I just missing something?
Edit: If anyone needs clarification let me know and I will do my best to explain differently. I realized that it might not be clear where the outside input would be coming from. It would be completely seperate from what is happening on the website, more like a bash script run locally on the server.
Edit2: My question might be a duplicate of [Setting up an API "listening" page](https://wordpress.stackexchange.com/questions/130169/setting-up-an-api-listening-page), but I'm not restricted to just an HTTP post.
Edit3: I also realized the plugin I was using might help:(plugin.php)
```
$address = 'localhost';
$port = 8888;
if(( $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false ) {
error_log("socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n");
}
if(socket_bind($sock, $address, $port) === false ){
error_log("socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n");
}
if(socket_listen($sock, 5) === false){
error_log("socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n");
}
socket_set_nonblock($sock);
do{
if(($msgsock = socket_accept($sock)) === false ){
error_log("socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n");
}
else{
do{
if( false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))){
error_log("socket_read() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n");
}
//Do things with buf
socket_close($msg_socket);
} while(true);
}
break;
} while(true);
socket_close($sock);
```
Right now it doesn't do anything except for wait for a connection and read 2048 bytes, but when it goes to socket\_accept it gets an error "Success". | **EDIT - apparently this is all wrong so please disregard.**
You can use the `WP_LANG_DIR` constant to load translations from the update-safe languages directory first, and fall back to your plugin languages directory for any plugin-supplied translations. The default location is `wp-content/languages`, and users can set `WP_LANG_DIR` themselves in `wp-config.php`. When you load translations from multiple sources, the first found instance will be used, so user translations will always override any plugin-supplied translations, and allow users to do partial translations without translating all strings.
```
function your_plugin_load_plugin_textdomain(){
$domain = 'your-plugin';
$locale = apply_filters( 'plugin_locale', get_locale(), $domain );
// wp-content/languages/your-plugin/your-plugin-de_DE.mo
load_textdomain( $domain, trailingslashit( WP_LANG_DIR ) . $domain . '/' . $domain . '-' . $locale . '.mo' );
// wp-content/plugins/your-plugin/languages/your-plugin-de_DE.mo
load_plugin_textdomain( $domain, FALSE, basename( dirname( __FILE__ ) ) . '/languages/' );
}
add_action( 'init', 'your_plugin_load_plugin_textdomain' );
``` |
219,845 | <p>To display all the categories name with checkbox from custom taxonomy called <code>ct_category</code> I have the following code: </p>
<pre><code>$terms = get_terms('ct_category');
foreach ( $terms as $term ) {
echo '<li class='.$term->term_id.'><label > <input class="taxonomy_category" type="checkbox" name="taxonomy_category['.$term->term_id.']" value ="'.$term->term_id.'" />'.$term->name.'</label ></li>';
}
</code></pre>
<p>I would like to display content only from checked categories. I tried following that didn't work:</p>
<pre><code>$args = array(
'post_type' => 'cpt',
'tax_query' => array(
array(
'taxonomy' => $ct_category,
'field' => 'term_id',
'terms' => $_POST['taxonomy_category']
)
)
);
$loop = new WP_Query( $args );
</code></pre>
<p>I can guess that the issue is in <code>'terms' => $_POST['taxonomy_category']</code>. If name attribute <code>taxonomy_category['.$term->term_id.']</code> can be displayed as array in <code>'terms' =></code>, the issue would be fixed. Spent plenty of times searching google but couldn't find any solution. </p>
<p>Here is the full code</p>
<pre><code><?php
function add_meta_box() {
add_meta_box( 'ct_metabox', 'CT', 'meta_box_content_output', 'cpt', 'normal' );
}
add_action( 'add_meta_boxes', 'add_meta_box' );
function meta_box_content_output ( $post ) {
wp_nonce_field( 'save_meta_box_data', 'meta_box_nonce' );
$taxonomy_category = get_post_meta( $post->ID, 'taxonomy_category', true );
function categories_checkbox(){
$terms = get_terms('ct_category');
foreach ( $terms as $term ) {
echo '<li class='.$term->term_id.'><label > <input class="taxonomy_category" type="checkbox" name="taxonomy_category['.$term->term_id.']" value ="'.$term->term_id.'" />'.$term->name.'</label ></li>';
}
}
<?
<ul>
<li>
<?php categories_checkbox() ?>
<li>
</ul>
<?php
}
function save_meta_box_data( $post_id ) {
// Check if our nonce is set.
if ( ! isset( $_POST['meta_box_nonce'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST['meta_box_nonce'], 'save_meta_box_data' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}
} else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
$taxonomy_category_value = "";
if(isset($_POST["logo_taxonomy_category"])) {
$taxonomy_category_value = sanitize_text_field( $_POST["logo_taxonomy_category"] );
}
update_post_meta($post_id, "logo_taxonomy_category", $taxonomy_category_value);
}
add_action( 'save_post', 'save_meta_box_data' );
?>
<?php
$args = array(
'post_type' => 'cpt',
'tax_query' => array(
array(
'taxonomy' => $ct_category,
'field' => 'term_id',
'terms' => $taxonomy_category
)
)
);
$loop = new WP_Query( $args );
?>
</code></pre>
| [
{
"answer_id": 219848,
"author": "willrich33",
"author_id": 90020,
"author_profile": "https://wordpress.stackexchange.com/users/90020",
"pm_score": 0,
"selected": false,
"text": "<p>It is an advanced question that would take me time to debug. However I believe the 'id' value for 'field' ... | 2016/03/06 | [
"https://wordpress.stackexchange.com/questions/219845",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48090/"
] | To display all the categories name with checkbox from custom taxonomy called `ct_category` I have the following code:
```
$terms = get_terms('ct_category');
foreach ( $terms as $term ) {
echo '<li class='.$term->term_id.'><label > <input class="taxonomy_category" type="checkbox" name="taxonomy_category['.$term->term_id.']" value ="'.$term->term_id.'" />'.$term->name.'</label ></li>';
}
```
I would like to display content only from checked categories. I tried following that didn't work:
```
$args = array(
'post_type' => 'cpt',
'tax_query' => array(
array(
'taxonomy' => $ct_category,
'field' => 'term_id',
'terms' => $_POST['taxonomy_category']
)
)
);
$loop = new WP_Query( $args );
```
I can guess that the issue is in `'terms' => $_POST['taxonomy_category']`. If name attribute `taxonomy_category['.$term->term_id.']` can be displayed as array in `'terms' =>`, the issue would be fixed. Spent plenty of times searching google but couldn't find any solution.
Here is the full code
```
<?php
function add_meta_box() {
add_meta_box( 'ct_metabox', 'CT', 'meta_box_content_output', 'cpt', 'normal' );
}
add_action( 'add_meta_boxes', 'add_meta_box' );
function meta_box_content_output ( $post ) {
wp_nonce_field( 'save_meta_box_data', 'meta_box_nonce' );
$taxonomy_category = get_post_meta( $post->ID, 'taxonomy_category', true );
function categories_checkbox(){
$terms = get_terms('ct_category');
foreach ( $terms as $term ) {
echo '<li class='.$term->term_id.'><label > <input class="taxonomy_category" type="checkbox" name="taxonomy_category['.$term->term_id.']" value ="'.$term->term_id.'" />'.$term->name.'</label ></li>';
}
}
<?
<ul>
<li>
<?php categories_checkbox() ?>
<li>
</ul>
<?php
}
function save_meta_box_data( $post_id ) {
// Check if our nonce is set.
if ( ! isset( $_POST['meta_box_nonce'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $_POST['meta_box_nonce'], 'save_meta_box_data' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}
} else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
$taxonomy_category_value = "";
if(isset($_POST["logo_taxonomy_category"])) {
$taxonomy_category_value = sanitize_text_field( $_POST["logo_taxonomy_category"] );
}
update_post_meta($post_id, "logo_taxonomy_category", $taxonomy_category_value);
}
add_action( 'save_post', 'save_meta_box_data' );
?>
<?php
$args = array(
'post_type' => 'cpt',
'tax_query' => array(
array(
'taxonomy' => $ct_category,
'field' => 'term_id',
'terms' => $taxonomy_category
)
)
);
$loop = new WP_Query( $args );
?>
``` | If `$taxonomy_category` is already an array, then:
```
'terms' => array($taxonomy_category)
```
should just be:
```
'terms' => $taxonomy_category
```
where `$taxonomy_category` is equal to whatever was submitted from your form as `$_POST['taxonomy_category']` or `$_GET['taxonomy_category']` |
219,867 | <p>I have a setup, where I want to achieve that I have a big Picture of a product (Post-image), and then below a list of other thumbnails, which can be opened in a Lightbox. I made this, by querying the post-image in the appropriate large size, and then querying the attachment images through a WP_Query post-type. But, the problem is, that the Query get also the post-thumbnail, and not only the images attached to the post. This is the code</p>
<pre><code><div class="product-img">
<?php if ( has_post_thumbnail()) : // Check if Thumbnail exists ?>
<?php // get fullimage
$thumb_id = get_post_thumbnail_id( $post->ID );
$image = wp_get_attachment_image_src( $thumb_id,'full' ); ?>
<a href="<?php echo $image[0]; ?>" title="<?php the_title(); ?>" rel="lightbox">
<?php the_post_thumbnail( 'large' ); // large image for the single post ?>
</a>
<?php endif; ?>
<div class="other-images">
<?php /* QUery attached images */
$images_query_args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => 'image',
'post_parent' => $post->ID
);
$images_query = new WP_Query( $images_query_args );
if ( $images_query->have_posts() ) : while ( $images_query->have_posts() ) : $images_query->the_post();
?>
<a href="<?php echo wp_get_attachment_image_url( get_the_ID(), 'large' ); ?>" title="<?php the_title(); ?>" rel="lightbox">
<?php // Output the attachment image
echo wp_get_attachment_image( get_the_ID(), 'thumbnail' ); ?>
</a>
<?php
endwhile; endif;
wp_reset_postdata();
?>
</div>
</code></pre>
<p>How can I make the image_query not to display the post-image, but only the others?
Or, if there exists a plugin which handles the attached galleries better (eg. custom sorting-order, better visualizing which image is attached) than the native WP, I'm also interested in reworking the code if necessary. It would be important for the editors that these galleries are per-post, and not separate, through shortcodes like eg. the NextCellent</p>
| [
{
"answer_id": 219848,
"author": "willrich33",
"author_id": 90020,
"author_profile": "https://wordpress.stackexchange.com/users/90020",
"pm_score": 0,
"selected": false,
"text": "<p>It is an advanced question that would take me time to debug. However I believe the 'id' value for 'field' ... | 2016/03/06 | [
"https://wordpress.stackexchange.com/questions/219867",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80726/"
] | I have a setup, where I want to achieve that I have a big Picture of a product (Post-image), and then below a list of other thumbnails, which can be opened in a Lightbox. I made this, by querying the post-image in the appropriate large size, and then querying the attachment images through a WP\_Query post-type. But, the problem is, that the Query get also the post-thumbnail, and not only the images attached to the post. This is the code
```
<div class="product-img">
<?php if ( has_post_thumbnail()) : // Check if Thumbnail exists ?>
<?php // get fullimage
$thumb_id = get_post_thumbnail_id( $post->ID );
$image = wp_get_attachment_image_src( $thumb_id,'full' ); ?>
<a href="<?php echo $image[0]; ?>" title="<?php the_title(); ?>" rel="lightbox">
<?php the_post_thumbnail( 'large' ); // large image for the single post ?>
</a>
<?php endif; ?>
<div class="other-images">
<?php /* QUery attached images */
$images_query_args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => 'image',
'post_parent' => $post->ID
);
$images_query = new WP_Query( $images_query_args );
if ( $images_query->have_posts() ) : while ( $images_query->have_posts() ) : $images_query->the_post();
?>
<a href="<?php echo wp_get_attachment_image_url( get_the_ID(), 'large' ); ?>" title="<?php the_title(); ?>" rel="lightbox">
<?php // Output the attachment image
echo wp_get_attachment_image( get_the_ID(), 'thumbnail' ); ?>
</a>
<?php
endwhile; endif;
wp_reset_postdata();
?>
</div>
```
How can I make the image\_query not to display the post-image, but only the others?
Or, if there exists a plugin which handles the attached galleries better (eg. custom sorting-order, better visualizing which image is attached) than the native WP, I'm also interested in reworking the code if necessary. It would be important for the editors that these galleries are per-post, and not separate, through shortcodes like eg. the NextCellent | If `$taxonomy_category` is already an array, then:
```
'terms' => array($taxonomy_category)
```
should just be:
```
'terms' => $taxonomy_category
```
where `$taxonomy_category` is equal to whatever was submitted from your form as `$_POST['taxonomy_category']` or `$_GET['taxonomy_category']` |
219,870 | <p>I am working on the data validation side of my WordPress theme. I have an option where user can input JS in the backend, and same is outputted in the front end between the script tags.</p>
<p>The problem I am facing is, I am not able to find a WordPress function that allows only JavaScript to pass through. What if user types some junk, CSS/HTML in it?</p>
<p>Is there any function in WordPress core/PHP that I can use? Or will I have to just echo it straightaway?</p>
| [
{
"answer_id": 219881,
"author": "thebigtine",
"author_id": 76059,
"author_profile": "https://wordpress.stackexchange.com/users/76059",
"pm_score": 1,
"selected": false,
"text": "<p>From this answer: <a href=\"https://wordpress.stackexchange.com/a/107558/76059\">https://wordpress.stackex... | 2016/03/06 | [
"https://wordpress.stackexchange.com/questions/219870",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63853/"
] | I am working on the data validation side of my WordPress theme. I have an option where user can input JS in the backend, and same is outputted in the front end between the script tags.
The problem I am facing is, I am not able to find a WordPress function that allows only JavaScript to pass through. What if user types some junk, CSS/HTML in it?
Is there any function in WordPress core/PHP that I can use? Or will I have to just echo it straightaway? | What you're asking for is impossible, there is no such thing as a safe javascript entry box.
Even if we strip out extra script and style tags, it's pointless, as the javascript code itself is inherently dangerous, and can create any elements it wants using DOM construction, e.g.:
```
var s = jQuery( 'script', { 'src': 'example.com/dangerous.js' } );
jQuery('body').append( s );
```
Or
```
var s = jQuery( 'link', {
'rel': 'stylesheet',
'type': 'text/css',
'href': 'example.com/broken.css'
} );
jQuery('body').append( s );
```
Nevermind something that steals your login cookies, etc. Javascript is inherently dangerous, and what you're trying to implement is an attack vector. This isn't because people might break out of javascript, but because the javascript itself is potentially dangerous |
219,874 | <p>My WordPress plugin uses Chosen Select and is supposed to use the css file at <code>my-plugin/assets/resources/chosen.min.css</code>.</p>
<p>Unfortunately, when another plugin also uses Chosen Select, my plugin has a tendency to grab styles from the other css file instead. </p>
<p>For example, it's currently getting styles from <code>yith-woocommerce-ajax-search/plugin-fw/assets/css/chosen/chosen.css</code> which messes up all my custom styling. </p>
<p>What's the best way to make sure an installation of Chosen Select (or other common things that have their own syling) doesn't get styles from other css files?</p>
<p>Here's how I register the stylesheet. </p>
<pre><code>function lsmi_load_admin_script() {
wp_register_style( 'chosencss', plugins_url( 'assets/resources/chosen.min.css', __FILE__ ), true, '', 'all' );
wp_enqueue_style( 'chosencss' );
}
</code></pre>
| [
{
"answer_id": 219880,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>There really is no foolproof method to detect a style sheet from other plugins or from a theme and then ... | 2016/03/06 | [
"https://wordpress.stackexchange.com/questions/219874",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81557/"
] | My WordPress plugin uses Chosen Select and is supposed to use the css file at `my-plugin/assets/resources/chosen.min.css`.
Unfortunately, when another plugin also uses Chosen Select, my plugin has a tendency to grab styles from the other css file instead.
For example, it's currently getting styles from `yith-woocommerce-ajax-search/plugin-fw/assets/css/chosen/chosen.css` which messes up all my custom styling.
What's the best way to make sure an installation of Chosen Select (or other common things that have their own syling) doesn't get styles from other css files?
Here's how I register the stylesheet.
```
function lsmi_load_admin_script() {
wp_register_style( 'chosencss', plugins_url( 'assets/resources/chosen.min.css', __FILE__ ), true, '', 'all' );
wp_enqueue_style( 'chosencss' );
}
``` | There really is no foolproof method to detect a style sheet from other plugins or from a theme and then "switching them off". You can only guess that other plugins and themes will be using the same handle as you to register the style sheet with. It is however much easier if your plugin is for personal use only, then you can manually go through a plugin, get the handle of the conflicting style sheet and deregister it yourself
You can also give your `wp_enqueue_scripts` action a very low priority (*very high number*) in order to load your style sheet as late as possible
```
add_action( 'wp_enqueue_scripts', 'lsmi_load_admin_script', PHP_INT_MAX );
function lsmi_load_admin_script()
{
// Deregister and dequeue other conflicting stylesheets
wp_dequeue_style( 'chosencss' );
wp_deregister_style( 'chosencss' );
// Add your own stylesheet
wp_register_style( 'chosencss', plugins_url( 'assets/resources/chosen.min.css', __FILE__ ), true, '', 'all' );
wp_enqueue_style( 'chosencss' );
}
``` |
219,911 | <p>I'm developing my first plugin and wp_enqueue_style doesn't work. I'm in localhost (apache2) installation, ubuntu 14.04.</p>
<p>In my main file I have</p>
<pre><code>define( 'EASYDM_CSS_DIR', plugin_dir_path( __FILE__ ).'css/' );
add_action( 'wp_enqueue_style', 'easydm_add_link_tag_to_head' );
</code></pre>
<p>And in my php functions file I have:</p>
<pre><code>function easydm_add_link_tag_to_head() {
wp_enqueue_style( 'style.css', EASYDM_CSS_DIR );
}
</code></pre>
<p>I want to style an option page, in the admin panel.</p>
| [
{
"answer_id": 219914,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 1,
"selected": false,
"text": "<p>You've given <code>wp_enqueue_style</code> a directory, but no file name. Have a look at <a href=\"https:/... | 2016/03/07 | [
"https://wordpress.stackexchange.com/questions/219911",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89766/"
] | I'm developing my first plugin and wp\_enqueue\_style doesn't work. I'm in localhost (apache2) installation, ubuntu 14.04.
In my main file I have
```
define( 'EASYDM_CSS_DIR', plugin_dir_path( __FILE__ ).'css/' );
add_action( 'wp_enqueue_style', 'easydm_add_link_tag_to_head' );
```
And in my php functions file I have:
```
function easydm_add_link_tag_to_head() {
wp_enqueue_style( 'style.css', EASYDM_CSS_DIR );
}
```
I want to style an option page, in the admin panel. | You've given `wp_enqueue_style` a directory, but no file name. Have a look at <https://developer.wordpress.org/reference/functions/wp_enqueue_style/>:
* The first parameter of `wp_enqueue_style` is the name, or handle, of the stylesheet as referred to internally by Wordpress (this should be a unique name for each stylesheet you enqueue)
* The second parameter is the src to the stylesheet - so this is where you need to add both your directory and your stylesheet name
So, if you change your second parameter to `EASYDM_CSS_DIR . "style.css"` - and just use something like `'my-stylesheet'` as the first parameter, providing everything is in the right place you should find it works. :)
**EDIT**
Just noticed something I didn't pick up earlier in your code: there's actually no `wp_enqueue_style` action. You need to use the `wp_enqueue_scripts` action to add both styles and scripts. This is a bit confusing, because the *function* `wp_enqueue_style` you've used *is* correct, but it's never being called because of the incorrect action.
Change this:
`add_action( 'wp_enqueue_style', 'easydm_add_link_tag_to_head' );`
to this:
`add_action( 'wp_enqueue_scripts', 'easydm_add_link_tag_to_head' );`
and then your function `easydm_add_link_tag_to_head` should be called correctly.
If it's still not working, it's probably down to either the path not being correct, or something else I didn't notice in the code! This is where we need to start debugging to find the issue. The simplest, crudest, easiest way to do this is just to put `echo 1;`, `echo 2;`, `echo 3;` etc. in different parts of your code - and then viewing the source of your page - to determine what is working and what isn't. Of course, it's also worth checking if the `<link>` tag is making it through to the source of your page, because if it is, the clue might be in the path not being correct! |
219,931 | <p>I am using the Wordpress theme Twenty Twelve (a child of it to be precise). </p>
<p>I want to know how to insert some HTML just after body opening, in just functions.php and not using header.php. </p>
<p>Is that possible?</p>
| [
{
"answer_id": 219938,
"author": "Adam",
"author_id": 13418,
"author_profile": "https://wordpress.stackexchange.com/users/13418",
"pm_score": 6,
"selected": true,
"text": "<p>Twenty Twelve does not have any hooks that fire immediately after the opening <code><body></code> tag.</p>\... | 2016/03/07 | [
"https://wordpress.stackexchange.com/questions/219931",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87509/"
] | I am using the Wordpress theme Twenty Twelve (a child of it to be precise).
I want to know how to insert some HTML just after body opening, in just functions.php and not using header.php.
Is that possible? | Twenty Twelve does not have any hooks that fire immediately after the opening `<body>` tag.
Therefore you in your child theme which extends the parent Twenty Twelve theme, copy the `header.php` across to your child theme directory.
Open the `header.php` file in your child theme and just after the opening body tag add an action hook which you can then hook onto via your `functions.php` file.
For example in your `twenty-twelve-child/header.php` file:
```
<body <?php body_class(); ?>>
<?php do_action('after_body_open_tag'); ?>
```
Then in your `twenty-twelve-child/functions.php` file:
```
function custom_content_after_body_open_tag() {
?>
<div>My Custom Content</div>
<?php
}
add_action('after_body_open_tag', 'custom_content_after_body_open_tag');
```
This will then render in your HTML as:
```
<body>
<div>My Custom Content</div>
```
Recommended reading:
<https://developer.wordpress.org/reference/functions/do_action/>
UPDATE: JULY, 2019
------------------
As commented by [Junaid Bhura](https://wordpress.stackexchange.com/questions/219931/insert-html-just-after-body-tag/219938?noredirect=1#comment504459_219938) from WordPress 5.2 a new theme helper function [`wp_body_open`](https://developer.wordpress.org/reference/functions/wp_body_open/) has been introduced that is intended for use as per the likes of other helper functions `wp_head` and `wp_footer`.
For example:
```
<html>
<head>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<?php wp_body_open(); ?>
<!-- BODY CONTENT HERE -->
<?php wp_footer(); ?>
</body>
</html>
```
In your theme functions.php file (or suitably elsewhere)
```
function custom_content_after_body_open_tag() {
?>
<div>My Custom Content</div>
<?php
}
add_action('wp_body_open', 'custom_content_after_body_open_tag');
```
### IMPORTANT
>
> You should ensure that the hook exists within the theme that you are wanting to inject-into as this may not be widely adopted by the community, yet.
>
>
> If **NOT**, you will still **need to follow the principle of extending the theme with a child theme** with the exception that **YOU** would use:
>
>
> `<?php wp_body_open(); ?>`
>
>
> ...instead of OR in addition to:
>
>
> `<?php do_action('after_body_open_tag'); ?>`
>
>
>
Recommended reading:
<https://developer.wordpress.org/reference/functions/wp_body_open/> |
219,954 | <p>My loop below shows the latest 4 posts from the same category as the post currently being viewed. Its located within single.php. </p>
<p>I'm trying to get the URL of that same category so I can link back to category.php to view all posts from that same category. I thought grabbing the category slug would work but my code below doesn't output anything:</p>
<pre><code><?php
global $post;
$categories = get_the_category();
foreach ($categories as $category) :
$exclude = get_the_ID();
$posts = get_posts('posts_per_page=4&category='. $category->term_id);
foreach($posts as $post) :
if( $exclude != get_the_ID() ) { ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="post c-1"> Link to actual post</a>
<?php } endforeach; ?>
<a href="<?php bloginfo('url'); ?>/categories/<?php echo $childcat->cat_slug; ?>" title="View all" class="btn border"><i class="i-right-double-arrow"></i> View all <?php echo $childcat->cat_slug; ?></a>
<?php endforeach; wp_reset_postdata(); ?>
</code></pre>
| [
{
"answer_id": 219955,
"author": "Adam",
"author_id": 13418,
"author_profile": "https://wordpress.stackexchange.com/users/13418",
"pm_score": 4,
"selected": true,
"text": "<p>Use:</p>\n\n<pre><code>get_category_link( $category_id );\n</code></pre>\n\n<p>See: </p>\n\n<p><a href=\"https://... | 2016/03/07 | [
"https://wordpress.stackexchange.com/questions/219954",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14149/"
] | My loop below shows the latest 4 posts from the same category as the post currently being viewed. Its located within single.php.
I'm trying to get the URL of that same category so I can link back to category.php to view all posts from that same category. I thought grabbing the category slug would work but my code below doesn't output anything:
```
<?php
global $post;
$categories = get_the_category();
foreach ($categories as $category) :
$exclude = get_the_ID();
$posts = get_posts('posts_per_page=4&category='. $category->term_id);
foreach($posts as $post) :
if( $exclude != get_the_ID() ) { ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="post c-1"> Link to actual post</a>
<?php } endforeach; ?>
<a href="<?php bloginfo('url'); ?>/categories/<?php echo $childcat->cat_slug; ?>" title="View all" class="btn border"><i class="i-right-double-arrow"></i> View all <?php echo $childcat->cat_slug; ?></a>
<?php endforeach; wp_reset_postdata(); ?>
``` | Use:
```
get_category_link( $category_id );
```
See:
<https://codex.wordpress.org/Function_Reference/get_category_link>
In your specific case:
```
<?php
global $post;
$categories = get_the_category();
foreach ($categories as $category) :
$exclude = get_the_ID();
$posts = get_posts('posts_per_page=4&category='. $category->term_id);
foreach($posts as $post) :
if( $exclude != get_the_ID() ) { ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="post c-1"> Link to actual post</a>
<?php } endforeach; ?>
<a href="<?php echo esc_url( get_category_link( $category->term_id ) ); ?>" title="View all" class="btn border"><i class="i-right-double-arrow"></i> View all <?php echo $category->name; ?></a>
<?php endforeach; wp_reset_postdata(); ?>
``` |
219,959 | <p>I want to restrict pending posts to only certain users in the admin section, so I want to remove it from the post status options when viewing all posts (the bit highlighted in red in the image below):</p>
<p><a href="https://i.stack.imgur.com/XHX9j.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XHX9j.png" alt="WordPress post statuses submenu"></a></p>
<p>However, I can't find which hook I need to edit this. Can anyone shunt me in the right direction? I've scanned the filter reference but didn't see anything appropriate.</p>
| [
{
"answer_id": 219961,
"author": "Adam",
"author_id": 13418,
"author_profile": "https://wordpress.stackexchange.com/users/13418",
"pm_score": 2,
"selected": false,
"text": "<p>The filter you are looking for is <code>views_{$this->screen->id}</code> which is located in the <code>WP_... | 2016/03/07 | [
"https://wordpress.stackexchange.com/questions/219959",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63673/"
] | I want to restrict pending posts to only certain users in the admin section, so I want to remove it from the post status options when viewing all posts (the bit highlighted in red in the image below):
[](https://i.stack.imgur.com/XHX9j.png)
However, I can't find which hook I need to edit this. Can anyone shunt me in the right direction? I've scanned the filter reference but didn't see anything appropriate. | The filter you are looking for is `views_{$this->screen->id}` which is located in the `WP_List_Table::views()` method.
Where `$this->screen->id` is that of the context you are in, e.g. `posts`, `users`, etc...
File `wp-admin/class-wp-list-table.php`
Example usage:
```
function filter_posts_listable_views($views) {
//do your thing...
return $views;
}
add_filter( 'views_posts', 'filter_posts_list_table_views', 100);
``` |
219,974 | <p>I have declared post type as below:</p>
<pre><code> $args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array('slug' => 'agences'),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => 5,
'taxonomies' => array('brands', 'country'),
'supports' => array('title', 'editor', 'author', 'thumbnail', 'custom-fields')
);
register_post_type('destinations', $args);
</code></pre>
<p>Initially I was able to access single page of this post type using <code>single-agences.php</code> but now it is redirecting to 404.</p>
<p>I have checked other answers and found that its a common mistake but other answers were not able to resolve this.
Any help will be wonderful.</p>
| [
{
"answer_id": 219980,
"author": "Mayeenul Islam",
"author_id": 22728,
"author_profile": "https://wordpress.stackexchange.com/users/22728",
"pm_score": 4,
"selected": false,
"text": "<p>Newly registered CPT shows 404 because, the <code>register_post_type()</code> doesn't flush the rewrit... | 2016/03/07 | [
"https://wordpress.stackexchange.com/questions/219974",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66318/"
] | I have declared post type as below:
```
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array('slug' => 'agences'),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => 5,
'taxonomies' => array('brands', 'country'),
'supports' => array('title', 'editor', 'author', 'thumbnail', 'custom-fields')
);
register_post_type('destinations', $args);
```
Initially I was able to access single page of this post type using `single-agences.php` but now it is redirecting to 404.
I have checked other answers and found that its a common mistake but other answers were not able to resolve this.
Any help will be wonderful. | It was due to a plugin "Remove taxonomy base slug". It was conflicting with base slug of CPT "destinations". I had to use `add_rewrite_rule` to check for slug and manually redirect it to proper location |
219,975 | <p>I have a WordPress database with over 2 million posts. Whenever I insert a new post I have to call <code>wp_set_object_terms</code> which takes over two seconds to execute. I came across <a href="http://www.kellbot.com/wordpress-post-inserts-are-super-slow/" rel="nofollow">this post</a> that recommends calling <code>wp_defer_term_counting</code> to skip the term counting.</p>
<p>Are there serious consequences to the functioning of WordPress if I use this approach?</p>
<p>Here's the code from the post just in case the link goes dead:</p>
<pre><code>function insert_many_posts(){
wp_defer_term_counting(true);
$tasks = get_default_tasks();
for ($tasks as $task){
$post = array(
'post_title' => $task[content],
'post_author' => $current_user->ID,
'post_content' => '',
'post_type' => 'bpc_default_task',
'post_status' => 'publish'
);
$task_id = wp_insert_post( $post );
if ( $task[category] )
//Make sure we're passing an int as the term so it isn't mistaken for a slug
wp_set_object_terms( $task_id, array( intval( $category ) ), 'bpc_category' );
}
}
</code></pre>
| [
{
"answer_id": 219977,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 0,
"selected": false,
"text": "<p>This should be relatively safe as an operation. This is deferring the counting of terms that appears on the ... | 2016/03/07 | [
"https://wordpress.stackexchange.com/questions/219975",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/657/"
] | I have a WordPress database with over 2 million posts. Whenever I insert a new post I have to call `wp_set_object_terms` which takes over two seconds to execute. I came across [this post](http://www.kellbot.com/wordpress-post-inserts-are-super-slow/) that recommends calling `wp_defer_term_counting` to skip the term counting.
Are there serious consequences to the functioning of WordPress if I use this approach?
Here's the code from the post just in case the link goes dead:
```
function insert_many_posts(){
wp_defer_term_counting(true);
$tasks = get_default_tasks();
for ($tasks as $task){
$post = array(
'post_title' => $task[content],
'post_author' => $current_user->ID,
'post_content' => '',
'post_type' => 'bpc_default_task',
'post_status' => 'publish'
);
$task_id = wp_insert_post( $post );
if ( $task[category] )
//Make sure we're passing an int as the term so it isn't mistaken for a slug
wp_set_object_terms( $task_id, array( intval( $category ) ), 'bpc_category' );
}
}
``` | **Here are some thoughts on the issue, but please note that this is by no means a conclusive answer as there may be some things I have overlooked however this should give you an insight to the potential gotchas.**
---
Yes, technically there could be consequences.
Where calling `wp_defer_term_counting(true)` becomes truly beneficial is when for instance you are performing a mass insertion to the database of posts and assigned terms to each object as part of the process.
In such a case you would do the following:
```
wp_defer_term_counting(true); //defer counting terms
//mass insertion or posts and assignment of terms here
wp_defer_term_counting(false); //count terms after completing business logic
```
Now in your case, if you are only inserting one post at a time, then deferring term counting will still benefit you however by not call `wp_defer_term_counting(false)` after your operation could leave you and or other parties involved with the request in a bind if you rely upon the term count for any other logic/processing, conditional or otherwise.
To explain further, let's say you do the following:
Assume we have 3 terms within a taxonomy called `product_cat`, the IDs for those terms are 1 (term name A), 2 (term name B) and 3 (term name C) respectively.
Each of the above terms already has a term count of **`5`** (just for the example).
Then this happens...
```
wp_defer_term_counting(true); //defer counting terms
$post_id = wp_insert_post($data);
wp_set_object_terms($post_id, array(1, 2, 3), 'product_cat');
```
Then later in your logic you decide to fetch the term because you want to assess the amount of objects associated with that term and perform some other action based on the result.
So you do this...
```
$terms = get_the_terms($post_id, 'product_cat');
//let's just grab the first term object off the array of returned results
//for the sake of this example $terms[0] relates to term_id 1 (A)
echo $terms[0]->count; //result 5
//dump output of $terms above
array (
0 =>
WP_Term::__set_state(array(
'term_id' => 1,
'name' => 'A',
'slug' => 'a',
'term_group' => 0,
'term_taxonomy_id' => 1,
'taxonomy' => 'product_cat',
'description' => '',
'parent' => 0,
'count' => 5, //notice term count still equal to 5 instead of 6
'filter' => 'raw',
)),
)
```
In the case of our example, we said that term name A (term\_id 1) already has 5 objects associated with it, in otherwords already has a term count of 5.
So we would expect the `count` parameter on the returned object above to be 6 but because you did not call `wp_defer_term_counting(false)` after your operation, the term counts were not updated for the terms applicable (term A, B or C).
Therefore that is the **consequence** of calling `wp_defer_term_counting(true)` without calling `wp_defer_term_counting(false)` after your operation.
Now the question is of course, does this effect you? What if you have no need to call `get_the_terms` or perform some action that retrieves the term where by you use the `count` value to perform some other operation? Well in that case **great, no problem for you**.
But... what if someone else is hooked onto `set_object_terms` action in the `wp_set_object_terms()` function and they are relying upon the term count being correct? Now you see where the consequences could arise.
Or what if after the request has terminated, another request is performed that retrieves a taxonomy term and makes use of the `count` property in their business logic? That could be a problem.
While it may sound far fetched that `count` values could be of much harm, we cannot assume the way such data will be used based on our own philosophy.
Also as mentioned in the alternate answer, the count as seen on the taxonomy list table will not be updated either.
In fact the only way to update term counts after you defer term counting and your request has ended is to manually call `wp_update_term_count($terms, $taxonomy)` or wait until someone adds a term for the given taxonomy either via the taxonomy UI or programmatically.
Food for thought. |
219,983 | <p>I need help. Thanks in advance.
I need a function that update post title and slug with some default title + current date when post status is updated from draft to published.</p>
<p>I use this one to update the post date on status change but I need to add a functionality the title also to be updated (with a default one) plus current date also to be shown in the updated title.</p>
<pre><code>//auto change post date on every status change
add_filter('wp_insert_post_data','reset_post_date',99,2);
function reset_post_date($data,$postarr) {
$data['post_date'] = $data['post_modified'];
$data['post_date_gmt'] = $data['post_modified_gmt'];
return $data;
}
</code></pre>
<p>Example:</p>
<p>J. Doe register to my site and publish a new post.</p>
<p>He gives the post some crazy name.</p>
<p>J. Doe's post go to drafts.</p>
<p>After 2 weeks Draft scheduler Plugin takes J. Doe's post from drafts and publish it by changing its status to published.</p>
<p>At this point the desired function has to be able to update the post date with the current date, rename J. Doe's crazy title with a default one, add the current date into the title and update the slug.</p>
| [
{
"answer_id": 219992,
"author": "Grandeto",
"author_id": 90139,
"author_profile": "https://wordpress.stackexchange.com/users/90139",
"pm_score": 1,
"selected": false,
"text": "<p>I think I found the solution:</p>\n\n<pre><code> add_filter('wp_insert_post_data','reset_post_date',99,2);\n... | 2016/03/07 | [
"https://wordpress.stackexchange.com/questions/219983",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90139/"
] | I need help. Thanks in advance.
I need a function that update post title and slug with some default title + current date when post status is updated from draft to published.
I use this one to update the post date on status change but I need to add a functionality the title also to be updated (with a default one) plus current date also to be shown in the updated title.
```
//auto change post date on every status change
add_filter('wp_insert_post_data','reset_post_date',99,2);
function reset_post_date($data,$postarr) {
$data['post_date'] = $data['post_modified'];
$data['post_date_gmt'] = $data['post_modified_gmt'];
return $data;
}
```
Example:
J. Doe register to my site and publish a new post.
He gives the post some crazy name.
J. Doe's post go to drafts.
After 2 weeks Draft scheduler Plugin takes J. Doe's post from drafts and publish it by changing its status to published.
At this point the desired function has to be able to update the post date with the current date, rename J. Doe's crazy title with a default one, add the current date into the title and update the slug. | I think I found the solution:
```
add_filter('wp_insert_post_data','reset_post_date',99,2);
function reset_post_date($data,$postarr) {
//update post time on status change
$data['post_date'] = $data['post_modified'];
$data['post_date_gmt'] = $data['post_modified_gmt'];
//also update title and add the current date to title
$data['post_title'] = 'Your Default Title - '. current_time ( 'm-d-Y' );
//also update the slug of the post for the URL
$data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'] ), $postarr['ID'], $data['post_status'], $data['post_type'], $data['post_parent'] );
return $data;
}
``` |
219,998 | <p>I have a script I'd like to include with Wordpress. This script relies on another (prettyPhoto) to run, as well as on JQuery being loaded. I'd like my script to be the very last script to be included on the page.</p>
<p>After reading about using wp_enqueue_scipt in this answer:
<a href="https://stackoverflow.com/a/19914138/1745715">https://stackoverflow.com/a/19914138/1745715</a></p>
<p>And after fostertime was nice enough to walk me through a little debugging down in the comments below, I've found that I can't enqueue my script, as the last script to load (themify.gallery.js, I was mistaken in the comments below when I thought it was carousel.js) is done so asyncronously in a function inside a Themify javascript file called main.js <em>(themes/themify-ultra/themify/js/main.js)</em></p>
<p>Here's where it's loaded:</p>
<pre><code> InitGallery: function ($el, $args) {
var lightboxConditions = ((themifyScript.lightbox.lightboxContentImages && $(themifyScript.lightbox.contentImagesAreas).length && themifyScript.lightbox.lightboxGalleryOn) || themifyScript.lightbox.lightboxGalleryOn) ? true : false;
if ($('.module.module-gallery').length > 0 || $('.module.module-image').length > 0 || $('.lightbox').length || lightboxConditions) {
if ($('.module.module-gallery').length > 0)
this.showcaseGallery();
this.LoadAsync(themify_vars.url + '/js/themify.gallery.js', function () {
Themify.GalleryCallBack($el, $args);
}, null, null, function () {
return ('undefined' !== typeof ThemifyGallery);
});
}
},
</code></pre>
<p>It would stand to reason that I could simply add my javascript include right here within this function after the line that loads themify.gallery.js. However, I want to ensure that I can upgrade my themify theme without causing the change to be lost. To solve this problem I'm using a child theme. As this main.js is located within the themes folder, is it possible to overwrite it the same way I would a normal template file, and make my change? Even if it is, is it really safe to overwrite the entire main.js file when I'm concerned about my ability to upgrade Themify later down the road? Or Is there a less destructive way to inject my include code into this function from elsewhere? Open to suggestions on the best solution.</p>
| [
{
"answer_id": 220001,
"author": "fostertime",
"author_id": 90145,
"author_profile": "https://wordpress.stackexchange.com/users/90145",
"pm_score": 0,
"selected": false,
"text": "<p>I would have simply commented on your post first, but I don't have enough reputation... :/</p>\n\n<p>Are a... | 2016/03/07 | [
"https://wordpress.stackexchange.com/questions/219998",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90152/"
] | I have a script I'd like to include with Wordpress. This script relies on another (prettyPhoto) to run, as well as on JQuery being loaded. I'd like my script to be the very last script to be included on the page.
After reading about using wp\_enqueue\_scipt in this answer:
<https://stackoverflow.com/a/19914138/1745715>
And after fostertime was nice enough to walk me through a little debugging down in the comments below, I've found that I can't enqueue my script, as the last script to load (themify.gallery.js, I was mistaken in the comments below when I thought it was carousel.js) is done so asyncronously in a function inside a Themify javascript file called main.js *(themes/themify-ultra/themify/js/main.js)*
Here's where it's loaded:
```
InitGallery: function ($el, $args) {
var lightboxConditions = ((themifyScript.lightbox.lightboxContentImages && $(themifyScript.lightbox.contentImagesAreas).length && themifyScript.lightbox.lightboxGalleryOn) || themifyScript.lightbox.lightboxGalleryOn) ? true : false;
if ($('.module.module-gallery').length > 0 || $('.module.module-image').length > 0 || $('.lightbox').length || lightboxConditions) {
if ($('.module.module-gallery').length > 0)
this.showcaseGallery();
this.LoadAsync(themify_vars.url + '/js/themify.gallery.js', function () {
Themify.GalleryCallBack($el, $args);
}, null, null, function () {
return ('undefined' !== typeof ThemifyGallery);
});
}
},
```
It would stand to reason that I could simply add my javascript include right here within this function after the line that loads themify.gallery.js. However, I want to ensure that I can upgrade my themify theme without causing the change to be lost. To solve this problem I'm using a child theme. As this main.js is located within the themes folder, is it possible to overwrite it the same way I would a normal template file, and make my change? Even if it is, is it really safe to overwrite the entire main.js file when I'm concerned about my ability to upgrade Themify later down the road? Or Is there a less destructive way to inject my include code into this function from elsewhere? Open to suggestions on the best solution. | After doing some reading, I found that it is not possible to overwrite one function in a JS file in that way. The solution was to overwrite the entire main.js file in order to make the change. I then enqueued my new main.js script with the exact same name that it was registered to in the original:
```
// Enqueue main js that will load others needed js
wp_register_script('themify-main-script', '/wp-includes/js/main.js', array('jquery'), THEMIFY_VERSION, true);
wp_enqueue_script('themify-main-script');
``` |
220,003 | <p>I'm running a website that uses EasyAdmin (for user content generation).</p>
<p>I created two taxonomies (via functions.php) for my own needs, but now my users can see them when they are adding their content to the website.</p>
<pre><code>add_action( 'init', 'create_item_nominations' );
function create_item_nominations() {
register_taxonomy(
'nominations',
'ait-dir-item',
array(
'label' => __( 'Nominations' ),
'rewrite' => array( 'slug' => 'nominations' ),
'hierarchical' => true,
)
);
}
</code></pre>
<p>I can hide them with CSS but that's not a really nice solution, more like a workaround for a while. </p>
<p>Thank you</p>
| [
{
"answer_id": 220022,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like just setting <code>show_ui</code> to <code>false</code> will do what you're after - it will hi... | 2016/03/07 | [
"https://wordpress.stackexchange.com/questions/220003",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90155/"
] | I'm running a website that uses EasyAdmin (for user content generation).
I created two taxonomies (via functions.php) for my own needs, but now my users can see them when they are adding their content to the website.
```
add_action( 'init', 'create_item_nominations' );
function create_item_nominations() {
register_taxonomy(
'nominations',
'ait-dir-item',
array(
'label' => __( 'Nominations' ),
'rewrite' => array( 'slug' => 'nominations' ),
'hierarchical' => true,
)
);
}
```
I can hide them with CSS but that's not a really nice solution, more like a workaround for a while.
Thank you | Sounds like just setting `show_ui` to `false` will do what you're after - it will hide the taxonomy in the admin menu, and it won't create a metabox on the post edit page.
After this:
`'hierarchical' => true,`
Add this:
`'show_ui' => false,`
You'll find a full reference of all the available arguments over at the Wordpress codex: <https://codex.wordpress.org/Function_Reference/register_taxonomy>
**EDIT:** (thanks to Howdy\_McGee in the comments)
This will hide from all backend users including admins. If you want the taxonomy to be visible just for admins but not lower level users, instead use:
`'show_ui' => current_user_can( 'administrator' ),`
Instead of 'administrator' here, you can also use any role at <https://codex.wordpress.org/Roles_and_Capabilities> if you want more fine-grained control. |
220,004 | <p>Basically what I am trying to achieve is to have title changed of posts which are in category number 30.</p>
<p>My code is:</p>
<pre><code>function adddd($title) {
if(has_category('30',$post->ID)){
$title = 'Prefix '.$title;
}
return $title;
}
add_action('the_title','adddd');
</code></pre>
<p>The code works, but has one issue. When I am inside the post which has that category, title is being changed for all other pages (which are called through the_title) too.</p>
<p>How can I change the title only to post titles which has that category, no matter what page I am on?</p>
| [
{
"answer_id": 220005,
"author": "nicogaldo",
"author_id": 87880,
"author_profile": "https://wordpress.stackexchange.com/users/87880",
"pm_score": 0,
"selected": false,
"text": "<p>Why not use javascript/jquery?</p>\n<p>if your use <code><?php post_class(); ?></code> you can find a... | 2016/03/07 | [
"https://wordpress.stackexchange.com/questions/220004",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66106/"
] | Basically what I am trying to achieve is to have title changed of posts which are in category number 30.
My code is:
```
function adddd($title) {
if(has_category('30',$post->ID)){
$title = 'Prefix '.$title;
}
return $title;
}
add_action('the_title','adddd');
```
The code works, but has one issue. When I am inside the post which has that category, title is being changed for all other pages (which are called through the\_title) too.
How can I change the title only to post titles which has that category, no matter what page I am on? | `$post` is undefined in your filter. You need to explicitely invoke the `$post` global inside your filter function to have it available. You must remember that variables (*even global variables*) outside a function will not be available inside a function, that is how PHP works.
You actually do not need to use the `$post` global, the post ID is passed by reference as second parameter to the `the_title` filter.
You can use the following:
```
add_action( 'the_title', 'adddd', 10, 2 );
function adddd( $title, $post_id )
{
if( has_category( 30, $post_id ) ) {
$title = 'Prefix ' . $title;
}
return $title;
}
```
If you need to target only the titles of posts in the main query/loop, you can wrap your contional in an extra `in_the_loop()` condition |
220,014 | <p>My <code>WP_Query</code> request looks like:</p>
<pre><code>$query_args = array('posts_per_page' => $products, 'no_found_rows' => 1, 'post_status' => 'publish', 'post_type' => 'product' );
$query_args['meta_query'] = $woocommerce->query->get_meta_query();
$query_args['meta_query'][] = array(
'key' => '_featured',
'value' => 'yes'
);
$r = new WP_Query($query_args);
</code></pre>
<p>What argument I need to add to return a query ordered by IDs in a particular row (ex. I need to return products IDs 161,165,131,202 in that order).</p>
<p>Edit: I have added a <code>post__in</code> and <code>orderby</code> arguments which pulls only those particular products by IDs but not in the order specified in the array but it looks like based on when product was added to the back end.</p>
<pre><code>$query_args = array('posts_per_page' => $products, 'no_found_rows' => 1, 'post_status' => 'publish', 'post_type' => 'product', 'post__in' => array(161,165,131,202), 'orderby' => 'post__in', 'order' => 'ASC' );
</code></pre>
<p>WP Query for that looks like:</p>
<pre><code>SELECT wp_posts.ID
FROM wp_posts
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id )
WHERE 1=1
AND wp_posts.ID IN (161,165,131,202)
AND wp_posts.post_type = 'product'
AND ((wp_posts.post_status = 'publish'))
AND ( ( wp_postmeta.meta_key = '_visibility'
AND CAST(wp_postmeta.meta_value AS CHAR) IN ('visible','catalog') )
AND (mt1.meta_key = '_featured' AND CAST(mt1.meta_value AS CHAR) = 'yes' ))
GROUP BY wp_posts.ID
ORDER BY wp_posts.menu_order, FIELD( wp_posts.ID, 161,165,131,202 )
LIMIT 0, 5
</code></pre>
<p>no clue why <code>ORDER BY</code> is set to be <code>menu_order</code> not <code>post__in</code></p>
| [
{
"answer_id": 220023,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 0,
"selected": false,
"text": "<p>You can order in ascending or descending order, but you can't specify a custom order - in the query parame... | 2016/03/07 | [
"https://wordpress.stackexchange.com/questions/220014",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28491/"
] | My `WP_Query` request looks like:
```
$query_args = array('posts_per_page' => $products, 'no_found_rows' => 1, 'post_status' => 'publish', 'post_type' => 'product' );
$query_args['meta_query'] = $woocommerce->query->get_meta_query();
$query_args['meta_query'][] = array(
'key' => '_featured',
'value' => 'yes'
);
$r = new WP_Query($query_args);
```
What argument I need to add to return a query ordered by IDs in a particular row (ex. I need to return products IDs 161,165,131,202 in that order).
Edit: I have added a `post__in` and `orderby` arguments which pulls only those particular products by IDs but not in the order specified in the array but it looks like based on when product was added to the back end.
```
$query_args = array('posts_per_page' => $products, 'no_found_rows' => 1, 'post_status' => 'publish', 'post_type' => 'product', 'post__in' => array(161,165,131,202), 'orderby' => 'post__in', 'order' => 'ASC' );
```
WP Query for that looks like:
```
SELECT wp_posts.ID
FROM wp_posts
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id )
WHERE 1=1
AND wp_posts.ID IN (161,165,131,202)
AND wp_posts.post_type = 'product'
AND ((wp_posts.post_status = 'publish'))
AND ( ( wp_postmeta.meta_key = '_visibility'
AND CAST(wp_postmeta.meta_value AS CHAR) IN ('visible','catalog') )
AND (mt1.meta_key = '_featured' AND CAST(mt1.meta_value AS CHAR) = 'yes' ))
GROUP BY wp_posts.ID
ORDER BY wp_posts.menu_order, FIELD( wp_posts.ID, 161,165,131,202 )
LIMIT 0, 5
```
no clue why `ORDER BY` is set to be `menu_order` not `post__in` | To keep the same post order as it was passed to the `post__in` parameter, you need to pass `post__in` as value to `orderby` argument and `ASC` to the `order` argument
```
$query_args = [
'posts_per_page' => $products,
'no_found_rows' => true,
'post_type' => 'product',
'post__in' => [161,165,131,202],
'orderby' => 'post__in',
'order' => 'ASC'
];
```
EDIT
----
Looking at your edit, you have a bad filter somewhere, most probably a bad `pre_get_posts` action or a `posts_orderby` filter. Do the two following tests
* Add `'suppress_filters' => true,` to your query arguments, if that helps, you have a bad filter
* Add `remove_all_actions( 'pre_get_posts' );` before you do your query, if that helps, you have a bad `pre_get_posts` filter
* A third, but most probable useless check would be to add `wp_reset_query()` before the custom query, if that helps, you have a bad query somewhere, most probably one using `query_posts` |
220,021 | <p>It took me great time today to convert one site from <a href="https://example.com" rel="nofollow">https://example.com</a> to <a href="https://sub.example2.com" rel="nofollow">https://sub.example2.com</a> from WordPress multiste installation to normal WordPress installation (read: singlesite). </p>
<p>Since I started using wp-cli recently I thought it will be possible to do it only with wp-cli.</p>
<p>I used wp-cli to export a database. Since my instance was prefixed as: <code>wp_9_</code></p>
<p>I used the code like this:</p>
<pre><code>wp db export --tables="wp_users, wp_usermeta, wp_9_posts, wp_9_comments, wp_9_links, wp_9_options, wp_9_postmeta, wp_9_terms, wp_9_term_taxonomy, wp_9_term_relationships, wp_9_termmeta, wp_9_commentmeta"
</code></pre>
<p>While I later found I should use something like this:</p>
<pre><code>wp db export --tables=wp_users,wp_usermeta, $(wp db tables --all-tables-with-prefix 'wp_9' --format=csv --allow-root) --allow-root
</code></pre>
<p>For those not using the #</p>
<pre><code>wp db export --tables=wp_users,wp_usermeta, $(wp db tables --all-tables-with-prefix 'wp_9' --format=csv)
</code></pre>
<p>Then I set:</p>
<pre><code>define('WP_HOME','https://sub.example2.com');
define('WP_SITEURL','https://sub.example2.com');
</code></pre>
<p>But I faced the problem: posts, guids, and meta not updated...
Usually I never do the next step since it just works in numerous instances. </p>
<p>But I was forced to do the following:</p>
<pre><code>UPDATE wp_posts SET post_content = replace(post_content, 'https://example.com', 'https://sub.example2.com');
UPDATE wp_posts SET guid = replace(guid, 'https://example.com', 'https://sub.example2.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'https://example.com', 'https://sub.example2.com');
</code></pre>
<p>Even further, I needed to update the uploads path, in the post content and even in the post_meta, since on mulitsite the uploads path was <code>/uploads/sites/9/</code> while on a single site only <code>/uploads/</code>.</p>
<p>This should also reflect in the posts and post meta like this:</p>
<pre><code>UPDATE wp_posts SET post_content = replace(post_content, '/uploads/sites/9/', '/uploads/');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'/uploads/sites/9/', '/uploads/');
</code></pre>
<p>After this step, I manually copied files from /uploads/sites/9/ folder to the /uploads/ folder of the new WordPress instance on the same server using the <code>cp</code> command. Sadly, I haven't even considered wp-cli for that.</p>
<p>I am asking is it possible to automate this processes entirely using wp-cli?
It would be a great helper next time.</p>
| [
{
"answer_id": 225620,
"author": "AntonChanning",
"author_id": 5077,
"author_profile": "https://wordpress.stackexchange.com/users/5077",
"pm_score": 1,
"selected": false,
"text": "<p>If your multi-site install only has a small number of subsites, you might find it easier to just use the ... | 2016/03/08 | [
"https://wordpress.stackexchange.com/questions/220021",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88606/"
] | It took me great time today to convert one site from <https://example.com> to <https://sub.example2.com> from WordPress multiste installation to normal WordPress installation (read: singlesite).
Since I started using wp-cli recently I thought it will be possible to do it only with wp-cli.
I used wp-cli to export a database. Since my instance was prefixed as: `wp_9_`
I used the code like this:
```
wp db export --tables="wp_users, wp_usermeta, wp_9_posts, wp_9_comments, wp_9_links, wp_9_options, wp_9_postmeta, wp_9_terms, wp_9_term_taxonomy, wp_9_term_relationships, wp_9_termmeta, wp_9_commentmeta"
```
While I later found I should use something like this:
```
wp db export --tables=wp_users,wp_usermeta, $(wp db tables --all-tables-with-prefix 'wp_9' --format=csv --allow-root) --allow-root
```
For those not using the #
```
wp db export --tables=wp_users,wp_usermeta, $(wp db tables --all-tables-with-prefix 'wp_9' --format=csv)
```
Then I set:
```
define('WP_HOME','https://sub.example2.com');
define('WP_SITEURL','https://sub.example2.com');
```
But I faced the problem: posts, guids, and meta not updated...
Usually I never do the next step since it just works in numerous instances.
But I was forced to do the following:
```
UPDATE wp_posts SET post_content = replace(post_content, 'https://example.com', 'https://sub.example2.com');
UPDATE wp_posts SET guid = replace(guid, 'https://example.com', 'https://sub.example2.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'https://example.com', 'https://sub.example2.com');
```
Even further, I needed to update the uploads path, in the post content and even in the post\_meta, since on mulitsite the uploads path was `/uploads/sites/9/` while on a single site only `/uploads/`.
This should also reflect in the posts and post meta like this:
```
UPDATE wp_posts SET post_content = replace(post_content, '/uploads/sites/9/', '/uploads/');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'/uploads/sites/9/', '/uploads/');
```
After this step, I manually copied files from /uploads/sites/9/ folder to the /uploads/ folder of the new WordPress instance on the same server using the `cp` command. Sadly, I haven't even considered wp-cli for that.
I am asking is it possible to automate this processes entirely using wp-cli?
It would be a great helper next time. | Try using the `10up/MU-Migration` command: <https://github.com/10up/MU-Migration> |
220,029 | <p>I want to display a product with a product image and when visitor hovers over that image, it will change to the first image from the product gallery. I am using this code to display the image gallery, but it displays all the images from product gallery. I just want the 1 image.</p>
<pre><code> <?php do_action( 'woocommerce_product_thumbnails' ); ?>
</code></pre>
<p>Anybody know how to resolve this problem? Really appreciate any ideas.</p>
<p>Regards</p>
| [
{
"answer_id": 220036,
"author": "Isaac Lubow",
"author_id": 2150,
"author_profile": "https://wordpress.stackexchange.com/users/2150",
"pm_score": 3,
"selected": true,
"text": "<p>Along with the product thumbnail (I'm assuming you have this), what you need is a list (array) of the produc... | 2016/03/08 | [
"https://wordpress.stackexchange.com/questions/220029",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89109/"
] | I want to display a product with a product image and when visitor hovers over that image, it will change to the first image from the product gallery. I am using this code to display the image gallery, but it displays all the images from product gallery. I just want the 1 image.
```
<?php do_action( 'woocommerce_product_thumbnails' ); ?>
```
Anybody know how to resolve this problem? Really appreciate any ideas.
Regards | Along with the product thumbnail (I'm assuming you have this), what you need is a list (array) of the product images - WooCommerce has such methods, eg `$product->get_gallery_attachment_ids()`.
You can grab the first ID in the array and use it to fetch the single image using [`wp_get_attachment_image()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image/), or [`wp_get_attachment_url()`](https://codex.wordpress.org/Function_Reference/wp_get_attachment_url), etc., then use that as an alternate source for the main (thumbnail) image.
Incidentally, the `woocommerce_product_thumbnails` call is outputting markup that you probably don't want to use. You'll need to either discard this or unhook functions from it to get the output you want. |
220,059 | <p>A WordPress website is created and MySQL is the database for it. When tried to import the database to an empty database via Linux Command Shell we encountered below errors:</p>
<blockquote>
<p>ERROR 1146 (42S02): Table 'xx-xxx-xxx-xxx' doesn't exist</p>
<p>ERROR 1273 (HY000): Unknown collation: 'utf8mb4_unicode_ci'</p>
<p>ERROR 1115 (42000): Unknown character set: 'utf8mb4'</p>
</blockquote>
<p>What could be the possible cause for these errors? Or should we try an alternative step to restore my WordPress website?</p>
<p>The source database version is mysqlnd 5.0.12 and the destination database is mySQL 5.1.66.</p>
| [
{
"answer_id": 220061,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p>When exporting from original database you should choose to create the tables if they dosn't exist (First erro... | 2016/03/08 | [
"https://wordpress.stackexchange.com/questions/220059",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75992/"
] | A WordPress website is created and MySQL is the database for it. When tried to import the database to an empty database via Linux Command Shell we encountered below errors:
>
> ERROR 1146 (42S02): Table 'xx-xxx-xxx-xxx' doesn't exist
>
>
> ERROR 1273 (HY000): Unknown collation: 'utf8mb4\_unicode\_ci'
>
>
> ERROR 1115 (42000): Unknown character set: 'utf8mb4'
>
>
>
What could be the possible cause for these errors? Or should we try an alternative step to restore my WordPress website?
The source database version is mysqlnd 5.0.12 and the destination database is mySQL 5.1.66. | When exporting from original database you should choose to create the tables if they dosn't exist (First error). If you didn't choose that option (in phpMyAdmin that option exists, not sure in other database tools), the import file can not create the tables for your and you need to create then prior to start importing it.
For second and third error, you should upgrade your database version to MySQL 5.5.3 or later. Although WordPress can run on MySQL 5.0+, [the recommended MySQL version is 5.6 or greater](https://wordpress.org/about/requirements/). The problem is that WordPress updates the database to use utf8mb4 if database version is 5.5.3 or later, so probably the source database version was greater than 5.5.3 and the destination database version is lesser than 5.5.3.
If you can not upgrade the destination databser version, edit the import file to change the collation utf8\_general\_ci and character set to utf8.
Lood for lines similar to:
```
SET character_set_client = utf8mb4 ;
SET character_set_results = utf8mb4 ;
SET collation_connection = utf8mb4_unicode_ci;
```
and change them. |
220,073 | <p>While looking for proper form submission handling in plugins for users (frontend) I've stumbled upon this article <a href="http://www.sitepoint.com/handling-post-requests-the-wordpress-way/">Handling POST Requests the WordPress Way</a>, which encourages to use <code>admin-post.php</code> for this purpose. Taking a look into header we can find some kind of confirmation:</p>
<pre><code> /**
* WordPress Generic Request (POST/GET) Handler
*
* Intended for form submission handling in themes and plugins.
*
* @package WordPress
* @subpackage Administration
*/
</code></pre>
<p>My main concern is that this method comes from admin part of WP code and its use in non-admin tasks makes some ambiguity.</p>
<p>Can anyone (especially WP authors) confirm that this approach intention is really holistic or admin only as I think?</p>
| [
{
"answer_id": 220074,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": false,
"text": "<p>Seems fairly clear from the use of the <code>nopriv</code> handling (for non logged in users) in <code>admin-p... | 2016/03/08 | [
"https://wordpress.stackexchange.com/questions/220073",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89088/"
] | While looking for proper form submission handling in plugins for users (frontend) I've stumbled upon this article [Handling POST Requests the WordPress Way](http://www.sitepoint.com/handling-post-requests-the-wordpress-way/), which encourages to use `admin-post.php` for this purpose. Taking a look into header we can find some kind of confirmation:
```
/**
* WordPress Generic Request (POST/GET) Handler
*
* Intended for form submission handling in themes and plugins.
*
* @package WordPress
* @subpackage Administration
*/
```
My main concern is that this method comes from admin part of WP code and its use in non-admin tasks makes some ambiguity.
Can anyone (especially WP authors) confirm that this approach intention is really holistic or admin only as I think? | `admin-post.php` is like a poor mans controller for handling requests.
It's useful in the sense that you don't need to process your request on an alternative hook such as `init` and check to see whether or not special keys exists on the superglobals, like:
```
function handle_request() {
if ( !empty($_POST['action']) && $_POST['action'] === 'xyz' ) {
//do business logic
}
}
add_action('init', 'handle_request');
```
Instead using admin-post.php affords you the ability to specify a callback function that will always be called on any request that supplies an action value that matches the suffix supplied to the action.
```
function handle_request() {
//do business logic here...
}
add_action( 'admin_post_handle_request', 'handle_request' );
add_action( 'admin_post_nopriv_handle_request', 'handle_request' );
```
In the above example, we can forgoe the need to check for `!empty($_POST['action']) && $_POST['action'] === 'xyz'` because at this point that processing has been taken care of for us.
That is the result of the specifying the action parameter and value and posting said value to the `admin-post.php` URL.
Additionally what is beneficial is that `admin-post.php` handles both `$_POST` and `$_GET` so it's not neccessary to check what kind of method the request is of course unless you want to for more complex processing.
Bottom line:
It is safe to use, it's just the name that throws you off.
By the way you should also remember to `wp_redirect()` the user back to an acceptable location as requesting `admin-post.php` will return nothing but a white screen as its response. |
220,079 | <p>I use this function to insert at the beginning of the loop two post at my convenience (with meta key and value) </p>
<pre><code>add_filter( 'posts_results', 'insert_post_wpse_96347', 10, 2 );
function insert_post_wpse_96347( $posts, \WP_Query $q ) {
remove_filter( current_filter(), __FUNCTION__ );
if ( $q->is_main_query() && $q->is_home() && 0 == get_query_var( 'paged' ) ) {
$args = [
'meta_key' => 'caja',
'meta_value' => ['uno','dos'],
'post__not_in' => get_option( "sticky_posts" ),
'posts_per_page' => '2',
'suppress_filters' => true
];
$p2insert = new WP_Query($args);
$insert_at = 0;
if ( !empty( $p2insert->posts ) ) {
array_splice( $posts, $insert_at, 0, $p2insert->posts );
}
}
return $posts;
}
</code></pre>
<p>But these posts still appear in the loop, they would have to hide to not look twice.</p>
<p>How can I do this?</p>
| [
{
"answer_id": 220094,
"author": "Adam",
"author_id": 13418,
"author_profile": "https://wordpress.stackexchange.com/users/13418",
"pm_score": 0,
"selected": false,
"text": "<p>Try this instead:</p>\n\n<p><strong>NOTE: make sure to add any extra conditional logic you need for your usecase... | 2016/03/08 | [
"https://wordpress.stackexchange.com/questions/220079",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87880/"
] | I use this function to insert at the beginning of the loop two post at my convenience (with meta key and value)
```
add_filter( 'posts_results', 'insert_post_wpse_96347', 10, 2 );
function insert_post_wpse_96347( $posts, \WP_Query $q ) {
remove_filter( current_filter(), __FUNCTION__ );
if ( $q->is_main_query() && $q->is_home() && 0 == get_query_var( 'paged' ) ) {
$args = [
'meta_key' => 'caja',
'meta_value' => ['uno','dos'],
'post__not_in' => get_option( "sticky_posts" ),
'posts_per_page' => '2',
'suppress_filters' => true
];
$p2insert = new WP_Query($args);
$insert_at = 0;
if ( !empty( $p2insert->posts ) ) {
array_splice( $posts, $insert_at, 0, $p2insert->posts );
}
}
return $posts;
}
```
But these posts still appear in the loop, they would have to hide to not look twice.
How can I do this? | We can try the following alternative way:
* Remove the two posts we select via our custom query from the main query via the `pre_get_posts` action
* Return the two posts on top of page one via the `the_posts` filter
Lets look at possible code:
```
add_action( 'pre_get_posts', function ( $q )
{
remove_filter( current_filter(), __FUNCTION__ );
if ( $q->is_home() // Only target the home page
&& $q->is_main_query() // Only target the main query
) {
// Set our query args and run our query to get the required post ID's
$args = [
'meta_key' => 'caja',
'meta_value' => ['uno','dos'],
'posts_per_page' => '2',
'fields' => 'ids', // Get only post ID's
];
$ids = get_posts( $args );
// Make sure we have ID's, if not, bail
if ( !$ids )
return;
// We have id's, lets remove them from the main query
$q->set( 'post__not_in', $ids );
// Lets add the two posts in front on page one
if ( $q->is_paged() )
return;
add_filter( 'the_posts', function ( $posts, $q ) use ( $args )
{
if ( !$q->is_main_query() )
return $posts;
// Lets run our query to get the posts to add
$args['fields'] = 'all';
$posts_to_add = get_posts( $args );
$stickies = get_option( 'sticky_posts' );
if ( $stickies ) {
$sticky_count = count( $stickies );
array_splice( $posts, $sticky_count, 0, $posts_to_add );
return $posts;
}
// Add these two posts in front
$posts = array_merge( $posts_to_add, $posts );
return $posts;
}, 10, 2 );
}
});
```
This should replace the current code that you have posted in your question |
220,082 | <p>For each post, I use the custom excerpt field to write a custom excerpt (180 characters max) for each of my posts, which I use as the meta description of my post for SEO.</p>
<p>When I show a list of my posts (archive pages, categories etc.) this excerpt is displayed as "teaser text" for each of my posts. The problem is that this text is too short, as it is written for meta description purposes.</p>
<p>Would it be possible to have a longer excerpt showing in category and index pages, yet keep my custom excerpt as a meta description of each post?</p>
<p>Btw, most of my posts have a specifically placed "read more" tag, which now is ignored as I have a custom excerpt.</p>
| [
{
"answer_id": 220098,
"author": "thebigtine",
"author_id": 76059,
"author_profile": "https://wordpress.stackexchange.com/users/76059",
"pm_score": 1,
"selected": false,
"text": "<p>This is a function that I use all the time to create a custom excerpt:</p>\n\n<pre><code>function custom_e... | 2016/03/08 | [
"https://wordpress.stackexchange.com/questions/220082",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80031/"
] | For each post, I use the custom excerpt field to write a custom excerpt (180 characters max) for each of my posts, which I use as the meta description of my post for SEO.
When I show a list of my posts (archive pages, categories etc.) this excerpt is displayed as "teaser text" for each of my posts. The problem is that this text is too short, as it is written for meta description purposes.
Would it be possible to have a longer excerpt showing in category and index pages, yet keep my custom excerpt as a meta description of each post?
Btw, most of my posts have a specifically placed "read more" tag, which now is ignored as I have a custom excerpt. | We can try to filter the excerpt through the [`get_the_excerpt`](https://developer.wordpress.org/reference/hooks/get_the_excerpt/) filter. By default, if we have a manual excerpt, the manual excerpt will be used and not the automatically created excerpt which is created by the [`wp_trim_excerpt()`](https://developer.wordpress.org/reference/functions/wp_trim_excerpt/) function.
We can alter this behavior. What we will do is, when we are inside the main query (*`in_the_loop()`*), we will return the output from the `wp_trim_excerpt()` function. This way, we keep all filters as per default. Whenever we are outside the main query, we can return the manually created excerpt, if it exists, otherwise the normal excerpt
```
add_filter( 'get_the_excerpt', function( $text )
{
if ( in_the_loop() )
return wp_trim_excerpt();
return $text;
});
``` |
220,111 | <p>I want to pass a variable from my child theme function to a filter which resides in my parent theme. Please let me know whether below code will work or not ? Is it the right way ?</p>
<p><strong>Code in Parent Theme's functions.php</strong></p>
<pre><code>add_filter( 'post_thumbnail_html', "map_thumbnail" );
function map_thumbnail($html,$color) {
$my_post = get_post($post->ID);
$my_color = $color;
if($my_post->post_name == "contact") {
$html = '<img src="http://maps.googleapis.com/maps/api/staticmap?color:$my_color">';
}
return $html;
}
</code></pre>
<p><strong>Code in Child Theme's functions.php</strong></p>
<pre><code><?php map_thumbnail('#0099dd'); ?>
</code></pre>
<p>Please tell me, will above code work? Can I pass the variable <code>$color</code> from my child theme to parent theme like this ?</p>
| [
{
"answer_id": 220113,
"author": "Brent",
"author_id": 10972,
"author_profile": "https://wordpress.stackexchange.com/users/10972",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not exactly sure what you're trying to accomplish but this won't work because your trying to use or call th... | 2016/03/08 | [
"https://wordpress.stackexchange.com/questions/220111",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81686/"
] | I want to pass a variable from my child theme function to a filter which resides in my parent theme. Please let me know whether below code will work or not ? Is it the right way ?
**Code in Parent Theme's functions.php**
```
add_filter( 'post_thumbnail_html', "map_thumbnail" );
function map_thumbnail($html,$color) {
$my_post = get_post($post->ID);
$my_color = $color;
if($my_post->post_name == "contact") {
$html = '<img src="http://maps.googleapis.com/maps/api/staticmap?color:$my_color">';
}
return $html;
}
```
**Code in Child Theme's functions.php**
```
<?php map_thumbnail('#0099dd'); ?>
```
Please tell me, will above code work? Can I pass the variable `$color` from my child theme to parent theme like this ? | I'm not exactly sure what you're trying to accomplish but this won't work because your trying to use or call the function that is declared in the parent theme instead of replacing it with a new function. I'm not sure if replacing a function in the child theme would work either. Maybe someone else can help answer that.
The function `map_thumbnail()` that you're trying to call in the child theme, is actually being used by the `add_filter()` function right above it to modify the existing function `post_thumbnail_html()`.
Additionally, even if it would work, you only passed one paramater ('#0099dd') in your attempt to call the function, and it appears to be out of order. |
220,122 | <p>I have just had to deal with a few of my WordPress websites being hacked. First time put an index.html file in the cpanel of each site and replenished my admin user. Once I felt I cleaned this up, it's happened once again but it changed my title tag to "Hacked by Bala Sniper" and the widgets from the footer of each website were removed.</p>
<p>My WHM account isn't WP only websites so I know it can't be a hacker accessing from there.</p>
<p>I've Googled this many times and rectified a few issues such as not making the id=1 to be admin, captcha plugin amongst a few others.</p>
<p>I feel this is going to happen once again. I'm on here to ask if anyone has had this problem today or yesterday or if you've ever had this hacked by bala sniper title tag change etc. and if you cleaned up the problem and tightened your security, to hopefully help me out amongst anyone else who reads this.</p>
<p>What is concerning me the most is that it's been every single wordpress site on my WHM was compromised and I've not found anything where every single site has something similar to them all.</p>
<p>Thanks for anyone to helps, I have googled this and rectified as much issues I've neglected, just need to know why all of my WP accounts were effected.</p>
<p>Dev</p>
| [
{
"answer_id": 224778,
"author": "dExIT",
"author_id": 92983,
"author_profile": "https://wordpress.stackexchange.com/users/92983",
"pm_score": 1,
"selected": false,
"text": "<p>I wanted to state, this happened to me a few times in the early WP 3.x days.\nAm using GoDaddy shared hsoting e... | 2016/03/08 | [
"https://wordpress.stackexchange.com/questions/220122",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86831/"
] | I have just had to deal with a few of my WordPress websites being hacked. First time put an index.html file in the cpanel of each site and replenished my admin user. Once I felt I cleaned this up, it's happened once again but it changed my title tag to "Hacked by Bala Sniper" and the widgets from the footer of each website were removed.
My WHM account isn't WP only websites so I know it can't be a hacker accessing from there.
I've Googled this many times and rectified a few issues such as not making the id=1 to be admin, captcha plugin amongst a few others.
I feel this is going to happen once again. I'm on here to ask if anyone has had this problem today or yesterday or if you've ever had this hacked by bala sniper title tag change etc. and if you cleaned up the problem and tightened your security, to hopefully help me out amongst anyone else who reads this.
What is concerning me the most is that it's been every single wordpress site on my WHM was compromised and I've not found anything where every single site has something similar to them all.
Thanks for anyone to helps, I have googled this and rectified as much issues I've neglected, just need to know why all of my WP accounts were effected.
Dev | *wordpress configuration file is located in the root*.In the event that PHP stops functioning on webserver for any reason.we run the risk of this file being displayed in plaintext,which will give our password and database information to visitor.
you can safely move **wp-config** directory up out of root directory.this will stop if from accidentally served. Wordpress has built-in functionality that automatic check parent directory if it cannot find a configuration file.
In this situations on certain hosts, is not option. An alternative on Apache web servers is to set your **.htaccess** to not serve up the **wp-config** file.
Add the following line to ur **.htaccess** file in the root directory.
```
<FilesMatch ^wp-config.php$>deny from all</FilesMatch>
``` |
220,163 | <p>I need to cross reference two taxonomies, <code>product_categories</code> and <code>brands</code>. the only way I can think to do this is to get all the posts in one taxonomy, then get all the posts that exist in another taxonomy:</p>
<pre><code><?php
$category = /* Taxonomy object selected from list */;
// Get all the posts in this query
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => $category->taxonomy,
'field' => 'slug',
'terms' => $category->slug
)
)
);
$product_items = get_posts( $args );
// create a blank array ready for the IDs
$product_items_ids = [];
// For every post found, populate the array
foreach ($product_items as $product_item) {
// Create array from all post IDs in category
$product_items_ids[] = $product_item->ID;
}
// Get all terms in Brand taxonomy that are in the array above
$brand_items = wp_get_object_terms( $product_items_ids, 'brand' );
// Output the information needed
foreach ($brand_items as $brand_item) { ?>
<li><a href="<?php echo get_term_link( $brand_item->slug, $brand_item->taxonomy ); ?>"> <?php echo $brand_item->name; ?></a></li>
<?php } ?>
</code></pre>
<p>I'm calling this in 5-10 times, and if the product listings become vast, this means i'm calling in every post on the site 10 times to load the menu etc.</p>
<p>Is there a more efficient way of doing this type of query?</p>
<hr>
<p>Addition things to note:</p>
<p>The first query pulls in the posts assigned the taxonomy of <code>$category->taxonomy</code>.</p>
<p><code>$category</code> is a taxonomy object selected in the admin by Advanced Custom Fields. For this example, say <strong>accessories</strong> is a term, and <code>product_cat</code> is the taxonomy @PieterGoosen</p>
<p>I need to return all the terms in brands that are also posts with the accessories term.</p>
| [
{
"answer_id": 220213,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 0,
"selected": false,
"text": "<p>I am not so good with SQL. But this query does the job for me, I just combined two queries into one!</p>\n\n<pr... | 2016/03/09 | [
"https://wordpress.stackexchange.com/questions/220163",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27504/"
] | I need to cross reference two taxonomies, `product_categories` and `brands`. the only way I can think to do this is to get all the posts in one taxonomy, then get all the posts that exist in another taxonomy:
```
<?php
$category = /* Taxonomy object selected from list */;
// Get all the posts in this query
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => $category->taxonomy,
'field' => 'slug',
'terms' => $category->slug
)
)
);
$product_items = get_posts( $args );
// create a blank array ready for the IDs
$product_items_ids = [];
// For every post found, populate the array
foreach ($product_items as $product_item) {
// Create array from all post IDs in category
$product_items_ids[] = $product_item->ID;
}
// Get all terms in Brand taxonomy that are in the array above
$brand_items = wp_get_object_terms( $product_items_ids, 'brand' );
// Output the information needed
foreach ($brand_items as $brand_item) { ?>
<li><a href="<?php echo get_term_link( $brand_item->slug, $brand_item->taxonomy ); ?>"> <?php echo $brand_item->name; ?></a></li>
<?php } ?>
```
I'm calling this in 5-10 times, and if the product listings become vast, this means i'm calling in every post on the site 10 times to load the menu etc.
Is there a more efficient way of doing this type of query?
---
Addition things to note:
The first query pulls in the posts assigned the taxonomy of `$category->taxonomy`.
`$category` is a taxonomy object selected in the admin by Advanced Custom Fields. For this example, say **accessories** is a term, and `product_cat` is the taxonomy @PieterGoosen
I need to return all the terms in brands that are also posts with the accessories term. | We can do quite a lot to improve performance of your code. Lets set some benchmarks first
BENCH MARKS
-----------
* I'm testing this with a
+ `category` taxonomy term which has 9 posts and
+ the `post_tag` taxonomy with 61 matching tags.
With your current code, I get the following results
* ***69 queries in =/- 0.4s***
That is pretty expensive and a huge amount of queries on such a small database and test subject
OPTIMIZATIONS
-------------
The first thing we will do, is to query only the post ID's from the posts because of the following reasons
* We do not need any post data
* We do not need post cache and post meta cache updated, we do not need that
* Obviously, only querying post ID's will increase performance drastically
Only querying the ID's have the drawback in that we also loose the term cache. Because we do not update the term cache, this will lead to a huge increase in db queries. In order to solve that, we will manually update the term cache with `update_object_term_cache`.
By this time, just on your query alone, you have gained 1db call and 0.02s, which is not that much, but it makes a huge difference on a huge database. The real gain will come in the next section
The really big gain is by passing the term object to `get_term_link()`, and not the term ID. If there is no terms in the term cache, and you pass the term ID to `get_term_link()`, instead of getting the term object from the cache, `get_term_link()` will query the db to get the term object. Just on test, this amounts to an extra 61 db calls, one per tag. Think about a few hundred tags.
We already have the term object, so we can simply pass the complete term object. You should always do that. Even if the term object is in cache, it is still very marginally slower to pass the term ID as we must still get the term object from the cache
I have cleaned up your code a bit. Note, I have used short array syntax which do need PHP 5.4+. Here is how your code could look like
```
$category = get_category( 13 ); // JUST FOR TESTING< ADJUST TO YOUR NEEDS
$args = [
'post_type' => 'product',
'fields' => 'ids', // Only query the post ID's, not complete post objects
'tax_query' => [
[
'taxonomy' => $category->taxonomy,
'field' => 'slug',
'terms' => $category->slug
]
]
];
$ids = get_posts( $args );
$links = [];
// Make sure we have ID'saves
if ( $ids ) {
/**
* Because we only query post ID's, the post caches are not updated which is
* good and bad
*
* GOOD -> It saves on resources because we do not need post data or post meta data
* BAD -> We loose the vital term cache, which will result in even more db calls
*
* To solve that, we manually update the term cache with update_object_term_cache
*/
update_object_term_cache( $ids, 'product' );
$term_names = [];
foreach ( $ids as $id ) {
$terms = get_object_term_cache( $id, 'post_tag' );
foreach ( $terms as $term ) {
if ( in_array( $term->name, $term_names ) )
continue;
$term_names[] = $term->name;
$links[$term->name] = '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>';
}
}
}
if ( $links ) {
ksort( $links );
$link_string = implode( "\n\t" , $links );
} else {
$link_string = '';
}
echo $link_string;
```
As it now stand, we have reduced the numbers down to ***6 db queries in 0.04s*** which is a huge improvement.
We can even go further and store the results in a transient
```
$category = get_category( 13 ); // JUST FOR TESTING< ADJUST TO YOUR NEEDS
$link_string = '';
$transient_name = 'query_' . md5( $category->slug . $category->taxonomy );
if ( false === ( $link_string = get_transient( $transient_name ) ) ) {
$args = [
'post_type' => 'product',
'fields' => 'ids', // Only query the post ID's, not complete post objects
'tax_query' => [
[
'taxonomy' => $category->taxonomy,
'field' => 'slug',
'terms' => $category->slug
]
]
];
$ids = get_posts( $args );
$links = [];
// Make sure we have ID'saves
if ( $ids ) {
/**
* Because we only query post ID's, the post caches are not updated which is
* good and bad
*
* GOOD -> It saves on resources because we do not need post data or post meta data
* BAD -> We loose the vital term cache, which will result in even more db calls
*
* To solve that, we manually update the term cache with update_object_term_cache
*/
update_object_term_cache( $ids, 'product' );
$term_names = [];
foreach ( $ids as $id ) {
$terms = get_object_term_cache( $id, 'post_tag' );
foreach ( $terms as $term ) {
if ( in_array( $term->name, $term_names ) )
continue;
$term_names[] = $term->name;
$links[$term->name] = '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>';
}
}
}
if ( $links ) {
ksort( $links );
$link_string = implode( "\n\t" , $links );
} else {
$link_string = '';
}
set_transient( $transient_name, $link_string, 7 * DAY_IN_SECONDS );
}
echo $link_string;
```
This will reduce everything to ***2 queries in 0.002s***. With the transient in place, we will just to flush the transient when we publish, update, delete or undelete posts. We will use the `transition_post_status` hook here
```
add_action( 'transition_post_status', function ()
{
global $wpdb;
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_query_%')" );
$wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_query_%')" );
});
``` |
220,181 | <p>I want to pass my google map custom colors from my child theme to my parent theme. </p>
<p><strong>So in my Parent Theme's functions.php I have</strong></p>
<pre><code>add_filter( 'post_thumbnail_html', "map_thumbnail" );
function map_thumbnail($html, $color1, $color2) {
$my_post = get_post($post->ID);
$water_color=$color1;
$tree_color=$color2;
if($my_post->post_name == "contact") {
$html = '<img height="100%" width="100%" src="http://maps.googleapis.com/maps/api/staticmap?watercolor='.$water_color.'treecolor='.$tree_color.'">';
}
return $html;
}
</code></pre>
<p><strong>I just want to pass two colors from my child theme's functions.php like so,</strong></p>
<pre><code>$color1 = '#fb0000';
$color2 = '#c0e8e8';
apply_filters('post_thumbnail_html', $color1, $color2);
</code></pre>
<p>But unfortunately this is not working. Can anyone help me out here ? I have 3 child themes and all of them have the same map, just the tree color and water color are different. I want to keep the main map_thumbnail function in the parent theme and pass only the individual colors from my child themes. Please help me out if possible.</p>
| [
{
"answer_id": 220183,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 0,
"selected": false,
"text": "<p>Without having tried it myself I would suggest you write a small function for your child theme and then ... | 2016/03/09 | [
"https://wordpress.stackexchange.com/questions/220181",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81686/"
] | I want to pass my google map custom colors from my child theme to my parent theme.
**So in my Parent Theme's functions.php I have**
```
add_filter( 'post_thumbnail_html', "map_thumbnail" );
function map_thumbnail($html, $color1, $color2) {
$my_post = get_post($post->ID);
$water_color=$color1;
$tree_color=$color2;
if($my_post->post_name == "contact") {
$html = '<img height="100%" width="100%" src="http://maps.googleapis.com/maps/api/staticmap?watercolor='.$water_color.'treecolor='.$tree_color.'">';
}
return $html;
}
```
**I just want to pass two colors from my child theme's functions.php like so,**
```
$color1 = '#fb0000';
$color2 = '#c0e8e8';
apply_filters('post_thumbnail_html', $color1, $color2);
```
But unfortunately this is not working. Can anyone help me out here ? I have 3 child themes and all of them have the same map, just the tree color and water color are different. I want to keep the main map\_thumbnail function in the parent theme and pass only the individual colors from my child themes. Please help me out if possible. | Stick to filtering one value at a time to keep it simple, and add filters for the colors to be used by the child theme:
```
add_filter( 'post_thumbnail_html', 'map_thumbnail');
function map_thumbnail($html) {
$my_post = get_post($post->ID);
$defaultcolor1 = "#??????"; // parent theme default
$defaultcolor2 = "#??????"; // parent theme default
$water_color = apply_filters('water_color',$defaultcolor1);
$tree_color = apply_filters('tree_color',$defaultcolor2);
if($my_post->post_name == "contact") {
$html = '<img height="100%" width="100%" src="http://maps.googleapis.com/maps/api/staticmap?watercolor='.$water_color.'treecolor='.$tree_color.'">';
}
return $html;
}
```
So in the child theme you can use:
```
add_filter('water_color','custom_water_color');
add_filter('tree_color','custom_tree_color');
function custom_water_color() {return '#fb0000';}
function custom_tree_color() {return '#c0e8e8';}
``` |
220,208 | <p>I've applied the following code to enable the comment section in the page template.</p>
<pre><code><div class="col-md-12">
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="sec-text wow fadeInUp" data-wow-delay="300ms" data-wow-duration="1000ms">
<?php the_content(); ?>
</div>
</article>
<div class="col-md-8">
<?php
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
?>
</div>
<?php endwhile; wp_reset_query();?>
</div>
</code></pre>
<p>The comment form is showing directly by this code. User can not able to disable or re-enable the comment form in editor for specific page.</p>
| [
{
"answer_id": 220210,
"author": "Chandan Kumar Thakur",
"author_id": 88637,
"author_profile": "https://wordpress.stackexchange.com/users/88637",
"pm_score": 0,
"selected": false,
"text": "<p>yes you can do that for specific pages like with a page of page id 9</p>\n\n<pre><code> //for si... | 2016/03/09 | [
"https://wordpress.stackexchange.com/questions/220208",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81042/"
] | I've applied the following code to enable the comment section in the page template.
```
<div class="col-md-12">
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="sec-text wow fadeInUp" data-wow-delay="300ms" data-wow-duration="1000ms">
<?php the_content(); ?>
</div>
</article>
<div class="col-md-8">
<?php
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
?>
</div>
<?php endwhile; wp_reset_query();?>
</div>
```
The comment form is showing directly by this code. User can not able to disable or re-enable the comment form in editor for specific page. | I think it *could* be a problem with `get_comments_number` which returns numeric, though theoretically it should test this way too... you could try instead:
```
if ( comments_open() || have_comments() ) :
comments_template();
endif;
```
OR
```
if ( comments_open() || (get_comments_number() > 0) ) :
comments_template();
endif;
``` |
220,214 | <p>I'm a newbie for coding,
I would like to learn how to add css style conditionally in functions.php
My header controlled by <code>.header-outer</code> class. What would it be the best way to add css depending on category?
I was able to determine category slug (not standard wordpress category) and wrote some if conditions. It's working but could not understand adding css.
With <code>wp_enqueue_style</code> should I call external predefined css files or is it possible to write directly in functions.php.</p>
<pre><code>wp_enqueue_style( '***', get_template_directory_uri() . '/mycss/category1.css', array(), '1.1', 'all');
</code></pre>
<p>Here I could not understand the first *** part ? I would like to embed all style not a class.</p>
<p>Thank you,
Best Regards.</p>
| [
{
"answer_id": 220210,
"author": "Chandan Kumar Thakur",
"author_id": 88637,
"author_profile": "https://wordpress.stackexchange.com/users/88637",
"pm_score": 0,
"selected": false,
"text": "<p>yes you can do that for specific pages like with a page of page id 9</p>\n\n<pre><code> //for si... | 2016/03/09 | [
"https://wordpress.stackexchange.com/questions/220214",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32315/"
] | I'm a newbie for coding,
I would like to learn how to add css style conditionally in functions.php
My header controlled by `.header-outer` class. What would it be the best way to add css depending on category?
I was able to determine category slug (not standard wordpress category) and wrote some if conditions. It's working but could not understand adding css.
With `wp_enqueue_style` should I call external predefined css files or is it possible to write directly in functions.php.
```
wp_enqueue_style( '***', get_template_directory_uri() . '/mycss/category1.css', array(), '1.1', 'all');
```
Here I could not understand the first \*\*\* part ? I would like to embed all style not a class.
Thank you,
Best Regards. | I think it *could* be a problem with `get_comments_number` which returns numeric, though theoretically it should test this way too... you could try instead:
```
if ( comments_open() || have_comments() ) :
comments_template();
endif;
```
OR
```
if ( comments_open() || (get_comments_number() > 0) ) :
comments_template();
endif;
``` |
220,225 | <p>I'm using Postman to test my project and the wp-api. More specifically POST requests where a user must be authenticated to do something. Here's what I'm working with to create a user:</p>
<pre><code>{{url}}/projectname/wp-json/wp/v2/users/?username=anewname&email=ben@scientifik.com&password=passwordhere
</code></pre>
<p>However when testing something <a href="http://v2.wp-api.org/guide/authentication/" rel="nofollow">requiring authentication</a>, such as creating a user, I get a 401'ed:</p>
<pre><code>{
"code": "rest_cannot_create_user",
"message": "Sorry, you are not allowed to create resource.",
"data": {
"status": 401
}
}
</code></pre>
<p><strong>Authenticating via Nonce:</strong>
If you see the link above, the documentation explains setting the header and sending along the nonce. I could set the header to <code>X-WP-Nonce</code> but then how would I get the nonce to send along in Postman?</p>
<p><strong>Authenticating via cookies:</strong>
I've installed Postman's <a href="https://chrome.google.com/webstore/detail/postman-interceptor/aicmkgpgakddgnaphhhpliifpcfhicfo" rel="nofollow">interceptor</a> to grab cookies and am seeing 5 of them but still get 401'ed with the method above.</p>
<p>Any ideas or guidance would be really useful to the community.</p>
| [
{
"answer_id": 226822,
"author": "MTT",
"author_id": 1057,
"author_profile": "https://wordpress.stackexchange.com/users/1057",
"pm_score": -1,
"selected": false,
"text": "<p>Postman doesn't need a nonce to create content with v2 beta 12... just use the WP-API Basic Auth plugin. The one h... | 2016/03/09 | [
"https://wordpress.stackexchange.com/questions/220225",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18726/"
] | I'm using Postman to test my project and the wp-api. More specifically POST requests where a user must be authenticated to do something. Here's what I'm working with to create a user:
```
{{url}}/projectname/wp-json/wp/v2/users/?username=anewname&email=ben@scientifik.com&password=passwordhere
```
However when testing something [requiring authentication](http://v2.wp-api.org/guide/authentication/), such as creating a user, I get a 401'ed:
```
{
"code": "rest_cannot_create_user",
"message": "Sorry, you are not allowed to create resource.",
"data": {
"status": 401
}
}
```
**Authenticating via Nonce:**
If you see the link above, the documentation explains setting the header and sending along the nonce. I could set the header to `X-WP-Nonce` but then how would I get the nonce to send along in Postman?
**Authenticating via cookies:**
I've installed Postman's [interceptor](https://chrome.google.com/webstore/detail/postman-interceptor/aicmkgpgakddgnaphhhpliifpcfhicfo) to grab cookies and am seeing 5 of them but still get 401'ed with the method above.
Any ideas or guidance would be really useful to the community. | Postman shares cookies with Chrome. If you are logged into your site you may see unexpected results.
REF : <https://wordpress.org/support/topic/wp-api-cant-create-a-post/> |
220,245 | <p>Whats the most simple way to change my wp-menu generated output from <code><li><a href="">nav link</a></li></code> to <code><a href=""><li><li/></a></code>? Do I create an array in my <code>functions.php</code>?</p>
<p>This is what I have in my <code>functions.php</code> </p>
<pre><code>function register_my_menus() {
register_nav_menus(
array(
'primary' => __( 'Main Menu' ),
'mobile-menu' => __( 'Mobile Menu' ),
)
);
}
add_action( 'init', 'register_my_menus' );
</code></pre>
| [
{
"answer_id": 220253,
"author": "Madan Karki",
"author_id": 83958,
"author_profile": "https://wordpress.stackexchange.com/users/83958",
"pm_score": -1,
"selected": false,
"text": "<p>use <a href=\"https://gist.github.com/toscho/1053467\" rel=\"nofollow\">\"T5_Nav_Menu_Walker_Simple\"</a... | 2016/03/10 | [
"https://wordpress.stackexchange.com/questions/220245",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60779/"
] | Whats the most simple way to change my wp-menu generated output from `<li><a href="">nav link</a></li>` to `<a href=""><li><li/></a>`? Do I create an array in my `functions.php`?
This is what I have in my `functions.php`
```
function register_my_menus() {
register_nav_menus(
array(
'primary' => __( 'Main Menu' ),
'mobile-menu' => __( 'Mobile Menu' ),
)
);
}
add_action( 'init', 'register_my_menus' );
``` | I don't recommend having anything in-between a ul and li.
If you make the anchor tag display:block that fills the list, the whole list tag will be clickable. So dont put any height, width, or padding on the list and manage it all instead with the anchor.
```
a {
display: block;
width: 100%;
}
``` |
220,270 | <p>What I'm trying to do is show the current logged in user's comment at the top of the list in the comments section in Wordpress on any given post. I don't care if it is just duplicated at the top and still shows in the regular order below as well, I just need it to show at the top of the list so the user can find it easily. I figured out how to single out their comment so I can style it with CSS, but changing where it appears in the list is eluding me. Any help would be incredibly appreciated, thanks in advance guys.</p>
<pre><code>add_filter( 'comment_class', 'comment_class_logged_in_user' );
function comment_class_logged_in_user( $classes ) {
global $comment;
if ( $comment->user_id > 0 && is_user_logged_in() ) {
global $current_user; get_currentuserinfo();
$logged_in_user = $current_user->ID;
if( $comment->user_id == $logged_in_user ) $classes[] = 'comment-author-logged-in';
}
return $classes;
}
</code></pre>
<p>This is what I tried for my wp_comment_query, but it doesn't work.</p>
<pre><code><?php
global $current_user; get_currentuserinfo();
$logged_in_user = $current_user->ID;
$args = array(
'user_id' => '$logged_in_user',
);
// The Query
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
// Comment Loop
if ( $comments ) {
foreach ( $comments as $comment ) {
echo '<p>' . $comment->comment_content . '</p>';
}
} else {
echo 'No comments found.';
}
?>
</code></pre>
| [
{
"answer_id": 220253,
"author": "Madan Karki",
"author_id": 83958,
"author_profile": "https://wordpress.stackexchange.com/users/83958",
"pm_score": -1,
"selected": false,
"text": "<p>use <a href=\"https://gist.github.com/toscho/1053467\" rel=\"nofollow\">\"T5_Nav_Menu_Walker_Simple\"</a... | 2016/03/10 | [
"https://wordpress.stackexchange.com/questions/220270",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90312/"
] | What I'm trying to do is show the current logged in user's comment at the top of the list in the comments section in Wordpress on any given post. I don't care if it is just duplicated at the top and still shows in the regular order below as well, I just need it to show at the top of the list so the user can find it easily. I figured out how to single out their comment so I can style it with CSS, but changing where it appears in the list is eluding me. Any help would be incredibly appreciated, thanks in advance guys.
```
add_filter( 'comment_class', 'comment_class_logged_in_user' );
function comment_class_logged_in_user( $classes ) {
global $comment;
if ( $comment->user_id > 0 && is_user_logged_in() ) {
global $current_user; get_currentuserinfo();
$logged_in_user = $current_user->ID;
if( $comment->user_id == $logged_in_user ) $classes[] = 'comment-author-logged-in';
}
return $classes;
}
```
This is what I tried for my wp\_comment\_query, but it doesn't work.
```
<?php
global $current_user; get_currentuserinfo();
$logged_in_user = $current_user->ID;
$args = array(
'user_id' => '$logged_in_user',
);
// The Query
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
// Comment Loop
if ( $comments ) {
foreach ( $comments as $comment ) {
echo '<p>' . $comment->comment_content . '</p>';
}
} else {
echo 'No comments found.';
}
?>
``` | I don't recommend having anything in-between a ul and li.
If you make the anchor tag display:block that fills the list, the whole list tag will be clickable. So dont put any height, width, or padding on the list and manage it all instead with the anchor.
```
a {
display: block;
width: 100%;
}
``` |
220,275 | <p>I'm using PHPUnit to Unit Test my WP plugin on top of the WP testing suite. Everything works fine except that when I try to create a table via the setUp method, the table doesn't get created. </p>
<p>Here's my code:</p>
<pre><code>class Test_Db extends PAO_UnitTestCase {
function setUp() {
parent::setUp();
global $wpdb;
$sql = "CREATE TABLE {$wpdb->prefix}mytest (
id bigint(20) NOT NULL AUTO_INCREMENT,
column_1 varchar(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$this->el(dbDelta($sql));
}
function tearDown() {
parent::tearDown();
}
function test_db_stuff(){
global $wpdb;
$sql = "SHOW TABLES LIKE '%'";
$results = $wpdb->get_results($sql);
foreach($results as $index => $value) {
foreach($value as $tableName) {
$this->el($tableName);
}
}
}
}
</code></pre>
<p>The class PAO_UnitTestCase is simply an extension of the WP_UnitTestCase class which contains one method - the el method - which simply logs whatever into a file of my choosing.</p>
<p>As you can see, I used the el method to</p>
<ol>
<li>Write the response of dbDelta into the log</li>
<li>Write the names of all existing tables into the log</li>
</ol>
<p>According to the log, dbDelta was able to create the table but it's not being listed down as part of the existing tables.</p>
<p>So my questions are:</p>
<ol>
<li>Is it possible to create tables during unit testing via PHPUnit?</li>
<li>If so, what am I doing wrong?</li>
</ol>
<p>Hope someone can help me.</p>
<p>Thanks!</p>
<p><strong>Update:</strong> As seen in the discussion and accepted answer below, the tables do get created but as TEMPORARY tables. You won't be able to see the tables via SHOW TABLES though but you check its existence by inserting a row and then trying to retrieve the row.</p>
| [
{
"answer_id": 220308,
"author": "J.D.",
"author_id": 27757,
"author_profile": "https://wordpress.stackexchange.com/users/27757",
"pm_score": 5,
"selected": true,
"text": "<p>You've just discovered an important feature of the core test suite: it forces any tables created during the test ... | 2016/03/10 | [
"https://wordpress.stackexchange.com/questions/220275",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38261/"
] | I'm using PHPUnit to Unit Test my WP plugin on top of the WP testing suite. Everything works fine except that when I try to create a table via the setUp method, the table doesn't get created.
Here's my code:
```
class Test_Db extends PAO_UnitTestCase {
function setUp() {
parent::setUp();
global $wpdb;
$sql = "CREATE TABLE {$wpdb->prefix}mytest (
id bigint(20) NOT NULL AUTO_INCREMENT,
column_1 varchar(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$this->el(dbDelta($sql));
}
function tearDown() {
parent::tearDown();
}
function test_db_stuff(){
global $wpdb;
$sql = "SHOW TABLES LIKE '%'";
$results = $wpdb->get_results($sql);
foreach($results as $index => $value) {
foreach($value as $tableName) {
$this->el($tableName);
}
}
}
}
```
The class PAO\_UnitTestCase is simply an extension of the WP\_UnitTestCase class which contains one method - the el method - which simply logs whatever into a file of my choosing.
As you can see, I used the el method to
1. Write the response of dbDelta into the log
2. Write the names of all existing tables into the log
According to the log, dbDelta was able to create the table but it's not being listed down as part of the existing tables.
So my questions are:
1. Is it possible to create tables during unit testing via PHPUnit?
2. If so, what am I doing wrong?
Hope someone can help me.
Thanks!
**Update:** As seen in the discussion and accepted answer below, the tables do get created but as TEMPORARY tables. You won't be able to see the tables via SHOW TABLES though but you check its existence by inserting a row and then trying to retrieve the row. | You've just discovered an important feature of the core test suite: it forces any tables created during the test to be temporary tables.
If you look in the `WP_UnitTestCase::setUp()` method you'll see that [it calls a method called `start_transaction()`](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/includes/testcase.php#L120). That [`start_transaction()` method](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/includes/testcase.php#L260) starts a [MySQL database transaction](https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-transactions.html):
```
function start_transaction() {
global $wpdb;
$wpdb->query( 'SET autocommit = 0;' );
$wpdb->query( 'START TRANSACTION;' );
add_filter( 'query', array( $this, '_create_temporary_tables' ) );
add_filter( 'query', array( $this, '_drop_temporary_tables' ) );
}
```
It does this so that any changes that your test makes in the database can just be [rolled back afterward in the `tearDown()` method](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/includes/testcase.php#L141). This means that each test starts with a clean WordPress database, untainted by the prior tests.
However, you'll note that `start_transaction()` also hooks two methods to the [`'query'` filter](https://developer.wordpress.org/reference/hooks/query/): `_create_temporary_tables` and `_drop_temporary_tables`. If you look at [the source of these methods](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/includes/testcase.php#L278), you'll see that they cause any `CREATE` or `DROP` table queries to be for temporary tables instead:
```
function _create_temporary_tables( $query ) {
if ( 'CREATE TABLE' === substr( trim( $query ), 0, 12 ) )
return substr_replace( trim( $query ), 'CREATE TEMPORARY TABLE', 0, 12 );
return $query;
}
function _drop_temporary_tables( $query ) {
if ( 'DROP TABLE' === substr( trim( $query ), 0, 10 ) )
return substr_replace( trim( $query ), 'DROP TEMPORARY TABLE', 0, 10 );
return $query;
}
```
The `'query'` filter is applied to all database queries passed through `$wpdb->query()`, [which `dbDelta()` uses](https://developer.wordpress.org/reference/functions/dbdelta/#source-code). So that means when your tables are created, they are created as *temporary* tables.
So in order to list those tables, ~~I think you'd have to show temporary tables instead: `$sql = "SHOW TEMPORARY TABLES LIKE '%'";`~~
**Update:** MySQL doesn't allow you to list the temporary tables like you can with the regular tables. You will have to use another method of checking if the table exists, like attempting to insert a row.
But why does the unit test case require temporary tables to be created in the first place? Remember that we are using MySQL transactions so that the database stays clean. We don't want to ever commit the transactions though, we want to always roll them back at the end of the test. But there are [some MySQL statements that will cause an *implicit* commit](https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html). Among these are, you guessed it, `CREATE TABLE` and `DROP TABLE`. However, per the MySQL docs:
>
> `CREATE TABLE` and `DROP TABLE` statements do not commit a transaction if the `TEMPORARY` keyword is used.
>
>
>
So to avoid an implicit commit, the test case forces any tables created or dropped to be temporary tables.
This is not a well documented feature, but once you understand what is going on it should be pretty easy to work with. |
220,278 | <p>I am using CMB2 and following code to select date & time:</p>
<pre><code>$cmb->add_field( array(
'name' => __( 'Test Date/Time Picker Combo (UNIX timestamp)', 'cmb2' ),
'desc' => __( 'field description (optional)', 'cmb2' ),
'id' => $prefix . 'datetime_timestamp',
'type' => 'text_datetime_timestamp',
) );
</code></pre>
<p>That code give me this in admin panel:</p>
<p><a href="https://i.stack.imgur.com/tSJbN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tSJbN.png" alt="date and time admin"></a></p>
<p>To retrieve this meta data I am using following code:</p>
<pre><code>$text = get_post_meta( get_the_ID(), '_cmb2_event_date_prefix_datetime_timestamp', true )
echo esc_html( $text );
</code></pre>
<p>But this gives me a number as follow not the date and time I selected in admin panel.</p>
<pre><code>1457368800
</code></pre>
<p>Why is this ? How can I get the date and time I selected in that meta box.</p>
| [
{
"answer_id": 220280,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 3,
"selected": false,
"text": "<p>You're almost there. The number you see is a called <a href=\"https://en.m.wikipedia.org/wiki/Unix_time\" re... | 2016/03/10 | [
"https://wordpress.stackexchange.com/questions/220278",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69828/"
] | I am using CMB2 and following code to select date & time:
```
$cmb->add_field( array(
'name' => __( 'Test Date/Time Picker Combo (UNIX timestamp)', 'cmb2' ),
'desc' => __( 'field description (optional)', 'cmb2' ),
'id' => $prefix . 'datetime_timestamp',
'type' => 'text_datetime_timestamp',
) );
```
That code give me this in admin panel:
[](https://i.stack.imgur.com/tSJbN.png)
To retrieve this meta data I am using following code:
```
$text = get_post_meta( get_the_ID(), '_cmb2_event_date_prefix_datetime_timestamp', true )
echo esc_html( $text );
```
But this gives me a number as follow not the date and time I selected in admin panel.
```
1457368800
```
Why is this ? How can I get the date and time I selected in that meta box. | The date/time related field types for CMB2 store all their values as Unix timestamps in the database with the exception of `text_datetime_timestamp_timezone` which stores it's value as a serialized DateTime object.
* **text\_date\_timestamp** Date Picker (UNIX timestamp)
* **text\_datetime\_timestamp** Text Date/Time Picker Combo (UNIX timestamp)
* **text\_datetime\_timestamp\_timezone** Text Date/Time Picker/Time zone Combo (serialized DateTime object)
See: <https://github.com/WebDevStudios/CMB2/wiki/Field-Types>
What you see in the metabox is a conversion from the Unix timestamp to a human readable format which I believe you can adjust to your liking using the `date_format` key when calling `$cmb->add_field()`.
In your case, all you need to do is pass your timestamp through PHP's `date()` function to format the result as you desire.
Example:
```
$text = get_post_meta( get_the_ID(), '_cmb2_event_date_prefix_datetime_timestamp', true )
echo date('Y-m-d H:i:s A', $text ); // results in 2016-03-07 08:40:00 AM
```
See the documentation on PHP's `date()` function for formatting instructions:
* <http://php.net/manual/en/function.date.php> |
220,293 | <p>When I call the_content(), I want to show only text and don't want to show images.
Notable that, I don't want to remove text style. The text style should be display as well.
How can I do this?</p>
| [
{
"answer_id": 220298,
"author": "Kishan Chauhan",
"author_id": 63564,
"author_profile": "https://wordpress.stackexchange.com/users/63564",
"pm_score": 3,
"selected": true,
"text": "<p>This answer already here <a href=\"https://wordpress.stackexchange.com/questions/162162/how-to-remove-i... | 2016/03/10 | [
"https://wordpress.stackexchange.com/questions/220293",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81042/"
] | When I call the\_content(), I want to show only text and don't want to show images.
Notable that, I don't want to remove text style. The text style should be display as well.
How can I do this? | This answer already here [How to remove images from showing in a post with the\_content()?](https://wordpress.stackexchange.com/questions/162162/how-to-remove-images-from-showing-in-a-post-with-the-content#162165)
```
<?php
$content = get_the_content();
$content = preg_replace("/<img[^>]+\>/i", " ", $content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
?>
``` |
220,326 | <p>I'm hoping someone will be able to help me with this issue.
I noticed today that when I search certain serch terms in my Wordpress site's search box the link is messed up (shown in the image below outlined by the yellow boxes) and when clicked, the link takes the user to a blank page.</p>
<p><a href="https://i.stack.imgur.com/1J3I8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1J3I8.png" alt="Issue example"></a></p>
<p>When I searched other terms, either there was the issue on all of the search results for that term or there was no issue at all.</p>
<p>Any ideas what may be causing this and how to fix it?
Thanks in advance!</p>
| [
{
"answer_id": 220298,
"author": "Kishan Chauhan",
"author_id": 63564,
"author_profile": "https://wordpress.stackexchange.com/users/63564",
"pm_score": 3,
"selected": true,
"text": "<p>This answer already here <a href=\"https://wordpress.stackexchange.com/questions/162162/how-to-remove-i... | 2016/03/10 | [
"https://wordpress.stackexchange.com/questions/220326",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90354/"
] | I'm hoping someone will be able to help me with this issue.
I noticed today that when I search certain serch terms in my Wordpress site's search box the link is messed up (shown in the image below outlined by the yellow boxes) and when clicked, the link takes the user to a blank page.
[](https://i.stack.imgur.com/1J3I8.png)
When I searched other terms, either there was the issue on all of the search results for that term or there was no issue at all.
Any ideas what may be causing this and how to fix it?
Thanks in advance! | This answer already here [How to remove images from showing in a post with the\_content()?](https://wordpress.stackexchange.com/questions/162162/how-to-remove-images-from-showing-in-a-post-with-the-content#162165)
```
<?php
$content = get_the_content();
$content = preg_replace("/<img[^>]+\>/i", " ", $content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
?>
``` |
220,330 | <p>This is my code. Where I'm wrong? </p>
<pre><code><?php
$connection = mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD);
mysql_select_db($DB_NAME);
$img = mysql_query("SELECT * FROM wp_bwg_image");
while($res = mysql_fetch_array($img)){
echo $res;
}
?>
</code></pre>
<p>From this table I want to take any pictures.</p>
<p><a href="https://i.stack.imgur.com/2DaDY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2DaDY.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 220385,
"author": "brianlmerritt",
"author_id": 78419,
"author_profile": "https://wordpress.stackexchange.com/users/78419",
"pm_score": 1,
"selected": false,
"text": "<p>Use the global $wpdb for example <code>$myrows = $wpdb->get_results( “insert sql here\");</code></p>... | 2016/03/10 | [
"https://wordpress.stackexchange.com/questions/220330",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90333/"
] | This is my code. Where I'm wrong?
```
<?php
$connection = mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD);
mysql_select_db($DB_NAME);
$img = mysql_query("SELECT * FROM wp_bwg_image");
while($res = mysql_fetch_array($img)){
echo $res;
}
?>
```
From this table I want to take any pictures.
[](https://i.stack.imgur.com/2DaDY.jpg) | Use the global $wpdb for example `$myrows = $wpdb->get_results( “insert sql here");` |
220,339 | <p>I have a little problem, I created a wordpress theme with documentation created with the site helpscout, to reduce the number of support ticket, I would like to do the same thing EDD: <a href="https://easydigitaldownloads.com/support/" rel="nofollow">https://easydigitaldownloads.com/support/</a>, if you click on "Submit Support Request", an input appears and if you enter a word, for example, "google", links to helpscout documentation are available, then you can create a request.
I copied the code of this site, I created a multi-part form with gravity form, everything works well, except looking towards the doc, here is the code I entered my functions.php file:</p>
<pre><code>function support_form() {
if ( ! wp_script_is( 'gform_gravityforms' ) ) {
return;
} ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var wrap = $('.gform_body .gfield.helpscout-docs');
var paging = $('.gform_body .gform_page_footer');
var hidden = $('.gform_body .gfield.helpscout-docs').next().find('input');
var field = wrap.find('input[type="text"]');
var searching = false, allowed = false;
paging.hide();
wrap.append( '<div class="docs-search-wrap"></div>' );
field.attr( 'autocomplete', 'off' );
paging.find('input[type="submit"]').on('click', function(e) {
if( ! allowed ) {
return false;
}
});
field.keyup(function(e) {
query = $(this).val();
if( query.length < 4 ) {
return;
}
var html = '<ul class="docs-search-results">';
if( ! searching ) {
var count = 0;
// Getting Started
$.ajax({
url: 'https://docsapi.helpscout.net/v1/search/articles?collectionId=56d89d519033600eafd436e4&query=' + query,
headers: {
'Authorization': 'Basic <?php echo base64_encode( 'username:password' ); ?>'
},
xhrFields: {
withCredentials: false
},
beforeSend: function() {
searching = true;
},
success: function(results) {
count += results.articles.items.length;
$.each( results.articles.items, function( key, article ) {
html = html + '<li class="article"><a href="' + article.url + '" title="' + article.preview + '" target="_blank">' + article.name + '</a><li>';
});
}
}).done(function() {
// FAQs
$.ajax({
url: 'https://docsapi.helpscout.net/v1/search/articles?collectionId=56d8b3c9c6979159b4453cf6&query=' + query,
headers: {
'Authorization': 'Basic <?php echo base64_encode( 'username:password' ); ?>'
},
xhrFields: {
withCredentials: false
},
beforeSend: function() {
searching = true;
},
success: function(results) {
count += results.articles.items.length;
$.each( results.articles.items, function( key, article ) {
html = html + '<li class="article"><a href="' + article.url + '" title="' + article.preview + '" target="_blank">' + article.name + '</a><li>';
});
}
}).done(function() {
// Extensions
$.ajax({
url: 'https://docsapi.helpscout.net/v1/search/articles?collectionId=56d8b96fc6979159b4453d22&query=' + query,
headers: {
'Authorization': 'Basic <?php echo base64_encode( 'username:password' ); ?>'
},
xhrFields: {
withCredentials: false
},
beforeSend: function() {
searching = true;
},
success: function(results) {
count += results.articles.items.length;
$.each( results.articles.items, function( key, article ) {
html = html + '<li class="article"><a href="' + article.url + '" title="' + article.preview + '" target="_blank">' + article.name + '</a><li>';
});
}
}).done(function() {
html = html + '</ul>'
html = '<span class="results-found">' + count + ' results found . . . </span>' + html;
wrap.find('.docs-search-wrap').html( html );
paging.show();
searching = false;
});
});
});
}
});
});
</script>
<?php
}
add_action( 'send_headers', 'add_header_acao' );
function add_header_acao() {
header( 'Access-Control-Allow-Origin: *' );
}
</code></pre>
<p>But when I enter a word in the input I receive an error message in the console:
"No 'Access-Control-Allow-Origin' header is present on the requested resource."</p>
<p>I have not inserted the " 'Access-Control-Allow-Origin" correctly?
Is it because of the "username:password", I set the username and password from my dashboard help scout, maybe it is not that I need to insert.</p>
<p>Can you help me?</p>
<p>Thank you a lot :)</p>
| [
{
"answer_id": 220366,
"author": "kingkool68",
"author_id": 2744,
"author_profile": "https://wordpress.stackexchange.com/users/2744",
"pm_score": 0,
"selected": false,
"text": "<p>You're trying to make an AJAX request to another domain which is prohibited by JavaScript for security/priva... | 2016/03/10 | [
"https://wordpress.stackexchange.com/questions/220339",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45874/"
] | I have a little problem, I created a wordpress theme with documentation created with the site helpscout, to reduce the number of support ticket, I would like to do the same thing EDD: <https://easydigitaldownloads.com/support/>, if you click on "Submit Support Request", an input appears and if you enter a word, for example, "google", links to helpscout documentation are available, then you can create a request.
I copied the code of this site, I created a multi-part form with gravity form, everything works well, except looking towards the doc, here is the code I entered my functions.php file:
```
function support_form() {
if ( ! wp_script_is( 'gform_gravityforms' ) ) {
return;
} ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var wrap = $('.gform_body .gfield.helpscout-docs');
var paging = $('.gform_body .gform_page_footer');
var hidden = $('.gform_body .gfield.helpscout-docs').next().find('input');
var field = wrap.find('input[type="text"]');
var searching = false, allowed = false;
paging.hide();
wrap.append( '<div class="docs-search-wrap"></div>' );
field.attr( 'autocomplete', 'off' );
paging.find('input[type="submit"]').on('click', function(e) {
if( ! allowed ) {
return false;
}
});
field.keyup(function(e) {
query = $(this).val();
if( query.length < 4 ) {
return;
}
var html = '<ul class="docs-search-results">';
if( ! searching ) {
var count = 0;
// Getting Started
$.ajax({
url: 'https://docsapi.helpscout.net/v1/search/articles?collectionId=56d89d519033600eafd436e4&query=' + query,
headers: {
'Authorization': 'Basic <?php echo base64_encode( 'username:password' ); ?>'
},
xhrFields: {
withCredentials: false
},
beforeSend: function() {
searching = true;
},
success: function(results) {
count += results.articles.items.length;
$.each( results.articles.items, function( key, article ) {
html = html + '<li class="article"><a href="' + article.url + '" title="' + article.preview + '" target="_blank">' + article.name + '</a><li>';
});
}
}).done(function() {
// FAQs
$.ajax({
url: 'https://docsapi.helpscout.net/v1/search/articles?collectionId=56d8b3c9c6979159b4453cf6&query=' + query,
headers: {
'Authorization': 'Basic <?php echo base64_encode( 'username:password' ); ?>'
},
xhrFields: {
withCredentials: false
},
beforeSend: function() {
searching = true;
},
success: function(results) {
count += results.articles.items.length;
$.each( results.articles.items, function( key, article ) {
html = html + '<li class="article"><a href="' + article.url + '" title="' + article.preview + '" target="_blank">' + article.name + '</a><li>';
});
}
}).done(function() {
// Extensions
$.ajax({
url: 'https://docsapi.helpscout.net/v1/search/articles?collectionId=56d8b96fc6979159b4453d22&query=' + query,
headers: {
'Authorization': 'Basic <?php echo base64_encode( 'username:password' ); ?>'
},
xhrFields: {
withCredentials: false
},
beforeSend: function() {
searching = true;
},
success: function(results) {
count += results.articles.items.length;
$.each( results.articles.items, function( key, article ) {
html = html + '<li class="article"><a href="' + article.url + '" title="' + article.preview + '" target="_blank">' + article.name + '</a><li>';
});
}
}).done(function() {
html = html + '</ul>'
html = '<span class="results-found">' + count + ' results found . . . </span>' + html;
wrap.find('.docs-search-wrap').html( html );
paging.show();
searching = false;
});
});
});
}
});
});
</script>
<?php
}
add_action( 'send_headers', 'add_header_acao' );
function add_header_acao() {
header( 'Access-Control-Allow-Origin: *' );
}
```
But when I enter a word in the input I receive an error message in the console:
"No 'Access-Control-Allow-Origin' header is present on the requested resource."
I have not inserted the " 'Access-Control-Allow-Origin" correctly?
Is it because of the "username:password", I set the username and password from my dashboard help scout, maybe it is not that I need to insert.
Can you help me?
Thank you a lot :) | I found !!!
It had nothing to do with "Access-Control-Allow-Origin" was because of the API key, I entered the username and password from my dashboard help scout, I had to enter the api key for my documentation :)
Thanks a lot for your help :) |
220,347 | <p>I have created a metabox to upload images. Whenever I click on the "Select Image" button the Image Uploader Box successfully pops up but when I select an image and click the "Insert" button the image URL doesn't get inserted in the text field. Please tell me what to do so that whenever I insert an image the image URL gets inserted into the correct field.</p>
<pre><code>var image_field;
jQuery( function( $ ) {
$( document ).on( 'click', 'input.select-img', function( evt ) {
image_field = $( this ).siblings( '.img' );
check_flag = 1;
tb_show( '', 'media-upload.php?type=image&amp;TB_iframe=true' );
window.send_to_editor = function( html ) {
imgurl = $( 'img', html ).attr( 'src' );
image_field.val( imgurl );
tb_remove();
}
return false;
} );
} );
</code></pre>
| [
{
"answer_id": 220366,
"author": "kingkool68",
"author_id": 2744,
"author_profile": "https://wordpress.stackexchange.com/users/2744",
"pm_score": 0,
"selected": false,
"text": "<p>You're trying to make an AJAX request to another domain which is prohibited by JavaScript for security/priva... | 2016/03/10 | [
"https://wordpress.stackexchange.com/questions/220347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90367/"
] | I have created a metabox to upload images. Whenever I click on the "Select Image" button the Image Uploader Box successfully pops up but when I select an image and click the "Insert" button the image URL doesn't get inserted in the text field. Please tell me what to do so that whenever I insert an image the image URL gets inserted into the correct field.
```
var image_field;
jQuery( function( $ ) {
$( document ).on( 'click', 'input.select-img', function( evt ) {
image_field = $( this ).siblings( '.img' );
check_flag = 1;
tb_show( '', 'media-upload.php?type=image&TB_iframe=true' );
window.send_to_editor = function( html ) {
imgurl = $( 'img', html ).attr( 'src' );
image_field.val( imgurl );
tb_remove();
}
return false;
} );
} );
``` | I found !!!
It had nothing to do with "Access-Control-Allow-Origin" was because of the API key, I entered the username and password from my dashboard help scout, I had to enter the api key for my documentation :)
Thanks a lot for your help :) |
220,349 | <p>I have a plugin that is syncing data from a third party service into a custom post type. The idea is that the post type acts as a slave to the third party service, so any changes there overwrite any on the wordpress site. However there will be a few extra custom fields that will be made to add information from the wordpress side to the data from the third party service.</p>
<p>What I am looking for is a way to more or less disable the fields that will be overwritten (title, body, 50-60 custom fields) Leaving only the ones that will not be overwritten to be editable.</p>
<p>I know how to hide title/body (although unsure if it completely removes them), however I feel it would be beneficial to keep them visible, just grayed out / disabled. </p>
<p>This is how I am disabling title/body:</p>
<pre><code>function remove_edit_fields(){
remove_post_type_support( 'property_listings', 'title' );
remove_post_type_support( 'property_listings', 'editor' );
}
add_action( 'admin_init', 'remove_edit_fields' );
</code></pre>
<p>Is there any way to do this while keeping them visible and do the same for custom fields?</p>
| [
{
"answer_id": 220371,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>To begin with, adding an <code>_</code> to the start of the custom field key will make it a hidden field not a... | 2016/03/10 | [
"https://wordpress.stackexchange.com/questions/220349",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63445/"
] | I have a plugin that is syncing data from a third party service into a custom post type. The idea is that the post type acts as a slave to the third party service, so any changes there overwrite any on the wordpress site. However there will be a few extra custom fields that will be made to add information from the wordpress side to the data from the third party service.
What I am looking for is a way to more or less disable the fields that will be overwritten (title, body, 50-60 custom fields) Leaving only the ones that will not be overwritten to be editable.
I know how to hide title/body (although unsure if it completely removes them), however I feel it would be beneficial to keep them visible, just grayed out / disabled.
This is how I am disabling title/body:
```
function remove_edit_fields(){
remove_post_type_support( 'property_listings', 'title' );
remove_post_type_support( 'property_listings', 'editor' );
}
add_action( 'admin_init', 'remove_edit_fields' );
```
Is there any way to do this while keeping them visible and do the same for custom fields? | In order to do this I had to hide the fields in the default ACF output. There is no way to do this in the core, underscores can work to disable the output everywhere else but the edit area is an exception.
I had used the following code to create a hidden field type, it outputs no input and hides its own label. It is based off of <https://github.com/gerbenvandijk/acf-hidden-field>
```
<?php
class acf_field_hidden_field extends acf_field
{
// vars
var $settings, // will hold info such as dir / path
$defaults; // will hold default field options
/*
* __construct
*
* Set name / label needed for actions / filters
*
* @since 3.6
* @date 23/01/13
*/
function __construct()
{
// vars
$this->name = 'hidden_field';
$this->label = __('Hidden field');
$this->category = __("Basic",'acf'); // Basic, Content, Choice, etc
$this->defaults = array(
// add default here to merge into your field.
// This makes life easy when creating the field options as you don't need to use any if( isset('') ) logic. eg:
//'preview_size' => 'thumbnail'
);
// do not delete!
parent::__construct();
// settings
$this->settings = array(
'path' => apply_filters('acf/helpers/get_path', __FILE__),
'dir' => apply_filters('acf/helpers/get_dir', __FILE__),
'version' => '1.0.0'
);
}
/*
* create_field()
*
* Create the HTML interface for your field
*
* @param $field - an array holding all the field's data
*
* @type action
* @since 3.6
* @date 23/01/13
*/
function render_field( $field )
{
// defaults?
/*
$field = array_merge($this->defaults, $field);
*/
// perhaps use $field['preview_size'] to alter the markup?
// create Field HTML
?>
<style>div[data-key="<?php echo $field['key'];?>"]{ display: none;}</style>
<?php
}
}
// create field
new acf_field_hidden_field();
?>
```
I also used my own custom meta box to bring the data in, my way. I had "labeled" the fields by naming them in such a way as to know they were technically hidden fields (like `hide_title` and `hide_desc`). By using a custom one it does not affect the regular front end display. |
220,376 | <p>In the home page, I have a custom loop for displaying different post type content. I have this loop on my index.php</p>
<pre><code>$loop = new WP_Query(
array(
'post_type' => array('photo', 'video', 'web'),
'paged' => get_query_var('paged') ? get_query_var('paged') : 1,
'posts_per_page' => -1
)
);
</code></pre>
<p>Now it displays correctly but I want to include the title from what post type it belongs so that I can link to right page.</p>
<p>for example if I have these items in my home page (as a result of the above loop):</p>
<ol>
<li>Item 1 - <a href="http://page-video" rel="nofollow">video</a></li>
<li>Item 2 - <a href="http://page-photo" rel="nofollow">photo</a></li>
<li>Item 3 - <a href="http://page-web" rel="nofollow">web</a></li>
</ol>
<p>Where the links are the page I created that displays those custom post type and the title is the title of the post type (ie video. photo, web).</p>
<p>I have tried this to put inside my loop but it doesn't work.</p>
<pre><code><?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php
if ( is_singular( 'photo' ) ) :
echo "<a href='/photo'>photo</a>";
elseif ( is_singular( 'video' ) ) :
echo "<a href='/video'>video</a>";
elseif ( is_singular( 'web' ) ) :
echo "<a href='/web'>web</a>";
endif;
?>
<?php get_template_part( 'content', 'grid'); ?>
<?php endwhile; ?>
</code></pre>
| [
{
"answer_id": 220382,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>You are doing it wrong on many levels here:</p>\n\n<ul>\n<li><p>You should not be using a custom query i... | 2016/03/11 | [
"https://wordpress.stackexchange.com/questions/220376",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55160/"
] | In the home page, I have a custom loop for displaying different post type content. I have this loop on my index.php
```
$loop = new WP_Query(
array(
'post_type' => array('photo', 'video', 'web'),
'paged' => get_query_var('paged') ? get_query_var('paged') : 1,
'posts_per_page' => -1
)
);
```
Now it displays correctly but I want to include the title from what post type it belongs so that I can link to right page.
for example if I have these items in my home page (as a result of the above loop):
1. Item 1 - [video](http://page-video)
2. Item 2 - [photo](http://page-photo)
3. Item 3 - [web](http://page-web)
Where the links are the page I created that displays those custom post type and the title is the title of the post type (ie video. photo, web).
I have tried this to put inside my loop but it doesn't work.
```
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php
if ( is_singular( 'photo' ) ) :
echo "<a href='/photo'>photo</a>";
elseif ( is_singular( 'video' ) ) :
echo "<a href='/video'>video</a>";
elseif ( is_singular( 'web' ) ) :
echo "<a href='/web'>web</a>";
endif;
?>
<?php get_template_part( 'content', 'grid'); ?>
<?php endwhile; ?>
``` | You are doing it wrong on many levels here:
* You should not be using a custom query in place of the main query. Rather use `pre_get_posts` to alter the main query accordingly. Go back to the main loop and add the following in your functions file or in a custom plugin
```
add_action( 'pre_get_posts', function ( $q )
{
if ( $q->is_home()
&& $q->is_main_query()
) {
$q->set( 'post_type', ['photo', 'video', 'web'] );
$q->set( 'posts_per_page', -1 );
}
});
```
* `is_singular()` is the wrong check here. `is_singular()` checks if you are on a singular post page, so it will always return false on any page that is not a singular post page.
What you need is `get_post_type()` to get the post type the post belongs to and test against that
```
if ( 'photo' === get_post_type() ) :
echo "<a href='/photo'>photo</a>";
elseif ( 'video' === get_post_type() ) :
echo "<a href='/video'>video</a>";
elseif ( 'web' === get_post_type() ) :
echo "<a href='/web'>web</a>";
endif;
```
* Lastly, if you want to link to the archive pages of those post types, you should be using [`get_post_type_archive()`](https://codex.wordpress.org/Function_Reference/get_post_type_archive_link). Something like the following would work
```
<a href="<?php echo get_post_type_archive_link( 'Photo' ); ?>">Photo</a>
```
instead of `echo "<a href='/photo'>photo</a>"`
EDIT
----
From comments, I have done an extensive answer on why not to use custom queries in place of the main query. Feel free to check it out [here](https://wordpress.stackexchange.com/a/155976/31545). It should answer quite a few questions for you |
220,396 | <p>I am using the 'standard' trick for category removal in wordpress. In my permalinks I set the permalinks structure to </p>
<pre><code>/%category%/%postname%/
</code></pre>
<p>And my category base to </p>
<pre><code>.
</code></pre>
<p>Which worked fine, until the client said he wants parent categories to appear in the header of the article, and the child categories to show in the footer of the articles on the home/index pages...</p>
<p>I've set it up, but the problem is that my child categories links are now:</p>
<pre><code>http://www.example.com/./parent_category/child_category
</code></pre>
<p>And when I click the child category, I get sent to the latest article.</p>
<p>I've tried to add in my <code>.htaccess</code></p>
<pre><code>RewriteRule ^category/(.+)$ http://www.example.com/$1 [R=301,L]
</code></pre>
<p>But this did nothing. </p>
<p>Now all this works, when I remove the dot, but then my links look like:</p>
<pre><code>http://www.example.com/category/parent_category/child_category
</code></pre>
<p>And client explicitly doesn't want <code>category/</code> in the link...</p>
<p>Other than installing a plugin, what can I do? How to sort this? Can I have </p>
<pre><code>http://www.example.com/parent_category/child_category
</code></pre>
<p>As my permalink, and if so how to achieve this?</p>
| [
{
"answer_id": 220790,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 2,
"selected": false,
"text": "<p>The \".\" method was always an unlikely kludge. </p>\n\n<p>The <a href=\"https://wordpress.org/plugins/rem... | 2016/03/11 | [
"https://wordpress.stackexchange.com/questions/220396",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58895/"
] | I am using the 'standard' trick for category removal in wordpress. In my permalinks I set the permalinks structure to
```
/%category%/%postname%/
```
And my category base to
```
.
```
Which worked fine, until the client said he wants parent categories to appear in the header of the article, and the child categories to show in the footer of the articles on the home/index pages...
I've set it up, but the problem is that my child categories links are now:
```
http://www.example.com/./parent_category/child_category
```
And when I click the child category, I get sent to the latest article.
I've tried to add in my `.htaccess`
```
RewriteRule ^category/(.+)$ http://www.example.com/$1 [R=301,L]
```
But this did nothing.
Now all this works, when I remove the dot, but then my links look like:
```
http://www.example.com/category/parent_category/child_category
```
And client explicitly doesn't want `category/` in the link...
Other than installing a plugin, what can I do? How to sort this? Can I have
```
http://www.example.com/parent_category/child_category
```
As my permalink, and if so how to achieve this? | The "." method was always an unlikely kludge.
The ["Remove Category URL" plug-in](https://wordpress.org/plugins/remove-category-url/) works fine and, in my experience, as advertised. I'm not sure about the basis of the aversion to installing a plug-in for this purpose is, but, if you don't want to do so for some reason, you could always just examine it, and copy and pare down the technique employed by the plug-in developers, though the code, which relies on mastery of built-in rules, is not actually very complicated. The entirety of the main file is only 128 lines, and the core functionality resides in around 100 of them, covering four actions and four filters.
If you don't want to install it as a plugin, I suppose you could just strip out the plug-in convenience and installation functions/files, and add the core functions to your theme functions file. I suspect that whatever method anyone else drafts here is likely just to re-invent the same wheel.
```
/**
* Plugin Name: Remove Category URL
* Plugin URI: http://valeriosouza.com.br/portfolio/remove-category-url/
* Description: This plugin removes '/category' from your category permalinks. (e.g. `/category/my-category/` to `/my-category/`)
* Version: 1.1
* Author: Valerio Souza, WordLab Academy
* Author URI: http://valeriosouza.com.br/
*/
/* hooks */
register_activation_hook( __FILE__, 'remove_category_url_refresh_rules' );
register_deactivation_hook( __FILE__, 'remove_category_url_deactivate' );
/* actions */
add_action( 'created_category', 'remove_category_url_refresh_rules' );
add_action( 'delete_category', 'remove_category_url_refresh_rules' );
add_action( 'edited_category', 'remove_category_url_refresh_rules' );
add_action( 'init', 'remove_category_url_permastruct' );
/* filters */
add_filter( 'category_rewrite_rules', 'remove_category_url_rewrite_rules' );
add_filter( 'query_vars', 'remove_category_url_query_vars' ); // Adds 'category_redirect' query variable
add_filter( 'request', 'remove_category_url_request' ); // Redirects if 'category_redirect' is set
add_filter( 'plugin_row_meta', 'remove_category_url_plugin_row_meta', 10, 4 );
function remove_category_url_refresh_rules() {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
function remove_category_url_deactivate() {
remove_filter( 'category_rewrite_rules', 'remove_category_url_rewrite_rules' ); // We don't want to insert our custom rules again
remove_category_url_refresh_rules();
}
/**
* Removes category base.
*
* @return void
*/
function remove_category_url_permastruct() {
global $wp_rewrite, $wp_version;
if ( 3.4 <= $wp_version ) {
$wp_rewrite->extra_permastructs['category']['struct'] = '%category%';
} else {
$wp_rewrite->extra_permastructs['category'][0] = '%category%';
}
}
/**
* Adds our custom category rewrite rules.
*
* @param array $category_rewrite Category rewrite rules.
*
* @return array
*/
function remove_category_url_rewrite_rules( $category_rewrite ) {
global $wp_rewrite;
$category_rewrite = array();
/* WPML is present: temporary disable terms_clauses filter to get all categories for rewrite */
if ( class_exists( 'Sitepress' ) ) {
global $sitepress;
remove_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ) );
$categories = get_categories( array( 'hide_empty' => false, '_icl_show_all_langs' => true ) );
add_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ) );
} else {
$categories = get_categories( array( 'hide_empty' => false ) );
}
foreach ( $categories as $category ) {
$category_nicename = $category->slug;
if ( $category->parent == $category->cat_ID ) {
$category->parent = 0;
} elseif ( 0 != $category->parent ) {
$category_nicename = get_category_parents( $category->parent, false, '/', true ) . $category_nicename;
}
$category_rewrite[ '(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$' ] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
$category_rewrite[ '(' . $category_nicename . ')/page/?([0-9]{1,})/?$' ] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
$category_rewrite[ '(' . $category_nicename . ')/?$' ] = 'index.php?category_name=$matches[1]';
}
// Redirect support from Old Category Base
$old_category_base = get_option( 'category_base' ) ? get_option( 'category_base' ) : 'category';
$old_category_base = trim( $old_category_base, '/' );
$category_rewrite[ $old_category_base . '/(.*)$' ] = 'index.php?category_redirect=$matches[1]';
return $category_rewrite;
}
function remove_category_url_query_vars( $public_query_vars ) {
$public_query_vars[] = 'category_redirect';
return $public_query_vars;
}
/**
* Handles category redirects.
*
* @param $query_vars Current query vars.
*
* @return array $query_vars, or void if category_redirect is present.
*/
function remove_category_url_request( $query_vars ) {
if ( isset( $query_vars['category_redirect'] ) ) {
$catlink = trailingslashit( get_option( 'home' ) ) . user_trailingslashit( $query_vars['category_redirect'], 'category' );
status_header( 301 );
header( "Location: $catlink" );
exit;
}
return $query_vars;
}
function remove_category_url_plugin_row_meta( $links, $file ) {
if( plugin_basename( __FILE__ ) === $file ) {
$links[] = sprintf(
'<a target="_blank" href="%s">%s</a>',
esc_url('http://wordlab.com.br/donate/'),
__( 'Donate', 'remove_category_url' )
);
}
return $links;
}
``` |
220,421 | <p>I was wondering if it's possible to set up user roles in a way that means that users in certain groups can ONLY edit posts that have a specific taxonomy assigned to them e.g:</p>
<pre><code>Properties (Post Type)
Taxonomy One
Taxonomy Two
Taxonomy Three
User Roles
Group One - Can only edit properties with 'Taxonomy One' assigned.
Group Two - Can only edit properties with 'Taxonomy Two' assigned.
Group Three - Can only edit properties with 'Taxonomy Three' assigned.
</code></pre>
<p>I'm using the <a href="https://wordpress.org/plugins/members/" rel="nofollow">Members plugin</a> for role management at the moment, and I'm using custom post types/taxonomies.</p>
<p>From what I've seen so far it doesn't look as though you can restrict access to POSTS based on TAXONOMIES.</p>
<p><strong>UPDATE</strong></p>
<p>I've now got permissions working for post types using the following code:</p>
<pre><code>register_post_type( 'properties',
array(
'labels' => array(
'name' => __( 'Properties' ),
'singular_name' => __( 'Property' )
),
'public' => true,
'capability_type' => 'property',
'map_meta_cap' => true,
'capabilities' => array(
'publish_posts' => 'publish_properties', // This allows a user to publish a property.
'edit_posts' => 'edit_properties', // Allows editing of the user’s own properties but does not grant publishing permission.
'edit_others_posts' => 'edit_others_properties', // Allows the user to edit everyone else’s properties but not publish.
'delete_posts' => 'delete_properties', // Grants the ability to delete properties written by that user but not others’ properties.
'delete_others_posts' => 'delete_others_properties', // Capability to edit properties written by other users.
'read_private_posts' => 'read_private_properties', // Allows users to read private properties.
'edit_post' => 'edit_property', // Meta capability assigned by WordPress. Do not give to any role.
'delete_post' => 'delete_property', // Meta capability assigned by WordPress. Do not give to any role.
'read_post' => 'read_property', // Meta capability assigned by WordPress. Do not give to any role.
)
)
);
</code></pre>
<p>A 'Properties' section has now appeared when editing roles in the 'Members' plugin which lets me restrict/allow access. Just need to figure out if this is do-able for each taxonomy now :)</p>
| [
{
"answer_id": 220424,
"author": "Jarod Thornton",
"author_id": 44017,
"author_profile": "https://wordpress.stackexchange.com/users/44017",
"pm_score": 0,
"selected": false,
"text": "<p>I actually dug up that plugin developers blog and this is what he offers as insight.</p>\n\n<blockquot... | 2016/03/11 | [
"https://wordpress.stackexchange.com/questions/220421",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78497/"
] | I was wondering if it's possible to set up user roles in a way that means that users in certain groups can ONLY edit posts that have a specific taxonomy assigned to them e.g:
```
Properties (Post Type)
Taxonomy One
Taxonomy Two
Taxonomy Three
User Roles
Group One - Can only edit properties with 'Taxonomy One' assigned.
Group Two - Can only edit properties with 'Taxonomy Two' assigned.
Group Three - Can only edit properties with 'Taxonomy Three' assigned.
```
I'm using the [Members plugin](https://wordpress.org/plugins/members/) for role management at the moment, and I'm using custom post types/taxonomies.
From what I've seen so far it doesn't look as though you can restrict access to POSTS based on TAXONOMIES.
**UPDATE**
I've now got permissions working for post types using the following code:
```
register_post_type( 'properties',
array(
'labels' => array(
'name' => __( 'Properties' ),
'singular_name' => __( 'Property' )
),
'public' => true,
'capability_type' => 'property',
'map_meta_cap' => true,
'capabilities' => array(
'publish_posts' => 'publish_properties', // This allows a user to publish a property.
'edit_posts' => 'edit_properties', // Allows editing of the user’s own properties but does not grant publishing permission.
'edit_others_posts' => 'edit_others_properties', // Allows the user to edit everyone else’s properties but not publish.
'delete_posts' => 'delete_properties', // Grants the ability to delete properties written by that user but not others’ properties.
'delete_others_posts' => 'delete_others_properties', // Capability to edit properties written by other users.
'read_private_posts' => 'read_private_properties', // Allows users to read private properties.
'edit_post' => 'edit_property', // Meta capability assigned by WordPress. Do not give to any role.
'delete_post' => 'delete_property', // Meta capability assigned by WordPress. Do not give to any role.
'read_post' => 'read_property', // Meta capability assigned by WordPress. Do not give to any role.
)
)
);
```
A 'Properties' section has now appeared when editing roles in the 'Members' plugin which lets me restrict/allow access. Just need to figure out if this is do-able for each taxonomy now :) | You might be able to use the filter `user_has_cap` which is used when checking for a particular capability (found in `/wp-includes/class-wp-user.php` in `has_cap`):
```
/**
* Dynamically filter a user's capabilities.
*
* @since 2.0.0
* @since 3.7.0 Added the user object.
*
* @param array $allcaps An array of all the user's capabilities.
* @param array $caps Actual capabilities for meta capability.
* @param array $args Optional parameters passed to has_cap(), typically object ID.
* @param WP_User $user The user object.
*/
$capabilities = apply_filters( 'user_has_cap', $this->allcaps, $caps, $args, $this );
```
So it would be something like:
```
add_filter('user_has_cap','check_post_taxonomy',10,4);
function check_post_taxonomy($allcaps,$caps,$args,$user) {
global $post; if (!isset($post)) {return $allcaps;}
$group = get_user_meta($user->ID,'special_edit_group',true);
$taxonomy = 'taxonomy_'.$group; // maybe set to a, b or c?
$terms = get_the_terms($post->ID,$taxonomy);
// if there are no terms, remove the user capability(s) for this check
// you may have to experiment to remove all the ones you want to
if (!$terms) {
unset($allcaps['edit_properties']);
}
return $allcaps;
}
```
I have done it this way because I realized the logic of the question is not quite right. If a post type has taxonomy A, B and C assigned to it, even if you set these capability filters for the role groups as you say, all three role groups would be able to edit anything in this post type anyway. In other words, there is no case where taxonomy A, B or C is "not" actually assigned.
Instead, I think you are really meaning "check whether this particular post has any terms assigned to it in taxonomy A"... and if so along group A to edit it, and so on. (Note: I have no idea if the above code will actually work for this case, it might need some more work. For example, currently this is checking for a user meta key for the group rather than an actual role/group.) |
220,435 | <p>How can I add the words "Posted on" before the post data in a Twentyfourteen theme's post? The default is only to show the date and clock icon.</p>
<p>I'm not sure if this is a basic modification or if it's going to be a fix unique to Twentyfourteen.</p>
<p>I found <a href="https://premium.wpmudev.org/blog/remove-date-from-wordpress-posts/" rel="nofollow">this web page</a> talking about <em>removing</em> the "posted on" text in the Twentyeleven theme (I hoped the themes would be similar). It said to look in the functions.php file for <code>function twentyeleven_posted_on()</code> but I was unable to find anything like that in the Twentyfourteen parent theme's functions.php file. There didn't seem to be anything directly relating to a post's date in the Twentyfourteen functions.php file.</p>
<p>I am using a child theme, so I assume I'm probably going to be putting an altered function in my child theme's functions.php file, but I can't find the original function in Twentfourteen.</p>
<p>The reason I ask is because Twentyfourteen default of only having the date has confused some of my readers; when the post is talking about an event they think the post date is the date of the event.</p>
<h2>Solution (Thanks to Tom Woodward and Dave Clements)</h2>
<p>Both Tom's and Dave's functions worked, but neither of them did at first because I was placing the new function below the <code>?></code> which is the ending tag for PHP and no code would work below it.</p>
<p>This was my existing child theme's functions.php file (just basically copied from the <a href="https://codex.wordpress.org/Child_Themes" rel="nofollow">Wordpress support guide on setting up a child theme</a>)</p>
<pre><code><?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
?>
</code></pre>
<p>I needed to add the new function in between the last <code>}</code> and the bottom <code>?></code></p>
<pre><code><?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
function add_publish_dates( $the_date, $d, $post ) {
if ( is_int( $post) ) {
$post_id = $post;
} else {
$post_id = $post->ID;
}
return 'Posted on '. date( 'Y-d-m - h:j:s', strtotime( $the_date ) );
}
add_action( 'get_the_date', 'add_publish_dates', 10, 3 );
?>
</code></pre>
<p>I eventually ended up using Tom Woodward's code because it placed the little clock icon before the "Posted on" whereas Dave Clement's put it after "Posted on" in between it and the date, which looked odd.</p>
<p>Then I changed the date formatting for the date after <code>return 'Posted on '. date</code> from <code>'Y-d-m - h:j:s'</code> (which displayed the date as 2016-16-03 - 12:00:00 [which oddly ALWAYS said it was posted at 12am, when the posts were not]) to <code>'F j, Y'</code> (Which displays the default "March 16, 2016")</p>
<pre><code><?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
function add_publish_dates( $the_date, $d, $post ) {
if ( is_int( $post) ) {
$post_id = $post;
} else {
$post_id = $post->ID;
}
return 'Posted on '. date( 'F j, Y', strtotime( $the_date ) );
}
add_action( 'get_the_date', 'add_publish_dates', 10, 3 );
?>
</code></pre>
<p>As I said, I ended up using Tom Woodward's code as a base, but Dave Clements code did exactly what I had asked (just not exactly what I wanted) and he solved the <code>?></code> problem for me, so I give Dave the point. But thank you so much to both Tom and Dave!</p>
| [
{
"answer_id": 220454,
"author": "Tom Woodward",
"author_id": 82797,
"author_profile": "https://wordpress.stackexchange.com/users/82797",
"pm_score": 0,
"selected": false,
"text": "<p>I took a look at the documentation <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/get... | 2016/03/11 | [
"https://wordpress.stackexchange.com/questions/220435",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90408/"
] | How can I add the words "Posted on" before the post data in a Twentyfourteen theme's post? The default is only to show the date and clock icon.
I'm not sure if this is a basic modification or if it's going to be a fix unique to Twentyfourteen.
I found [this web page](https://premium.wpmudev.org/blog/remove-date-from-wordpress-posts/) talking about *removing* the "posted on" text in the Twentyeleven theme (I hoped the themes would be similar). It said to look in the functions.php file for `function twentyeleven_posted_on()` but I was unable to find anything like that in the Twentyfourteen parent theme's functions.php file. There didn't seem to be anything directly relating to a post's date in the Twentyfourteen functions.php file.
I am using a child theme, so I assume I'm probably going to be putting an altered function in my child theme's functions.php file, but I can't find the original function in Twentfourteen.
The reason I ask is because Twentyfourteen default of only having the date has confused some of my readers; when the post is talking about an event they think the post date is the date of the event.
Solution (Thanks to Tom Woodward and Dave Clements)
---------------------------------------------------
Both Tom's and Dave's functions worked, but neither of them did at first because I was placing the new function below the `?>` which is the ending tag for PHP and no code would work below it.
This was my existing child theme's functions.php file (just basically copied from the [Wordpress support guide on setting up a child theme](https://codex.wordpress.org/Child_Themes))
```
<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
?>
```
I needed to add the new function in between the last `}` and the bottom `?>`
```
<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
function add_publish_dates( $the_date, $d, $post ) {
if ( is_int( $post) ) {
$post_id = $post;
} else {
$post_id = $post->ID;
}
return 'Posted on '. date( 'Y-d-m - h:j:s', strtotime( $the_date ) );
}
add_action( 'get_the_date', 'add_publish_dates', 10, 3 );
?>
```
I eventually ended up using Tom Woodward's code because it placed the little clock icon before the "Posted on" whereas Dave Clement's put it after "Posted on" in between it and the date, which looked odd.
Then I changed the date formatting for the date after `return 'Posted on '. date` from `'Y-d-m - h:j:s'` (which displayed the date as 2016-16-03 - 12:00:00 [which oddly ALWAYS said it was posted at 12am, when the posts were not]) to `'F j, Y'` (Which displays the default "March 16, 2016")
```
<?php
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
function theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
function add_publish_dates( $the_date, $d, $post ) {
if ( is_int( $post) ) {
$post_id = $post;
} else {
$post_id = $post->ID;
}
return 'Posted on '. date( 'F j, Y', strtotime( $the_date ) );
}
add_action( 'get_the_date', 'add_publish_dates', 10, 3 );
?>
```
As I said, I ended up using Tom Woodward's code as a base, but Dave Clements code did exactly what I had asked (just not exactly what I wanted) and he solved the `?>` problem for me, so I give Dave the point. But thank you so much to both Tom and Dave! | The post date is added by `twentyfourteen_posted_on` as shown in [content.php](https://themes.trac.wordpress.org/browser/twentyfourteen/1.6/content.php#L34). This function is in [/inc/template-tags.php](https://themes.trac.wordpress.org/browser/twentyfourteen/1.6/inc/template-tags.php#L101) and is correctly wrapped in an `if ( ! function_exists( 'twentyfourteen_posted_on' ) )` conditional so you can declare the same function in your child theme and modify it to your heart's content.
As such you could add a function like this to your theme's functions.php file and that should do the trick (note the addition of "Posted on " in the `printf` function:
```
function twentyfourteen_posted_on() {
if ( is_sticky() && is_home() && ! is_paged() ) {
echo '<span class="featured-post">' . __( 'Sticky', 'twentyfourteen' ) . '</span>';
}
// Set up and print post meta information.
printf( 'Posted on <span class="entry-date"><a href="%1$s" rel="bookmark"><time class="entry-date" datetime="%2$s">%3$s</time></a></span> <span class="byline"><span class="author vcard"><a class="url fn n" href="%4$s" rel="author">%5$s</a></span></span>',
esc_url( get_permalink() ),
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
get_the_author()
);
}
``` |
220,471 | <p>I'm working on getting the editor to look more like the front end by adding extra CSS to the TinyMCE rich text editor.</p>
<p>WordPress adds <code>/wp-includes/js/tinymce/skins/lightgray/content.min.css</code> and <code>/wp-includes/js/tinymce/skins/wordpress/wp-content.css</code> by default.</p>
<p>Is there an easy way to remove this?</p>
| [
{
"answer_id": 220472,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 2,
"selected": false,
"text": "<p>You should be able to remove these by hooking into the <code>mce_css</code> filter in your <code>functions... | 2016/03/12 | [
"https://wordpress.stackexchange.com/questions/220471",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/41488/"
] | I'm working on getting the editor to look more like the front end by adding extra CSS to the TinyMCE rich text editor.
WordPress adds `/wp-includes/js/tinymce/skins/lightgray/content.min.css` and `/wp-includes/js/tinymce/skins/wordpress/wp-content.css` by default.
Is there an easy way to remove this? | This is what I arrived at. This will remove just the custom wordpress css `/wp-includes/js/tinymce/skins/wordpress/wp-content.css`.
```
function squarecandy_tinymce_remove_mce_css($stylesheets)
{
$stylesheets = explode(',',$stylesheets);
foreach ($stylesheets as $key => $sheet) {
if (preg_match('/wp\-includes/',$sheet)) {
unset($stylesheets[$key]);
}
}
$stylesheets = implode(',',$stylesheets);
return $stylesheets;
}
add_filter("mce_css", "squarecandy_tinymce_remove_mce_css");
```
The other file loaded by default (`/wp-includes/js/tinymce/skins/lightgray/content.min.css`) is not part of the mce\_css filter. There does not appear to be any way to remove this without breaking TinyMCE. But of the two css files, this one adds less default things that need to be overridden. |
220,473 | <p>I need a way to change the themes "Live Preview" url within the Appearance->Themes page? I want the themes thumbnails to link to a demo site showcasing the theme and not open the customizer.
I looked into the code some but I am not seeing much for a solution, but was wondering if someone else has a trick for this.
Thanks</p>
| [
{
"answer_id": 220476,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 0,
"selected": false,
"text": "<p>Wordpress seems to call <code>wp_customize_url</code> to get the theme preview URL, and there's not much t... | 2016/03/12 | [
"https://wordpress.stackexchange.com/questions/220473",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38434/"
] | I need a way to change the themes "Live Preview" url within the Appearance->Themes page? I want the themes thumbnails to link to a demo site showcasing the theme and not open the customizer.
I looked into the code some but I am not seeing much for a solution, but was wondering if someone else has a trick for this.
Thanks | External *Live Previews* For Themes
-----------------------------------
The `Live Preview` buttons, on the `/wp-admin/themes.php` page, are generated from the *tmpl-theme* micro template:
```
<script id="tmpl-wpse" type="text/template">
...cut...
<div class="theme-actions">
<# if ( data.active ) { #>
<# if ( data.actions.customize ) { #>
<a class="button button-primary customize load-customize hide-if-no-customize" href="{{{ data.actions.customize }}}"><?php _e( 'Customize' ); ?></a>
<# } #>
<# } else { #>
<a class="button button-secondary activate" href="{{{ data.actions.activate }}}"><?php _e( 'Activate' ); ?></a>
<a class="button button-primary load-customize hide-if-no-customize" href="{{{ data.actions.customize }}}"><?php _e( 'Live Preview' ); ?></a>
<# } #>
</div>
...cut...
</script>
```
We can modify the *template data* via the `wp_prepare_themes_for_js` filter.
Here's an example:
```
/**
* External Live Previews
*/
add_filter( 'wp_prepare_themes_for_js', function( $prepared_themes )
{
//--------------------------
// Edit this to your needs:
$externals = [
'twentysixteen' => 'http://foo.tld/demo/twentysixteen/',
'twentyfifteen' => 'http://bar.tld/demo/twentyfifteen/'
];
//--------------------------
foreach( $externals as $slug => $url )
{
if( isset( $prepared_themes[$slug]['actions']['customize'] ) )
$prepared_themes[$slug]['actions']['customize'] = $url;
}
return $prepared_themes;
} );
```
But this will not work as expected, because of the `load-customize` class, that will trigger a click event and open up an *iframe* overlay with:
```
$('#wpbody').on( 'click', '.load-customize', function( event ) {
event.preventDefault();
// Store a reference to the link that opened the Customizer.
Loader.link = $(this);
// Load the theme.
Loader.open( Loader.link.attr('href') );
});
```
When we click on the `Live Preview` button, with an external url, it will trigger an error like:
>
> Uncaught SecurityError: Failed to execute '`pushState`' on 'History': A
> history state object with URL '`http://foo.tld/demo/twentysixteen/`'
> cannot be created in a document with origin '`http://example.tld`' and
> URL '`http://example.tld/wp-admin/themes.php`'.
>
>
>
We could prevent this, by double clicking (not really a reliable option) or by removing the `load-customize` class for the external preview links. Here's one such hack:
```
/**
* Remove the .load-customize class from buttons with external links
*/
add_action( 'admin_print_styles-themes.php', function()
{ ?>
<script>
jQuery(document).ready( function($) {
$('.load-customize').each( function( index ){
if( this.host !== window.location.host )
$( this ).removeClass( 'load-customize' );
} );
});
</script> <?php
} );
```
where I got the `this.host` idea from @daved [here](https://stackoverflow.com/a/18660968/2078474).
Another more drastic approach would be to override the `tmpl-theme` template. |
220,479 | <p>Permalinks are (finally) working for individual posts of the custom <code>yoga-event</code> type I've created.</p>
<p>And archive works without URL rewriting: </p>
<p><code>http://website.localhost/?post_type=yoga-event</code></p>
<p>However <code>get_post_type_archive_link( 'yoga-event' )</code> returns false.</p>
<p>This is the array I'm sending to <code>register_post_type</code>:</p>
<pre><code>Array
(
[labels] => Array
(
[name] => Yoga Events
[singular_name] => Yoga Event
[menu_name] => Yoga Events
[all_items] => Yoga Events
[add_new] => Add New
[add_new_item] => Add New Yoga Event
[edit_item] => Edit Yoga Event
[new_item] => New Yoga Event
[view_item] => View Yoga Event
[search_items] => Search Yoga Events
[not_found] => No Yoga Events found
[not_found_in_trash] => No Yoga Events found in Trash
[parent_item_colon] => Parent Yoga Event:
)
[public] => 1
[rewrite] => Array
(
[slug] => yoga-event
)
[has_arhchive] => 1
[menu_icon] => dashicons-book-alt
)
</code></pre>
<p>I can sort of make my own "archive" like this:</p>
<pre><code>$type = 'yoga-event';
$args=array(
'post_type' => $type,
'post_status' => 'publish',
'posts_per_page' => -1,
'ignore_sticky_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) :
$my_query->the_post();
?>
<p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?> </a></p>
<?php
endwhile;
} // list of yoga-event items
</code></pre>
<p>But I'm guessing that the array that <code>register_post_type</code> is getting has some kind of misconfiguration.</p>
<p>Any insights?</p>
<p>PS:</p>
<pre><code>//List Post Types
foreach ( get_post_types( '', 'names' ) as $post_type ) {
echo '<p>' . $post_type . '</p>';
}
</code></pre>
<p>Returns <code>yoga-event</code> (among others).</p>
| [
{
"answer_id": 220502,
"author": "frogg3862",
"author_id": 83367,
"author_profile": "https://wordpress.stackexchange.com/users/83367",
"pm_score": 2,
"selected": true,
"text": "<p>Can I see your <code>register_post_type</code> line? Those are usually like: <code>register_post_type( 'some... | 2016/03/12 | [
"https://wordpress.stackexchange.com/questions/220479",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48604/"
] | Permalinks are (finally) working for individual posts of the custom `yoga-event` type I've created.
And archive works without URL rewriting:
`http://website.localhost/?post_type=yoga-event`
However `get_post_type_archive_link( 'yoga-event' )` returns false.
This is the array I'm sending to `register_post_type`:
```
Array
(
[labels] => Array
(
[name] => Yoga Events
[singular_name] => Yoga Event
[menu_name] => Yoga Events
[all_items] => Yoga Events
[add_new] => Add New
[add_new_item] => Add New Yoga Event
[edit_item] => Edit Yoga Event
[new_item] => New Yoga Event
[view_item] => View Yoga Event
[search_items] => Search Yoga Events
[not_found] => No Yoga Events found
[not_found_in_trash] => No Yoga Events found in Trash
[parent_item_colon] => Parent Yoga Event:
)
[public] => 1
[rewrite] => Array
(
[slug] => yoga-event
)
[has_arhchive] => 1
[menu_icon] => dashicons-book-alt
)
```
I can sort of make my own "archive" like this:
```
$type = 'yoga-event';
$args=array(
'post_type' => $type,
'post_status' => 'publish',
'posts_per_page' => -1,
'ignore_sticky_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) :
$my_query->the_post();
?>
<p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?> </a></p>
<?php
endwhile;
} // list of yoga-event items
```
But I'm guessing that the array that `register_post_type` is getting has some kind of misconfiguration.
Any insights?
PS:
```
//List Post Types
foreach ( get_post_types( '', 'names' ) as $post_type ) {
echo '<p>' . $post_type . '</p>';
}
```
Returns `yoga-event` (among others). | Can I see your `register_post_type` line? Those are usually like: `register_post_type( 'some-post-type', $args );`.
In this example, `some-post-type` would be the ID that you use in `get_post_type_archive_link( 'some-post-type' )`, not the rewrite slug `yoga-event`. |
220,483 | <p>So, I have a few form fields like so:</p>
<pre><code><input name='mainStageSatOrder[theband][theid]' type='hidden' class='band-id' value='' />";
<input name='mainStageSatOrder[theband][theorder]' type='hidden' class='band-order' value='' />";
</code></pre>
<p>As you can see, these form fields (of which there are more, these are just examples of both types) create a multi-dimensional array like so (I hope, please correct me if I'm wrong):</p>
<pre><code>Array (
[mainStageSatOrder] => Array
(
[theband] => Array
(
[theid] => 1
[theorder] => 5
)
[theband] => Array
(
[theid] => 2
[theorder] => 8
)
)
)
</code></pre>
<p>I want these values to use the update_post_meta function to update the relevant fields when the page update is submitted. I know I can hook into the submit action post_submitbox_start action which I understand just fine. </p>
<p>What I'm not sure on, is what the PHP might be once the submit button is clicked. What I want to happen is that when the submit button is clicked, the multidimensional array is looped through using a foreach loop and for each 'theband' sub-array, the two values are used in the update_post_meta function.</p>
<pre><code>foreach(???) {
update_post_meta( 1, 'theorder', '5' ); //where 1 and 5 are values passed from the MD array
}
</code></pre>
<p>So, the process goes:</p>
<p>1) User clicks publish/update button
2) All values from all fields are passed into the multidimensional array
3) The MD array is looped through and, using update_post_meta, the relavent data is updated
4) Confirm yes/no</p>
<p>Thanks.</p>
| [
{
"answer_id": 220552,
"author": "iantsch",
"author_id": 90220,
"author_profile": "https://wordpress.stackexchange.com/users/90220",
"pm_score": 1,
"selected": false,
"text": "<p>You got a litte thinking problem with your MD array, it should look like that, otherwise you will overwrite d... | 2016/03/12 | [
"https://wordpress.stackexchange.com/questions/220483",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35299/"
] | So, I have a few form fields like so:
```
<input name='mainStageSatOrder[theband][theid]' type='hidden' class='band-id' value='' />";
<input name='mainStageSatOrder[theband][theorder]' type='hidden' class='band-order' value='' />";
```
As you can see, these form fields (of which there are more, these are just examples of both types) create a multi-dimensional array like so (I hope, please correct me if I'm wrong):
```
Array (
[mainStageSatOrder] => Array
(
[theband] => Array
(
[theid] => 1
[theorder] => 5
)
[theband] => Array
(
[theid] => 2
[theorder] => 8
)
)
)
```
I want these values to use the update\_post\_meta function to update the relevant fields when the page update is submitted. I know I can hook into the submit action post\_submitbox\_start action which I understand just fine.
What I'm not sure on, is what the PHP might be once the submit button is clicked. What I want to happen is that when the submit button is clicked, the multidimensional array is looped through using a foreach loop and for each 'theband' sub-array, the two values are used in the update\_post\_meta function.
```
foreach(???) {
update_post_meta( 1, 'theorder', '5' ); //where 1 and 5 are values passed from the MD array
}
```
So, the process goes:
1) User clicks publish/update button
2) All values from all fields are passed into the multidimensional array
3) The MD array is looped through and, using update\_post\_meta, the relavent data is updated
4) Confirm yes/no
Thanks. | First off, there's a problem with your array. Arrays can not have duplicate keys. So, only the first key will be saved. You need to change your form to something like this.
```
<input name='mainStageSatOrder[theband0][theid]' type='hidden' class='band-id' value='' />";
<input name='mainStageSatOrder[theband0][theorder]' type='hidden' class='band-order' value='' />";
<input name='mainStageSatOrder[theband1][theid]' type='hidden' class='band-id' value='' />";
<input name='mainStageSatOrder[theband1][theorder]' type='hidden' class='band-order' value='' />";
```
The array will look like this
```
$array = array(
'mainStageSatOrder' => array(
'theband0' => array(
'theid' => 1,
'theorder' => 5
),
'theband1' => array(
'theid' => 2,
'theorder' => 8
)
)
);
```
You don't need a foreach loop while saving the meta data. You can instead save it as an array. WordPress will automatically serialize it for you.
```
$array = $_POST['mainStageSatOrder'];
update_post_meta( $postid, 'mainStageSatOrder', $array );
```
And, while retriving the values..
```
$data = get_post_meta($post->ID, 'mainStageSatOrder', true);
```
The returned `$data` will be an array. |
220,508 | <p>This is My Category List :</p>
<p>1- Years
2- Genere</p>
<p>And I use This Code For show in posts :</p>
<pre><code><?php the_category(' , ') ?>
</code></pre>
<p>How Can Hide "Year or Genere" in up code?</p>
<p>Please Help Me.i want Show Only One Category.</p>
| [
{
"answer_id": 220552,
"author": "iantsch",
"author_id": 90220,
"author_profile": "https://wordpress.stackexchange.com/users/90220",
"pm_score": 1,
"selected": false,
"text": "<p>You got a litte thinking problem with your MD array, it should look like that, otherwise you will overwrite d... | 2016/03/12 | [
"https://wordpress.stackexchange.com/questions/220508",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90454/"
] | This is My Category List :
1- Years
2- Genere
And I use This Code For show in posts :
```
<?php the_category(' , ') ?>
```
How Can Hide "Year or Genere" in up code?
Please Help Me.i want Show Only One Category. | First off, there's a problem with your array. Arrays can not have duplicate keys. So, only the first key will be saved. You need to change your form to something like this.
```
<input name='mainStageSatOrder[theband0][theid]' type='hidden' class='band-id' value='' />";
<input name='mainStageSatOrder[theband0][theorder]' type='hidden' class='band-order' value='' />";
<input name='mainStageSatOrder[theband1][theid]' type='hidden' class='band-id' value='' />";
<input name='mainStageSatOrder[theband1][theorder]' type='hidden' class='band-order' value='' />";
```
The array will look like this
```
$array = array(
'mainStageSatOrder' => array(
'theband0' => array(
'theid' => 1,
'theorder' => 5
),
'theband1' => array(
'theid' => 2,
'theorder' => 8
)
)
);
```
You don't need a foreach loop while saving the meta data. You can instead save it as an array. WordPress will automatically serialize it for you.
```
$array = $_POST['mainStageSatOrder'];
update_post_meta( $postid, 'mainStageSatOrder', $array );
```
And, while retriving the values..
```
$data = get_post_meta($post->ID, 'mainStageSatOrder', true);
```
The returned `$data` will be an array. |
220,511 | <p>I need to print all terms associated to a custom post type post.
In the post template I wrote that code:</p>
<pre><code><?php foreach (get_the_terms(the_ID(), 'taxonomy') as $cat) : ?>
<?php echo $cat->name; ?>
<?php endforeach; ?>
</code></pre>
<p>The loop works correctly, but before the list also the id was printed. Like:</p>
<pre><code>37
taxonomy01
taxonomy02
taxonomy03
</code></pre>
<p>What is wrong?</p>
| [
{
"answer_id": 220512,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/the_ID\" rel=\"noreferrer\"><code>the_ID()</code></a> p... | 2016/03/12 | [
"https://wordpress.stackexchange.com/questions/220511",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90362/"
] | I need to print all terms associated to a custom post type post.
In the post template I wrote that code:
```
<?php foreach (get_the_terms(the_ID(), 'taxonomy') as $cat) : ?>
<?php echo $cat->name; ?>
<?php endforeach; ?>
```
The loop works correctly, but before the list also the id was printed. Like:
```
37
taxonomy01
taxonomy02
taxonomy03
```
What is wrong? | [`the_ID()`](https://codex.wordpress.org/Function_Reference/the_ID) print the post ID. You need to use the [`get_the_ID()`](https://developer.wordpress.org/reference/functions/get_the_ID/) which return the post ID.
Example:
```
foreach (get_the_terms(get_the_ID(), 'taxonomy') as $cat) {
echo $cat->name;
}
```
Always remember the naming convention of WordPress for template tags. `the` which mean to print `get` which mean to return in most of the cases. |
220,549 | <p>I want to add an inline word(s) after comments of post author's name. Suppose, my name is Tiger and i am the post author, so <strong>Post author</strong> will be printed after my name every time when i add a comment on the post.</p>
<p><a href="https://i.stack.imgur.com/Ca7iP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ca7iP.png" alt="Like this picture"></a></p>
<p>I don't want to edit comment.php file. I want custom functions for functions.php</p>
| [
{
"answer_id": 220553,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 0,
"selected": false,
"text": "<p>If I'm not getting it wrong, you are going to add some text to commenter's name if he is the post author, rig... | 2016/03/13 | [
"https://wordpress.stackexchange.com/questions/220549",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75682/"
] | I want to add an inline word(s) after comments of post author's name. Suppose, my name is Tiger and i am the post author, so **Post author** will be printed after my name every time when i add a comment on the post.
[](https://i.stack.imgur.com/Ca7iP.png)
I don't want to edit comment.php file. I want custom functions for functions.php | Just wanted to mention some alternatives:
Alternative #1
--------------
You say you don't want to edit the `comments.php` file in the current theme directory. If we need to change how the `wp_list_comments()` works, we can always modify it through the `wp_list_comments_args` filter. For example to add our own callback:
```
add_filter( 'wp_list_comments_args', function( $r )
{
if( function_exists( 'wpse_comment_callback' ) )
$r['callback'] = 'wpse_comment_callback';
return $r;
} );
```
where the `wpse_comment_callback()` callback contains the customization of your comment's layout.
Alternative #2
--------------
If we take a look at e.g. the *Twenty Sixteen* theme, we will see how the `.bypostauthor` class is used to mark the *post comment author* from the stylesheet:
```
.bypostauthor > article .fn:after {
content: "\f304";
left: 3px;
position: relative;
top: 5px;
}
```
where you could adjust the content attribute to your needs. This might not be the workaround for you, if you need to style it or use words with translations. |
220,572 | <p>Using WordPress 4.4.2 (latest version as of writing this)</p>
<p>I'm trying to use the [video] shortcode to show a video on my site. If I provide a url ending with the <code>filename.mp4</code> it works fine:</p>
<p><code>[video src="http://example.com/filename.mp4"]</code></p>
<p>but when I add a querystring parameter to the end of the URL, it refuses to show the video player. Instead, it just shows me a link to the URL:</p>
<p><code>[video src="http://example.com/filename.mp4?type=0"]</code></p>
<p>I've tried using the <code>mp4</code> attribute, and it produces the same result.</p>
<p>How do I get the [video] shortcode to allow querystring parameters in the <code>src</code> or <code>mp4</code> attributes?</p>
| [
{
"answer_id": 220553,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 0,
"selected": false,
"text": "<p>If I'm not getting it wrong, you are going to add some text to commenter's name if he is the post author, rig... | 2016/03/13 | [
"https://wordpress.stackexchange.com/questions/220572",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44758/"
] | Using WordPress 4.4.2 (latest version as of writing this)
I'm trying to use the [video] shortcode to show a video on my site. If I provide a url ending with the `filename.mp4` it works fine:
`[video src="http://example.com/filename.mp4"]`
but when I add a querystring parameter to the end of the URL, it refuses to show the video player. Instead, it just shows me a link to the URL:
`[video src="http://example.com/filename.mp4?type=0"]`
I've tried using the `mp4` attribute, and it produces the same result.
How do I get the [video] shortcode to allow querystring parameters in the `src` or `mp4` attributes? | Just wanted to mention some alternatives:
Alternative #1
--------------
You say you don't want to edit the `comments.php` file in the current theme directory. If we need to change how the `wp_list_comments()` works, we can always modify it through the `wp_list_comments_args` filter. For example to add our own callback:
```
add_filter( 'wp_list_comments_args', function( $r )
{
if( function_exists( 'wpse_comment_callback' ) )
$r['callback'] = 'wpse_comment_callback';
return $r;
} );
```
where the `wpse_comment_callback()` callback contains the customization of your comment's layout.
Alternative #2
--------------
If we take a look at e.g. the *Twenty Sixteen* theme, we will see how the `.bypostauthor` class is used to mark the *post comment author* from the stylesheet:
```
.bypostauthor > article .fn:after {
content: "\f304";
left: 3px;
position: relative;
top: 5px;
}
```
where you could adjust the content attribute to your needs. This might not be the workaround for you, if you need to style it or use words with translations. |
220,581 | <p>I have a main page and beyond that it has children. I successfully rewrite the children like so:</p>
<pre><code>add_rewrite_rule('my-url/?([^/]*)', 'index.php?my-var=$matches[1]', 'top');
</code></pre>
<p>This works great. But when I try to rewrite the base:</p>
<pre><code>add_rewrite_rule('my-url/?', 'index.php?my-var=main', 'top');
</code></pre>
<p>... it doesn't work. I know, it's getting rewritten by the first rule, so I switched them around, but then the children were all getting redirected to the main page.</p>
<p>Is there a way to make the second rule strict so that it will only be effective if there is NOTHING after the "my-url/" ? This way I should be able to move it first, and all should work.</p>
<p>I have searched the net and found no solution. Maybe it's my terms, but I'm racking myself on this one. I hate regex! Shoot me if it's simple!</p>
| [
{
"answer_id": 220583,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>This should work for both, slight adjustments to each regex pattern-</p>\n\n<pre><code>add_rewrite_rule('my-url/([... | 2016/03/13 | [
"https://wordpress.stackexchange.com/questions/220581",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85669/"
] | I have a main page and beyond that it has children. I successfully rewrite the children like so:
```
add_rewrite_rule('my-url/?([^/]*)', 'index.php?my-var=$matches[1]', 'top');
```
This works great. But when I try to rewrite the base:
```
add_rewrite_rule('my-url/?', 'index.php?my-var=main', 'top');
```
... it doesn't work. I know, it's getting rewritten by the first rule, so I switched them around, but then the children were all getting redirected to the main page.
Is there a way to make the second rule strict so that it will only be effective if there is NOTHING after the "my-url/" ? This way I should be able to move it first, and all should work.
I have searched the net and found no solution. Maybe it's my terms, but I'm racking myself on this one. I hate regex! Shoot me if it's simple! | Change your rewrite rules and the order to the following:
```
add_rewrite_rule('my-url/([^/]*)/?$', 'index.php?my-var=$matches[1]', 'top');
add_rewrite_rule('my-url/?$', 'index.php?my-var=main', 'top');
```
**Why the order?**
If the order would be the other way around, the first rule will always apply, so the ruleset would never reach your *main page*
**Why the changed syntax?**
To allow an additional query string to be properly processed. E.g. <http://foo.bar/my-url/?my-var=foo> and <http://foo.bar/my-url/foo/?bar=1> should be fetched to.
**Additionally:** A template redirect, if you want to apply your rewrite rules to query string requests like <http://foo.bar/my-url/?my-var=foo>:
```
function custom_template_redirect(){
preg_match('/(\?|&)my-var=/', $_SERVER['REQUEST_URI'], $matches);
if (
get_query_var( 'my-var', false ) !== false &&
!empty($matches) &&
!is_admin()
) {
wp_redirect(
home_url(
'/my-url/'.(get_query_var( 'my-var' )?get_query_var( 'my-var' ).'/':'')
)
);
exit();
}
}
add_action( 'template_redirect', 'custom_template_redirect' );
``` |
220,587 | <p>I am really clueless. I want to do an insertion in my WordPress plugin the problem is it doesn't return any errors nor it insert the stuff!</p>
<p>I don't know how to fix this and really need your help. In the following code i used example names, but i used the character <code>-</code> for these in case of that my real table has also names with <code>-</code> in it as well as the table itself.</p>
<p>Usually there is no problem, just use some back ticks `` and the stuff works well, but now welcome to WordPress. Is there a problem with the insertion function in WordPress or is there any other possible error?</p>
<p>I really tried to fix this by myself but i failed.</p>
<pre><code>$insertion = $wpdb->insert($wpdb->prefix.'table-name-of-plugin', array(
'column-name' => $stringValueForC1,
'second-column-name' => $stringValueForC2
), array('%s, %s'));
</code></pre>
<p>If i use <code>var_dump()</code> for the insertion variable i get: <code>int(0)</code>.
string <code>0</code> for <code>wpdb->last_error</code> and <code>bool(false)</code> for <code>wpdb->last_query</code>.</p>
<p>I also double checked my table name and it is 100% correct!
What can be the error?</p>
| [
{
"answer_id": 220615,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 0,
"selected": false,
"text": "<p>Issue exist in the data type format. You've passed <code>array('%s, %s')</code> take a closer look, instead of ... | 2016/03/13 | [
"https://wordpress.stackexchange.com/questions/220587",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90515/"
] | I am really clueless. I want to do an insertion in my WordPress plugin the problem is it doesn't return any errors nor it insert the stuff!
I don't know how to fix this and really need your help. In the following code i used example names, but i used the character `-` for these in case of that my real table has also names with `-` in it as well as the table itself.
Usually there is no problem, just use some back ticks `` and the stuff works well, but now welcome to WordPress. Is there a problem with the insertion function in WordPress or is there any other possible error?
I really tried to fix this by myself but i failed.
```
$insertion = $wpdb->insert($wpdb->prefix.'table-name-of-plugin', array(
'column-name' => $stringValueForC1,
'second-column-name' => $stringValueForC2
), array('%s, %s'));
```
If i use `var_dump()` for the insertion variable i get: `int(0)`.
string `0` for `wpdb->last_error` and `bool(false)` for `wpdb->last_query`.
I also double checked my table name and it is 100% correct!
What can be the error? | Your format is wrong.
On your code is should be
```
$insertion = $wpdb->insert($wpdb->prefix . 'table-name-of-plugin', array(
'column-name' => $stringValueForC1,
'second-column-name' => $stringValueForC2
), array('%s', '%s') );
```
Notice the change from
```
array('%s, %s')
```
to
```
array('%s', '%s')
```
Also, since you are setting the format for both of the value as string. I recommend that you just use
```
'%s'
```
The format parameter accepts either array or string. If it's string, the string will be used as the format for all the values. Source - <https://codex.wordpress.org/Class_Reference/wpdb#INSERT_row> |
220,595 | <p>I know that the style.css file needs to be copied to the child theme before being edited for changes. Is that also true for template.php files? If so, do I need to just copy the specific template file only, or should I copy all?</p>
<p><strong>UPDATE:</strong></p>
<p><em>includes/breadcrumbs.php:</em></p>
<pre><code><?php
if ( is_front_page() ) return;
if ( class_exists( 'woocommerce' ) && is_woocommerce() ) {
woocommerce_breadcrumb();
return;
}
?>
<div id="breadcrumbs"<?php if ( function_exists( 'bcn_display') ) echo ' class="bcn_breadcrumbs"'; ?>>
<?php if(function_exists('bcn_display')) { bcn_display(); }
else {
$et_breadcrumbs_content_open = true;
?>
<span class="et_breadcrumbs_content">
<a href="<?php echo esc_url( home_url() ); ?>" class="breadcrumbs_home"><?php esc_html_e('Home','Nexus'
...
</code></pre>
| [
{
"answer_id": 220597,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>You should only copy the files you intend to change, otherwise when the parent theme is updated, it will loa... | 2016/03/14 | [
"https://wordpress.stackexchange.com/questions/220595",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89458/"
] | I know that the style.css file needs to be copied to the child theme before being edited for changes. Is that also true for template.php files? If so, do I need to just copy the specific template file only, or should I copy all?
**UPDATE:**
*includes/breadcrumbs.php:*
```
<?php
if ( is_front_page() ) return;
if ( class_exists( 'woocommerce' ) && is_woocommerce() ) {
woocommerce_breadcrumb();
return;
}
?>
<div id="breadcrumbs"<?php if ( function_exists( 'bcn_display') ) echo ' class="bcn_breadcrumbs"'; ?>>
<?php if(function_exists('bcn_display')) { bcn_display(); }
else {
$et_breadcrumbs_content_open = true;
?>
<span class="et_breadcrumbs_content">
<a href="<?php echo esc_url( home_url() ); ?>" class="breadcrumbs_home"><?php esc_html_e('Home','Nexus'
...
``` | Generally, you do not need to copy the complete parent stylesheet to your child theme, you can just copy the particular code in question to your child theme's stylesheet and modify that.
As for `functions.php` and any other functions related files, you cannot copy that to your child theme as this will lead to a cannot redeclare fatal error. There are a few write-ups on this, so be sure to use the site search for this.
Templates files should always be modified in a child theme (*if you are not the parent theme's author*) as templates are theme territory. You only need to copy the affected templates. It should be noted, for page templates, you need to keep the same file structure as the parent theme.
The real question is if whether or not you should copy a template and modify it. With the large amount of native filters and actions available to filter template tags, template parts, the loop itself, the posts array, nav menus, headers and footer, etc etc, it has became increasingly easy to change something via a custom plugin without having to directly alter template files itself. Changing these specifics via their respective filters and actions via a plugin have the added benefit of making these changes available across any theme used at any given time. It would be beneficial to sit down and decide what you would need to change and whether that change would be needed when you change themes before jumping in and copying a template file to a child theme to modify it.
Some of the big commercial themes have added theme specific filters which you can use to filter certain things within a template. In most cases you can alter a template through just these filters, in which case you would use these filters in your child theme's functions file to alter the parent template's output accordingly.
If your changes cannot be done through filters and actions, then yes, the correct way would be to copy that particular template to your child theme and modifying it there. The only drawback will then be that you would need to manually keep those templates updated |
220,619 | <p>What is the difference between <code>$GLOBALS['wp_the_query']</code> and <code>global $wp_query</code>?</p>
<p>Why prefer one over the other?</p>
| [
{
"answer_id": 220620,
"author": "Jebble",
"author_id": 81939,
"author_profile": "https://wordpress.stackexchange.com/users/81939",
"pm_score": 2,
"selected": false,
"text": "<p>The global keyword imports the variable into the local scope, while $GLOBALS just grants you access to the var... | 2016/03/14 | [
"https://wordpress.stackexchange.com/questions/220619",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27196/"
] | What is the difference between `$GLOBALS['wp_the_query']` and `global $wp_query`?
Why prefer one over the other? | You have missed one, `$GLOBALS['wp_query']`. For all purposes, `$GLOBALS['wp_query'] === $wp_query`. `$GLOBALS['wp_query']` is however better for readability and should be used instead of `$wp_query`, BUT, that remains personal preference
Now, in a perfect world where unicorns rule the world, `$GLOBALS['wp_the_query'] === $GLOBALS['wp_query'] === $wp_query`. By default, this should be true. If we look at where these globals are set (*[`wp-settings.php`](https://github.com/WordPress/WordPress/blob/5.3.2/wp-settings.php#L407-L422)*), you will see the main query object is stored in `$GLOBALS['wp_the_query']` and `$GLOBALS['wp_query']` is just a duplicate copy of `$GLOBALS['wp_the_query']`
```
/**
* WordPress Query object
* @global WP_Query $wp_the_query
* @since 2.0.0
*/
$GLOBALS['wp_the_query'] = new WP_Query();
/**
* Holds the reference to @see $wp_the_query
* Use this global for WordPress queries
* @global WP_Query $wp_query
* @since 1.5.0
*/
$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
```
The reason for doing it this way, is because WordPress saw the arrival of [`query_posts`](https://developer.wordpress.org/reference/functions/query_posts/) in version 1.5.
```
function query_posts($query) {
$GLOBALS['wp_query'] = new WP_Query();
return $GLOBALS['wp_query']->query($query);
}
```
As you can see, `query_posts` sets the main query object to the current custom query beign run. This breaks the integrity of the main query object, which gives you incorrect data, so anything that relies on the main query object is broken due to wrong data.
A way to counter this was to create another global to store the main query object, `$GLOBALS['wp_the_query']` which was introduced in version 2.0.0. This new global hold the main query object and `$GLOBALS['wp_query']` just a copy. Through `wp_reset_query()`, we could now reset `$GLOBALS['wp_query']` back to the original main query object to restore its integrity.
But this is not a perfect world, and `query_posts` are the devil himself. Although thousands of warnings, people still use `query_posts`. Apart from breaking the main query, it reruns the main query, making it much slower as a normal custom query with `WP_Query`. Many people also do not reset the `query_posts` query with `wp_reset_query()` when done, which makes `query_posts` even more evil.
Because we cannot do anything about that, and cannot stop plugins and themes from using `query_posts` and we can never know if a `query_posts` query was reset with `wp_reset_query()`, we need a more reliable copy of the main query object which we know will give us 99.99999% reliable, correct data. That is where `$GLOBALS['wp_the_query']` is useful as no WordPress related code can change it's value (*except through the filters and actions inside `WP_Query` itself*).
Quick proof, run the following
```
var_dump( $GLOBALS['wp_the_query'] );
var_dump( $GLOBALS['wp_query'] );
query_posts( 's=crap' );
var_dump( $GLOBALS['wp_the_query'] );
var_dump( $GLOBALS['wp_query'] );
```
and check the results. `$GLOBALS['wp_the_query']` did not change, and `$GLOBALS['wp_query']` has. So which is more reliable?
Final note, `$GLOBALS['wp_the_query']` is **NOT** a replacement for `wp_reset_query()`. `wp_reset_query()` should **always** be used with `query_posts`, and `query_posts` should **never** be used.
TO CONCLUDE
-----------
If you need reliable code which will almost always never fail, use `$GLOBALS['wp_the_query']`, if you trust and believe plugins and theme code and believe no one uses `query_posts` or is using it correctly, use `$GLOBALS['wp_query']` or `$wp_query`
IMPORTANT EDIT
--------------
Being answering questions on this site now for a couple of years, I saw many users using `$wp_query` as a local variable, which in turn also breaks the main query object. This further increases the vulnerabilty of the `$wp_query`.
As example, some people to this
```
$wp_query = new WP_Query( $args );
```
which is in essence the exactly the same as what `query_posts` are doing |
220,639 | <p>When I switched to using a blank theme, the WordPress dashboard disappeared. </p>
<p>To re-activate the previous theme I was using (which did have dashboard support), I reset the values of <em>template, stylesheet</em> and <em>current_theme</em> fields in the <em>wp_options</em> table to the previous theme (by manually entering the theme name). However, this failed to restore the dashboard. I did restart both the MySQL database and the Apache web server. I am using the Bitnami WAMP stack.</p>
<p>How can I manually activate my previous theme without browser access to dashboard?</p>
| [
{
"answer_id": 220841,
"author": "Monkey Puzzle",
"author_id": 48568,
"author_profile": "https://wordpress.stackexchange.com/users/48568",
"pm_score": 0,
"selected": false,
"text": "<p>At the server, can you delete (or download and delete) the current non-working theme? The other one (if... | 2016/03/14 | [
"https://wordpress.stackexchange.com/questions/220639",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89458/"
] | When I switched to using a blank theme, the WordPress dashboard disappeared.
To re-activate the previous theme I was using (which did have dashboard support), I reset the values of *template, stylesheet* and *current\_theme* fields in the *wp\_options* table to the previous theme (by manually entering the theme name). However, this failed to restore the dashboard. I did restart both the MySQL database and the Apache web server. I am using the Bitnami WAMP stack.
How can I manually activate my previous theme without browser access to dashboard? | In your current theme, you can use switch\_theme('stylesheet') in the index.php of your theme folder.No need to make changes in the database :)
```
<?php
switch_theme('twentyfifteen');//Specify the name of stylesheet of intended theme
exit;
//Rest of the code
?>
```
You can remove the code after use |
220,650 | <p>I am adding an admin notice via the conventional <code>admin_notice</code> hook in my plugin:</p>
<pre><code>function my_admin_notice() { ?>
<div class="notice notice-info is-dismissible">
<p><?php _e( 'some message', 'my-text-domain' ); ?></p>
</div>
<?php
}
if ( my_plugin_show_admin_notice() )
add_action( 'admin_notices', 'my_admin_notice' );
</code></pre>
<p>How can I control where wordpress places the admin notice, in the html on the current screen, without using Javascript?</p>
| [
{
"answer_id": 220652,
"author": "iantsch",
"author_id": 90220,
"author_profile": "https://wordpress.stackexchange.com/users/90220",
"pm_score": 2,
"selected": false,
"text": "<p>According to the Codex <code>admin_notice</code> does the following:</p>\n\n<blockquote>\n <p>Notices displa... | 2016/03/14 | [
"https://wordpress.stackexchange.com/questions/220650",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/15010/"
] | I am adding an admin notice via the conventional `admin_notice` hook in my plugin:
```
function my_admin_notice() { ?>
<div class="notice notice-info is-dismissible">
<p><?php _e( 'some message', 'my-text-domain' ); ?></p>
</div>
<?php
}
if ( my_plugin_show_admin_notice() )
add_action( 'admin_notices', 'my_admin_notice' );
```
How can I control where wordpress places the admin notice, in the html on the current screen, without using Javascript? | I found out by accident recently that all the notices will be moved to after the first `<h2>` tag on the page inside a `<div class="wrap">`. This gives you some *slight* control in that, for example, on a plugin settings page you can put an empty `<h2></h2>` at the very top if you want to use `<h2>Plugin Title</h2>` without it messing up the display formatting there. |
220,661 | <p><strong>What I'm trying to do:</strong><br>
Make an ajax-powered search button that gets the text from an input and give a list of post id's that match that search.</p>
<p>Note: I must probably sound very stupid to 90% of you, but I'm rather new to ajax and wordpress, so if I'm doing it all wrong, it would be great if someone could point me out what I'm doing wrong or if he knows a better guide than the ones I used. (The problems I think I'm having with the script are written all the way down below.)</p>
<p>To start I thought of just making <strong>a button that uses ajax to get the title of a post-id.</strong><Br>
I read these pages:</p>
<ul>
<li><a href="https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/" rel="nofollow">https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/</a></li>
<li><a href="https://developer.wordpress.org/plugins/javascript/summary/" rel="nofollow">https://developer.wordpress.org/plugins/javascript/summary/</a></li>
</ul>
<p>I've tried out all this code on both these pages, however, I'm always stuck because I need to create a plugin. <strong>I'm not trying to create a plugin</strong> so I was wondering if I could just write all the code on my search page.</p>
<p>I'm sad however that it doesn't work, and I cannot find out why... (i get redirected to the homepage)</p>
<p>I'm just curious if I have to research how to create plugins etc. or is there a much simpler way that just allows me to get e.g. the post title of a certain ID through an AJAX call without using a plugin?</p>
<p>This is the code I tried:</p>
<p><strong>The Ajax call:</strong></p>
<pre><code><script>
jQuery(document).ready(function($) { //wrapper
$("body").on("click",".ajax",function() { //event
var s_str = this.value;
console.log(s_str);
console.log(admin_ajax_url.ajax_url);
var this2 = this; //use in callback
$.post(admin_ajax_url.ajaxurl, { //POST request
_ajax_nonce: get_title_nonce.nonce, //nonce
action: "get_title", //action
id: s_str, //data
success: function(response) {
if(response.type == "success") {
alert("success")
}
else {
alert("failed")
}
}
}, function(data) { //callback
$("#tt").html(data); //insert server response
});
});
});
</script>
</code></pre>
<p><strong>The search form:</strong></p>
<pre><code>$the_title = '';
$s_str = 18694;
$nonce = wp_create_nonce("get_title_nonce");
$link = admin_url('http://jtc.ae/pre/wp/wp-admin/admin-ajax.php?action=get_title&post_id='.$s_str.'&nonce='.$nonce);
echo '<a class="ajax" data-nonce="' . $nonce . '" data-post_id="' . $s_str . '" href="' . $link . '">'.$s_str.'</a> Title: <span id="tt">'.$the_title."</span>";
</code></pre>
<p><strong>The rest of the code I added as written in the guides:</strong><br></p>
<pre><code><?php
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script('ajax_search',TEMPLATEPATH.'/new/js/ajax_search.js', array('jquery'));
wp_localize_script('ajax_search', 'admin_ajax_url', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'ajax_search' );
}
add_action("wp_ajax_get_title", "get_title");
add_action("wp_ajax_nopriv_get_title", "get_title_must_login");
function get_title() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "get_title")) {
exit("No naughty business please");
}
$the_title = get_the_title($_REQUEST["post_id"]);
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
function get_title_must_login() {
echo "You must log in to get title";
die();
}
?>
</code></pre>
<p><strong>Probably the problems lie here:</strong><br>
I'm not sure about these <code>add_action</code> parts... I don't think I need it if I add the link to admin-ajax.php directly like I did just here above:
<code>http://jtc.ae/pre/wp/wp-admin/admin-ajax.php?</code> So could I just scrap this first <code>add_action</code>?</p>
<p>Also I think that the bottom <code>add_action</code>s are probably not properly excecuted on my search_page.php. But this is just the thing: I'm not planning on creating any plugins, so I don't know where to put them...</p>
| [
{
"answer_id": 220652,
"author": "iantsch",
"author_id": 90220,
"author_profile": "https://wordpress.stackexchange.com/users/90220",
"pm_score": 2,
"selected": false,
"text": "<p>According to the Codex <code>admin_notice</code> does the following:</p>\n\n<blockquote>\n <p>Notices displa... | 2016/03/14 | [
"https://wordpress.stackexchange.com/questions/220661",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87968/"
] | **What I'm trying to do:**
Make an ajax-powered search button that gets the text from an input and give a list of post id's that match that search.
Note: I must probably sound very stupid to 90% of you, but I'm rather new to ajax and wordpress, so if I'm doing it all wrong, it would be great if someone could point me out what I'm doing wrong or if he knows a better guide than the ones I used. (The problems I think I'm having with the script are written all the way down below.)
To start I thought of just making **a button that uses ajax to get the title of a post-id.**
I read these pages:
* <https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/>
* <https://developer.wordpress.org/plugins/javascript/summary/>
I've tried out all this code on both these pages, however, I'm always stuck because I need to create a plugin. **I'm not trying to create a plugin** so I was wondering if I could just write all the code on my search page.
I'm sad however that it doesn't work, and I cannot find out why... (i get redirected to the homepage)
I'm just curious if I have to research how to create plugins etc. or is there a much simpler way that just allows me to get e.g. the post title of a certain ID through an AJAX call without using a plugin?
This is the code I tried:
**The Ajax call:**
```
<script>
jQuery(document).ready(function($) { //wrapper
$("body").on("click",".ajax",function() { //event
var s_str = this.value;
console.log(s_str);
console.log(admin_ajax_url.ajax_url);
var this2 = this; //use in callback
$.post(admin_ajax_url.ajaxurl, { //POST request
_ajax_nonce: get_title_nonce.nonce, //nonce
action: "get_title", //action
id: s_str, //data
success: function(response) {
if(response.type == "success") {
alert("success")
}
else {
alert("failed")
}
}
}, function(data) { //callback
$("#tt").html(data); //insert server response
});
});
});
</script>
```
**The search form:**
```
$the_title = '';
$s_str = 18694;
$nonce = wp_create_nonce("get_title_nonce");
$link = admin_url('http://jtc.ae/pre/wp/wp-admin/admin-ajax.php?action=get_title&post_id='.$s_str.'&nonce='.$nonce);
echo '<a class="ajax" data-nonce="' . $nonce . '" data-post_id="' . $s_str . '" href="' . $link . '">'.$s_str.'</a> Title: <span id="tt">'.$the_title."</span>";
```
**The rest of the code I added as written in the guides:**
```
<?php
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script('ajax_search',TEMPLATEPATH.'/new/js/ajax_search.js', array('jquery'));
wp_localize_script('ajax_search', 'admin_ajax_url', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'ajax_search' );
}
add_action("wp_ajax_get_title", "get_title");
add_action("wp_ajax_nopriv_get_title", "get_title_must_login");
function get_title() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "get_title")) {
exit("No naughty business please");
}
$the_title = get_the_title($_REQUEST["post_id"]);
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
function get_title_must_login() {
echo "You must log in to get title";
die();
}
?>
```
**Probably the problems lie here:**
I'm not sure about these `add_action` parts... I don't think I need it if I add the link to admin-ajax.php directly like I did just here above:
`http://jtc.ae/pre/wp/wp-admin/admin-ajax.php?` So could I just scrap this first `add_action`?
Also I think that the bottom `add_action`s are probably not properly excecuted on my search\_page.php. But this is just the thing: I'm not planning on creating any plugins, so I don't know where to put them... | I found out by accident recently that all the notices will be moved to after the first `<h2>` tag on the page inside a `<div class="wrap">`. This gives you some *slight* control in that, for example, on a plugin settings page you can put an empty `<h2></h2>` at the very top if you want to use `<h2>Plugin Title</h2>` without it messing up the display formatting there. |
220,680 | <p>i had to resize a lot of existing images in my upload folder (around 1k). After reuploading them, Wordpress of course, doesn't recognize the new dimensions. My approach was to just change the size in the _post_meta table. But this looks like this:</p>
<pre><code>a:6{s:5:"width";s:3:"330";s:6:"height";s:4:"1067";s:14:"hwstring_small";s:22:"height='96' width='29'";s:4:"file";s:22:"2012/03/2-IMG_1540.png";s:5:"sizes";a:3:{s:9:"thumbnail";a:3:{s:4:"file";s:21:"2-IMG_1540-56x183.png"; ...
</code></pre>
<p>All I need to change is the "width" value of the first entry from "330" to sth. else. Although it looks like a dictionary to me I do not find a way to get access to that value in SQL. </p>
<p>The wp_update_attachment_metadata reference states that all data must be given as existing data will be wiped. That's the reason why I thought it would be easier to do it in SQL.</p>
| [
{
"answer_id": 220684,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>What you are looking at is PHP <a href=\"http://php.net/manual/en/function.serialize.php\" rel=\"nofollow\">seriali... | 2016/03/14 | [
"https://wordpress.stackexchange.com/questions/220680",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90571/"
] | i had to resize a lot of existing images in my upload folder (around 1k). After reuploading them, Wordpress of course, doesn't recognize the new dimensions. My approach was to just change the size in the \_post\_meta table. But this looks like this:
```
a:6{s:5:"width";s:3:"330";s:6:"height";s:4:"1067";s:14:"hwstring_small";s:22:"height='96' width='29'";s:4:"file";s:22:"2012/03/2-IMG_1540.png";s:5:"sizes";a:3:{s:9:"thumbnail";a:3:{s:4:"file";s:21:"2-IMG_1540-56x183.png"; ...
```
All I need to change is the "width" value of the first entry from "330" to sth. else. Although it looks like a dictionary to me I do not find a way to get access to that value in SQL.
The wp\_update\_attachment\_metadata reference states that all data must be given as existing data will be wiped. That's the reason why I thought it would be easier to do it in SQL. | You could do this via PHP instead of SQL, just get the existing metadata and change what you need to, it will handle the serializing for you:
```
$newwidth = '250'; // or whatever it is
$attachments = get_posts(array('post_type'=>'attachment'));
foreach ($attachments as $attachment) {
$id = $attachment->ID;
$metadata = wp_get_attachment_metadata($id);
$metadata['width'] = $newwidth;
wp_update_attachment_metadata($id,$metadata);
}
```
But really, you may do better using the [Regenerate Thumbnails Plugin](http://wordpres.org/plugins/regenerate-thumbnails/) which may fix this and regenerate the different thumbnail sizes at the same time. |
220,716 | <p>Currently I've tried this process with two browsers: Google Chrome and Mozilla Firefox. Whenever I want to run a JavaScript code on them they show me the raw code instead of executing it. Exactly what I wrote in my Editor will be shown in the browser screen.</p>
<p>Hope someone can help.</p>
<h2>Edit</h2>
<blockquote>
<p>Hey, am not using wordpress. </p>
</blockquote>
<p>Sorry that I didn't put the code here. Here is
the code in my text Editor:</p>
<pre><code><Script> Document.write("hello world") </script>
</code></pre>
<p>This is what it output .... </p>
<pre><code><Script> Document.write("hello world") </script>
</code></pre>
<p>The same thing.</p>
| [
{
"answer_id": 220683,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 4,
"selected": false,
"text": "<p>The best reason I can find it to separate Logic from Structure or Control from Markup. The handbook on the ... | 2016/03/15 | [
"https://wordpress.stackexchange.com/questions/220716",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83327/"
] | Currently I've tried this process with two browsers: Google Chrome and Mozilla Firefox. Whenever I want to run a JavaScript code on them they show me the raw code instead of executing it. Exactly what I wrote in my Editor will be shown in the browser screen.
Hope someone can help.
Edit
----
>
> Hey, am not using wordpress.
>
>
>
Sorry that I didn't put the code here. Here is
the code in my text Editor:
```
<Script> Document.write("hello world") </script>
```
This is what it output ....
```
<Script> Document.write("hello world") </script>
```
The same thing. | As in many things wordpress, inertia has a lot to do with why things are done in specific way. Early core themes were written using those constructs and later developers copied them because they either did not know better or thought there was some non obvious reason to prefer them.
As @Howdy\_McGee said, it is just a style preference but I would avoid the `endif`, `endwhile` as curly braces are standard block delimiters across many languages and therefor are in general easier to read even if we will ignore the benefit of syntax highlighting and block collapsing in general editors. |
220,726 | <p>I want to add a support page to my plugin wordpress. My plugin is already developed. Now I want to allow users to contact me for any question. I want the support button to be next to the activate and Update buttons in the plugin add page.</p>
| [
{
"answer_id": 220728,
"author": "denis.stoyanov",
"author_id": 76287,
"author_profile": "https://wordpress.stackexchange.com/users/76287",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(... | 2016/03/15 | [
"https://wordpress.stackexchange.com/questions/220726",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90607/"
] | I want to add a support page to my plugin wordpress. My plugin is already developed. Now I want to allow users to contact me for any question. I want the support button to be next to the activate and Update buttons in the plugin add page. | You can use the [`plugin_action_links_`](https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name)) filter for that task:
```
add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'add_support_link_wpse_220726' );
function add_support_link_wpse_220726( $links ) {
$links[] = '<a href="http://example.com/support/" target="_blank">Support</a>';
return $links;
}
```
Note that you must also pass the plugin name (`plugin_basename(__FILE__)`) for it to work. That's why take into consideration from where you will call it. |
220,789 | <p>Im experimenting with random theme and "new technology" and Im trying to convert whole front-end to pure JS single page application <em>(no page refreshes - like Facebook, Twitter etc)</em> using <a href="http://wp-api.org/" rel="nofollow">WP REST API</a>, <a href="http://redux.js.org/" rel="nofollow">Redux.js</a> and <a href="https://facebook.github.io/react/" rel="nofollow">React.js</a> and few other helpers.</p>
<p><strong>How to handle logged-in users?</strong> How do I keep track of that? I know that this information is normally handled with cookies. How would one check it <em>via</em> JS?</p>
<p>I could just make an ajax call every time route/url changes and use <code>is_user_logged_in()</code> in server-side but it seems primative. Could I access directly to cookie <em>via</em> JS and check it in browser?</p>
<hr>
<ul>
<li>I gave it a long thought if that's off-topic here but it really seems like a very WP specific question</li>
<li>Im just experimenting and trying to push it to a new level, please no <em>"this is a bad idea"</em> comments</li>
</ul>
| [
{
"answer_id": 220792,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 0,
"selected": false,
"text": "<p>You will need to check cookies than (and probably DB) or call a function somehow (maybe ajax or somet... | 2016/03/15 | [
"https://wordpress.stackexchange.com/questions/220789",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80903/"
] | Im experimenting with random theme and "new technology" and Im trying to convert whole front-end to pure JS single page application *(no page refreshes - like Facebook, Twitter etc)* using [WP REST API](http://wp-api.org/), [Redux.js](http://redux.js.org/) and [React.js](https://facebook.github.io/react/) and few other helpers.
**How to handle logged-in users?** How do I keep track of that? I know that this information is normally handled with cookies. How would one check it *via* JS?
I could just make an ajax call every time route/url changes and use `is_user_logged_in()` in server-side but it seems primative. Could I access directly to cookie *via* JS and check it in browser?
---
* I gave it a long thought if that's off-topic here but it really seems like a very WP specific question
* Im just experimenting and trying to push it to a new level, please no *"this is a bad idea"* comments | As you are going to send ajax request from theme (frontend) you need to specify the ajaxurl otherwise it will throw an error "undefined ajaurl"
```
/**
* frontend ajax requests.
*/
wp_enqueue_script( 'frontend-ajax', JS_DIR_URI . 'frontend-ajax.js', array('jquery'), null, true );
wp_localize_script( 'frontend-ajax', 'frontend_ajax_object',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
)
);
```
then in your frontend-ajax.js you can can send ajax request like this
```
$.ajax({
url: frontend_ajax_object.ajaxurl,
type: 'GET',
data: {
action: 'register_action_hook',
},
success: function( response ) {
console.log( response );
},
});
```
then in your functions.php you can hook your function to the register\_action\_hook.
```
add_action( 'wp_ajax_register_action_hook', 'prefix_do_something' );
function prefix_do_something() {
if ( is_user_logged_in ) {
// do something
} else {
// do something else
}
}
```
you can also use the @Howdy\_McGee method to localize the is\_logged\_in variable using
```
wp_localize_script( 'handler', 'js_object', $array_of_variables );
```
and accessing it in your js with js\_object.variable\_name see the @Howdy\_McGee answer for reference. |
220,802 | <p>I've found several other threads asking this same question, but for some reason I can't seem to make a solution work for me. For clarification, I want to have a custom field that is applied to a post but contains no value so that I can setup a template post (portfolio item in this case) and simply duplicate it around but leave out values where the field does not apply, and of course if there is no value I do not want the related html to show. So, here is what I have:</p>
<pre><code><?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_Process', false);
if (!empty($fbb_CurrentMetaSet)){?>
<div id="fbb_ProjectData_Process" class="fbb_ProjectDataSetSection">
<div class="fbb_Title"><h5>Process:</h5></div>
<div>
<?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){
echo '<div>'.$fbb_MetaDataSingle.'</div>';
}?>
</div>
</div>
<?php } ?>
</code></pre>
<p>This code works if I simply check whether the custom field exists ( if ($fbb_CurrentMetaSet) ), but for some reason the !empty() method isn't working. Can anyone explain why? FYI I'm using the latest wordpress and the x-theme.</p>
<p>It may be that the larger context yields an explanation so below I've pasted the entire set of related code. My test code can be found in the last section. Once I've got it working I intend to duplicate it to the similar sections above it:</p>
<pre><code><div id="fbb_ProjectDataWrap">
<div id="fbb_ProjectData_Client" class="fbb_ProjectDataSetSection">
<div class="fbb_Title"><h5>Client:</h5></div>
<ul>
<?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_Client', false);?>
<?phpforeach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){
echo '<li>'.$fbb_MetaDataSingle.'</li>';
}
}?>
</ul>
</div>
<div id="fbb_ProjectData_Tools" class="fbb_ProjectDataSetSection">
<div class="fbb_Title"><h5>Tools:</h5></div>
<ul>
<?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_Tools', false); ?>
<?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){
echo '<li>'.$fbb_MetaDataSingle.'</li>';
} ?>
</ul>
</div>
<div id="fbb_ProjectData_About" class="fbb_ProjectDataSetSection">
<div class="fbb_Title"><h5>About:</h5></div>
<div>
<?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_AboutTheProject', false); ?>
<?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){
echo '<div>'.$fbb_MetaDataSingle.'</div>';
} ?>
</div>
</div>
<?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_Process', false);
if (!empty($fbb_CurrentMetaSet)){?>
<div id="fbb_ProjectData_Process" class="fbb_ProjectDataSetSection">
<div class="fbb_Title"><h5>Process:</h5></div>
<div>
<?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){
echo '<div>'.$fbb_MetaDataSingle.'</div>';
}?>
</div>
</div>
<?php } ?>
</div>
</code></pre>
| [
{
"answer_id": 220803,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 3,
"selected": true,
"text": "<p>Your third parameter of <code>get_post_meta()</code> is set to <code>false</code>. This means it will return ... | 2016/03/15 | [
"https://wordpress.stackexchange.com/questions/220802",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90658/"
] | I've found several other threads asking this same question, but for some reason I can't seem to make a solution work for me. For clarification, I want to have a custom field that is applied to a post but contains no value so that I can setup a template post (portfolio item in this case) and simply duplicate it around but leave out values where the field does not apply, and of course if there is no value I do not want the related html to show. So, here is what I have:
```
<?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_Process', false);
if (!empty($fbb_CurrentMetaSet)){?>
<div id="fbb_ProjectData_Process" class="fbb_ProjectDataSetSection">
<div class="fbb_Title"><h5>Process:</h5></div>
<div>
<?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){
echo '<div>'.$fbb_MetaDataSingle.'</div>';
}?>
</div>
</div>
<?php } ?>
```
This code works if I simply check whether the custom field exists ( if ($fbb\_CurrentMetaSet) ), but for some reason the !empty() method isn't working. Can anyone explain why? FYI I'm using the latest wordpress and the x-theme.
It may be that the larger context yields an explanation so below I've pasted the entire set of related code. My test code can be found in the last section. Once I've got it working I intend to duplicate it to the similar sections above it:
```
<div id="fbb_ProjectDataWrap">
<div id="fbb_ProjectData_Client" class="fbb_ProjectDataSetSection">
<div class="fbb_Title"><h5>Client:</h5></div>
<ul>
<?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_Client', false);?>
<?phpforeach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){
echo '<li>'.$fbb_MetaDataSingle.'</li>';
}
}?>
</ul>
</div>
<div id="fbb_ProjectData_Tools" class="fbb_ProjectDataSetSection">
<div class="fbb_Title"><h5>Tools:</h5></div>
<ul>
<?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_Tools', false); ?>
<?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){
echo '<li>'.$fbb_MetaDataSingle.'</li>';
} ?>
</ul>
</div>
<div id="fbb_ProjectData_About" class="fbb_ProjectDataSetSection">
<div class="fbb_Title"><h5>About:</h5></div>
<div>
<?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_AboutTheProject', false); ?>
<?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){
echo '<div>'.$fbb_MetaDataSingle.'</div>';
} ?>
</div>
</div>
<?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_Process', false);
if (!empty($fbb_CurrentMetaSet)){?>
<div id="fbb_ProjectData_Process" class="fbb_ProjectDataSetSection">
<div class="fbb_Title"><h5>Process:</h5></div>
<div>
<?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){
echo '<div>'.$fbb_MetaDataSingle.'</div>';
}?>
</div>
</div>
<?php } ?>
</div>
``` | Your third parameter of `get_post_meta()` is set to `false`. This means it will return an array. Even though you didn't set a value for this custom field, it will still record an array element in the DB - so `empty()` will return false.
Try switching to `true` for your third param. That should return an empty string. |
220,822 | <p>I am trying to create two additional <strong>add_meta_box</strong> <em>context</em> locations ('after_title' and 'after_editor') within posts.</p>
<p>This doesn't appear to do what I think it should. The meta box does appear on the page just within the normal <em>context</em>, not in the new defined <em>context</em> locations. Does anyone have any insight on this? </p>
<p>Thank you in advance for your time and consideration,</p>
<p>Tim</p>
<p><strong>REFERENCES:</strong></p>
<p><a href="http://adambrown.info/p/wp_hooks/hook/edit_form_after_editor?version=4.4&file=wp-admin/edit-form-advanced.php" rel="nofollow">http://adambrown.info/p/wp_hooks/hook/edit_form_after_editor?version=4.4&file=wp-admin/edit-form-advanced.php</a></p>
<p><a href="http://adambrown.info/p/wp_hooks/hook/edit_form_after_title?version=4.4&file=wp-admin/edit-form-advanced.php" rel="nofollow">http://adambrown.info/p/wp_hooks/hook/edit_form_after_title?version=4.4&file=wp-admin/edit-form-advanced.php</a></p>
<p><strong>ACTION HOOKS:</strong></p>
<pre><code> public function initialize_hooks() {
add_action( 'edit_form_after_editor', array( $this, 'add_after_editor_meta_boxes' ) );
add_action( 'edit_form_after_title', array( $this, 'add_after_title_meta_boxes' ) ) ;
}
/**
* Register meta box context location: after_editor
*
* @return null
**/
public function add_after_editor_meta_boxes() {
global $post, $wp_meta_boxes;
# Output the `after_editor` meta boxes:
do_meta_boxes( get_current_screen(), 'after_editor', $post );
}
/**
* Register meta box context location: after_title
*
* @return null
**/
public function add_after_title_meta_boxes() {
global $post, $wp_meta_boxes;
# Output the `after_title` meta boxes:
do_meta_boxes( get_current_screen(), 'after_title', $post );
}
</code></pre>
<p><strong>ADD META BOX:</strong></p>
<pre><code> /**
* The function responsible for creating the actual meta box.
*
* @since 0.2.0
**/
public function add_meta_box() {
add_meta_box(
'new-meta-box',
"New Meta Box",
array( $this, 'display_meta_box' ),
'after_editor',
'high',
'default'
);
</code></pre>
| [
{
"answer_id": 220825,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>these metaboxes appears as <em>normal</em> because <code>add_meta_box()</code> adds them in the loop of the other... | 2016/03/16 | [
"https://wordpress.stackexchange.com/questions/220822",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90671/"
] | I am trying to create two additional **add\_meta\_box** *context* locations ('after\_title' and 'after\_editor') within posts.
This doesn't appear to do what I think it should. The meta box does appear on the page just within the normal *context*, not in the new defined *context* locations. Does anyone have any insight on this?
Thank you in advance for your time and consideration,
Tim
**REFERENCES:**
<http://adambrown.info/p/wp_hooks/hook/edit_form_after_editor?version=4.4&file=wp-admin/edit-form-advanced.php>
<http://adambrown.info/p/wp_hooks/hook/edit_form_after_title?version=4.4&file=wp-admin/edit-form-advanced.php>
**ACTION HOOKS:**
```
public function initialize_hooks() {
add_action( 'edit_form_after_editor', array( $this, 'add_after_editor_meta_boxes' ) );
add_action( 'edit_form_after_title', array( $this, 'add_after_title_meta_boxes' ) ) ;
}
/**
* Register meta box context location: after_editor
*
* @return null
**/
public function add_after_editor_meta_boxes() {
global $post, $wp_meta_boxes;
# Output the `after_editor` meta boxes:
do_meta_boxes( get_current_screen(), 'after_editor', $post );
}
/**
* Register meta box context location: after_title
*
* @return null
**/
public function add_after_title_meta_boxes() {
global $post, $wp_meta_boxes;
# Output the `after_title` meta boxes:
do_meta_boxes( get_current_screen(), 'after_title', $post );
}
```
**ADD META BOX:**
```
/**
* The function responsible for creating the actual meta box.
*
* @since 0.2.0
**/
public function add_meta_box() {
add_meta_box(
'new-meta-box',
"New Meta Box",
array( $this, 'display_meta_box' ),
'after_editor',
'high',
'default'
);
``` | Here is a fully working dummy plugin to show how to add the new meta box contexts.
**STEPS:**
1. Create the plugin structure below and copy the code into *plugin-shell.php*.
2. Leave the style sheets empty.
3. Install and activate the plugin.
4. Navigate to the plugin from the admin menu item 'Plugin Shell | Add New'.
5. Directions on use are in the meta box.
I hope this is easy to follow. If you have any questions ask them in the comments.
Best,
Tim
**PLUGIN DIRECTORY STRUCTURE:**
```
plugin-shell > plugin-shell.php
plugin-shell > assets > css > admin > style.css
plugin-shell > assets > css > frontend > style.css
```
**PLUGIN CODE:**
```
<?php
/*
Plugin Name: PluginShell
Plugin URI: http://www.pluginshell.com/
Description: Aenean Vestibulum Risus Commodo Ullamcorper
Author: PluginShell
Author URI: http://www.pluginshell.com/
Version: 0.0.0
*/
mb_internal_encoding("UTF-8");
class Plugin_Shell {
/**
*
* CONSTRUCTOR
* Adds all actions and filters to the class
*
* @since 0.0.0
*
**/
function __construct() {
//Actions
add_action( 'init', array( &$this, 'plugin_shell_register_post_type' ) );
add_action( 'admin_init', array( &$this, 'plugin_shell_register_and_build_fields') );
add_action( 'wp_enqueue_scripts', array( &$this, 'plugin_shell_enqueue_style' ) );
add_action( 'admin_enqueue_scripts', array( &$this, 'plugin_shell_enqueue_options_style' ) );
add_action( 'admin_menu', array( &$this, 'plugin_shell_add_meta_boxes' ) );
add_action( 'admin_menu', array( &$this, 'plugin_shell_options_page' ) );
add_action( 'add_meta_boxes', array( &$this, 'plugin_shell_add_contextable_meta_box' ) );
add_action( 'save_post', array( &$this, 'plugin_shell_meta_box_save' ), 1, 2 );
add_action( 'edit_form_after_editor',array( &$this, 'add_after_editor_meta_boxes' ) );
add_action( 'edit_form_after_title', array( &$this, 'add_after_title_meta_boxes' ) );
}
/**
*
* PHP4 CONSTRUCTOR
* Calls __construct to create class
*
* @since 0.0.0
*
**/
function plugin_shell() {
$this->__construct();
}
/**
*
* LOAD CSS INTO THE WEBSITE'S FRONT END
*
* @since 0.0.0
*
**/
function plugin_shell_enqueue_style() {
wp_register_style( 'plugin-shell-style', plugin_dir_url( __FILE__ ) . 'assets/css/frontend/style.css' );
wp_enqueue_style( 'plugin-shell-style' );
}
/**
*
* LOAD CSS INTO THE ADMIN PAGE
*
* @since 0.0.0
*
**/
function plugin_shell_enqueue_options_style() {
wp_register_style( 'plugin-shell-options-style', plugin_dir_url( __FILE__ ) . 'assets/css/admin/style.css' );
wp_enqueue_style( 'plugin-shell-options-style' );
}
/**
* Register meta box context location: after_editor
*
* @return null
**/
function add_after_editor_meta_boxes() {
global $post, $wp_meta_boxes;
# Output the `after_editor` meta boxes:
do_meta_boxes( get_current_screen(), 'after_editor', $post );
}
/**
* Register meta box context location: after_title
*
* @return null
**/
function add_after_title_meta_boxes() {
global $post, $wp_meta_boxes;
# Output the `after_title` meta boxes:
do_meta_boxes( get_current_screen(), 'after_title', $post );
}
/**
*
* REGISTER CUSTOM POST TYPE: plugin_shell
*
* @since 0.0.0
*
**/
function plugin_shell_register_post_type() {
$options = get_option('plugin_shell_options');
register_post_type( 'plugin_shell',
array(
'labels' => array(
'name' => __( 'Plugin Shell' ),
'singular_name' => __( 'term' ),
'add_new' => __( 'Add New' ),
'add_new_item' => __( 'Add New Term' ),
'edit' => __( 'Edit' ),
'edit_item' => __( 'Edit Term' ),
'new_item' => __( 'New Term' ),
'view' => __( 'View Term' ),
'view_item' => __( 'View Term' ),
'search_items' => __( 'Search Term' ),
'not_found' => __( 'No Terms found' ),
'not_found_in_trash' => __( 'No Terms found in Trash' )
),
'public' => true,
'query_var' => true,
'show_in_menu' => true,
'show_ui' => true,
'menu_icon' => 'dashicons-book-alt',
'supports' => array( 'title', 'editor' ),
'rewrite' => array( 'slug' => $options['plugin_shell_slug_url_setting'] ? get_post($options['plugin_shell_slug_url_setting'])->post_name : 'plugin-shell', 'with_front' => false )
)
);
}
/*********************************************************
BEGIN: CONTEXTABLE META BOX
*********************************************************/
/**
*
* CALLS ALL OF THE FUNCTIONS RESPONSIBLE FOR RENDERING THE CONTEXTABLE PLUGIN SHELL META BOX
*
* @since 0.0.0
*
**/
function plugin_shell_add_contextable_meta_box() {
$this->_plugin_shell_add_contextable();
}
/**
*
* RENDERS THE META BOX
* Responsible for allowing the user to enter the plugin shell term.
*
* @since 0.0.0
*
**/
function _plugin_shell_add_contextable() {
add_meta_box(
'contextable-meta-box',
__( 'Extended Context Meta Box', 'pluginshell-textdomain' ),
array( &$this, '_display_contextable_meta_box' ),
'plugin_shell', // CHANGE TO DESIRED post-type
'after_title', // CHANGE THIS TO 'after_editor' || 'after_title' || OR OTHER VALID CONTEXT LOCATION
'default'
);
}
/**
*
* DISPLAYS THE CONTENTS OF THE PLUGIN SHELL TERM META BOX
*
* @since 0.0.0
*
**/
function _display_contextable_meta_box() {
printf( '<em>Move this meta box with the extended context values</em><br /><strong>after_title</strong><br /><strong>after_editor</strong><br /> <br />To dettach the meta box to the bottom of the editor open <em>assets/css/admin/style.css</em><br /> <br />Add the style:<br /><strong>#after_editor-sortables {</strong><br /><strong>
padding-top: 40px;</strong><br />
<strong>}</strong><br /> <br />See <strong>comments</strong> in <em>function _plugin_shell_add_contextable()</em>' );
}
/*********************************************************
END: CONTEXTABLE META BOX
*********************************************************/
/**
*
* CALLS ALL OF THE FUNCTIONS RESPONSIBLE FOR RENDERING THE PLUGIN SHELL META BOX
*
* @since 0.0.0
*
**/
function plugin_shell_add_meta_boxes() {
$this->_plugin_shell_add_meta_box();
}
/**
*
* RENDERS THE META BOX
* Responsible for allowing the user to enter the plugin shell term.
*
* @since 0.0.0
*
**/
function _plugin_shell_add_meta_box() {
add_meta_box( 'plugin_shell', __('Plugin Shell Extra Meta Box', 'pluginshell-textdomain'), array( &$this, '_plugin_shell_definiton_meta_box' ), 'plugin_shell', 'normal', 'high' );
}
/**
*
* DISPLAYS THE CONTENTS OF THE PLUGIN SHELL TERM META BOX
*
* @since 0.0.0
*
**/
function _plugin_shell_definiton_meta_box() {
?>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Nullam id dolor id nibh ultricies vehicula ut id elit. Donec id elit non mi porta gravida at eget metus.</p>
<p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Nullam quis risus eget urna mollis ornare vel eu leo. Vestibulum id ligula porta felis euismod semper. Curabitur blandit tempus porttitor. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.</p>
<p>Vestibulum id ligula porta felis euismod semper. Cras mattis consectetur purus sit amet fermentum. Vestibulum id ligula porta felis euismod semper. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
<?php
}
/**
*
* SAVES PLUGIN SHELL TERM
*
* @since 0.0.0
*
**/
function plugin_shell_meta_box_save( $post_id, $post ) {
$key = '_plugin_shell_term';
// verify the nonce
if ( !isset($_POST['_plugin_shell_nonce']) || !wp_verify_nonce( $_POST['_plugin_shell_nonce'], plugin_basename(__FILE__) ) )
return;
// don't try to save the data under autosave, ajax, or future post.
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
if ( defined('DOING_AJAX') && DOING_AJAX ) return;
if ( defined('DOING_CRON') && DOING_CRON ) return;
// is the user allowed to edit the URL?
if ( ! current_user_can( 'edit_posts' ) || $post->post_type != 'plugin_shell' )
return;
$value = isset( $_POST[$key] ) ? $_POST[$key] : '';
if ( $value ) {
// save/update
$my_post = array();
update_post_meta($post->ID, $key, $value);
} else {
// delete if blank
delete_post_meta($post->ID, $key);
}
}
/**
*
* ADMIN MENU AND
* SETTING FEILDS
*
**/
/**
*
* BUILD THE SETTINGS OPTIONS PAGE
*
* @since 0.0.0
*
**/
function _plugin_shell_build_options_page() {
?>
<div id="plugin-shell-options-wrap">
<div class="icon32" id="icon-tools"> <br /> </div>
<form method="post" action="options.php" enctype="multipart/form-data">
<?php settings_fields('plugin_shell_option_group'); ?>
<?php do_settings_sections(__FILE__); ?>
<p class="submit">
<input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />
</p>
</form>
<p><hr></p>
<p>* After editing the Slug the Permalinks Settings must be saved again.</p>
</div>
<?php
}
/**
*
* REGISTER SETTINGS AND FIELDS FOR OPTIONS PAGE
*
* @since 0.0.0
*
**/
function plugin_shell_register_and_build_fields() {
register_setting('plugin_shell_option_group', 'plugin_shell_option_mainpage', 'plugin_shell_validate_setting');
add_settings_section('plugin_shell_settings_general', 'Plugin Shell General Settings', array( &$this, '_plugin_shell_settings_fields'), __FILE__);
}
/**
*
* RENDER THE SLUG SELECTION SETTINGS FIELD
*
* @since 0.9.2
*
**/
function _plugin_shell_settings_fields() {
add_settings_field('slug', 'Mainpage:', array( &$this, '_plugin_shell_slug_url_setting'), __FILE__, 'plugin_shell_settings_general');
}
/**
*
* SANITIZE OPTIONS
*
* @since 0.0.0
*
**/
function plugin_shell_validate_setting($plugin_shell_options) {
return $plugin_shell_options;
}
/**
*
* GET DROPDOWN OF ALL PAGES FOR SLUG SETTING OPTION
*
* @since 0.0.0
*
**/
function _plugin_shell_slug_url_setting() {
$options = get_option('plugin_shell_options');
wp_dropdown_pages(array('name' => 'theme_options[plugin_shell_slug_url_setting]', 'selected' => $options['plugin_shell_slug_url_setting'] ));
}
/**
*
* ADD THE OPTIONS PAGE
*
* @since 0.0.0
*
**/
function plugin_shell_options_page() {
add_options_page('Plugin Shell', 'Plugin Shell', 'administrator', __FILE__, array( &$this, '_plugin_shell_build_options_page' ) );
}
};
/**
*
* INSTANTIATE CLASS plugin_shell
*
* @since 0.0.0
*
**/
$PluginShell = new plugin_shell;
?>
``` |
220,839 | <p>I'd like to create a <em>Multi-Level Associative Object</em> on <code>$.post</code> method using WordPress, in order to make my code cleaner. The problem is, I don't know how to get those values to manipulate on the back-end.</p>
<p>This is what I would like to do in <code>my_query.js</code> file, which contains and handles the <strong>AJAX</strong> request.</p>
<pre><code>$.post( MyAjax.ajaxurl, {
action: 'my_action',
someValue: {
one: 'Some Value One',
two: 'Some Value Two',
three: 'Some Value Three',
four: 'Some Value Four',
}
} );
</code></pre>
<p>And this is the current solution, which I <strong>DO NOT</strong> want to implement on my code.</p>
<pre><code>$.post( MyAjax.ajaxurl, {
action: 'my_action',
someValueOne: 'Some Value One',
someValueTwo: 'Some Value Two',
someValueThree: 'Some Value Three',
someValueFour: 'Some Value Four'
} );
</code></pre>
<p>The only way I could get those values on the back-end is by using the second option and doing this in the <code>.php</code> file.</p>
<pre><code>$someValue = array(
'one' => $_POST[ 'someValueOne' ],
'two' => $_POST[ 'someValueTwo' ],
'three' => $_POST[ 'someValueThree' ],
'four' => $_POST[ 'someValueFour' ]
);
echo $someValue[ 'one' ];
wp_die();
</code></pre>
<h1>But... What is the problem anyways?</h1>
<p>I <strong>DO NOT</strong> know how to have access to the <strong>AJAX Data Object</strong> inside my <code>.php</code> file by using the first example (which I'd like to), it only works by using the second one. How could I return the <code>someValue</code> object inside the <code>.php</code> file by using the first <strong>AJAX Request</strong> example?</p>
| [
{
"answer_id": 220846,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to pass a complex value, your best path is probably to jsonify it. Something like</p>\n\n<pre... | 2016/03/16 | [
"https://wordpress.stackexchange.com/questions/220839",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90683/"
] | I'd like to create a *Multi-Level Associative Object* on `$.post` method using WordPress, in order to make my code cleaner. The problem is, I don't know how to get those values to manipulate on the back-end.
This is what I would like to do in `my_query.js` file, which contains and handles the **AJAX** request.
```
$.post( MyAjax.ajaxurl, {
action: 'my_action',
someValue: {
one: 'Some Value One',
two: 'Some Value Two',
three: 'Some Value Three',
four: 'Some Value Four',
}
} );
```
And this is the current solution, which I **DO NOT** want to implement on my code.
```
$.post( MyAjax.ajaxurl, {
action: 'my_action',
someValueOne: 'Some Value One',
someValueTwo: 'Some Value Two',
someValueThree: 'Some Value Three',
someValueFour: 'Some Value Four'
} );
```
The only way I could get those values on the back-end is by using the second option and doing this in the `.php` file.
```
$someValue = array(
'one' => $_POST[ 'someValueOne' ],
'two' => $_POST[ 'someValueTwo' ],
'three' => $_POST[ 'someValueThree' ],
'four' => $_POST[ 'someValueFour' ]
);
echo $someValue[ 'one' ];
wp_die();
```
But... What is the problem anyways?
===================================
I **DO NOT** know how to have access to the **AJAX Data Object** inside my `.php` file by using the first example (which I'd like to), it only works by using the second one. How could I return the `someValue` object inside the `.php` file by using the first **AJAX Request** example? | Actually the solution I've found was very simple and didn't required much. For some reason I wasn't able to retrieve the data inside my **AJAX Function Request** on the Back-end.
JavaScript Code
---------------
As you can see below I defined the `someValue` property just the way I wanted, very clean and pretty.
```
$.post( MyAjax.ajaxurl, {
action: 'my_action',
someValue: {
one: 'Some Value One',
two: 'Some Value Two',
three: 'Some Value Three',
four: 'Some Value Four'
}
} );
```
PHP Code
--------
I must've forgot that I could associate all the properties defined inside the **Data Object** as an **Array** inside my Back-end *function*.
```
$someValue = array(
'one' => $_POST[ 'someValue' ][ 'one' ],
'two' => $_POST[ 'someValue' ][ 'two' ],
'three' => $_POST[ 'someValue' ][ 'three' ],
'four' => $_POST[ 'someValue' ][ 'four' ]
);
wp_die();
```
If you are unsure about what kind of data you're getting from the **AJAX Request**. I recommend you to do what our friend [@mmm](https://wordpress.stackexchange.com/users/74311/mmm) asked me, just `var_dump()` or `print_r()` the `$_POST` superglobal, then you'll see if you're actually getting something. |
220,873 | <p>I have a custom post type called 'programmes' that details seminar information. Using a form visitors to the site can signup to a specific 'programme', once they have completed the form a new user is created with the following user meta:</p>
<ul>
<li>programme_id - the post ID of the 'programme' registered on</li>
<li>programme_name - the title of the 'programme' registered on</li>
<li>programme_end_date - the date the 'programme' ends</li>
</ul>
<p>The 'programme' dates are often changed (due to venue availability etc) after users have already registered, as a result I need to update the programme_end_date user meta field when these changes happen.</p>
<p>I know it's going to be some combination of the <code>save_post</code> action along with <code>update_user_meta</code> and presumably a loop to check for all the users that have the specific updated 'programme' ID in the programme_id user meta field, but I can get my head round exactly how to do it. Any pointers would be excellent.</p>
| [
{
"answer_id": 220874,
"author": "Christine Cooper",
"author_id": 24875,
"author_profile": "https://wordpress.stackexchange.com/users/24875",
"pm_score": 0,
"selected": false,
"text": "<p>I am a bit unsure what your aim is but I can definitely get you on your feet. </p>\n\n<p>So you want... | 2016/03/16 | [
"https://wordpress.stackexchange.com/questions/220873",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51458/"
] | I have a custom post type called 'programmes' that details seminar information. Using a form visitors to the site can signup to a specific 'programme', once they have completed the form a new user is created with the following user meta:
* programme\_id - the post ID of the 'programme' registered on
* programme\_name - the title of the 'programme' registered on
* programme\_end\_date - the date the 'programme' ends
The 'programme' dates are often changed (due to venue availability etc) after users have already registered, as a result I need to update the programme\_end\_date user meta field when these changes happen.
I know it's going to be some combination of the `save_post` action along with `update_user_meta` and presumably a loop to check for all the users that have the specific updated 'programme' ID in the programme\_id user meta field, but I can get my head round exactly how to do it. Any pointers would be excellent. | You could query all the authors and loop through to update their dates. The below query pulls all users who have a `programme_id` of the current `post_id` and allocates an array of their IDs. You can then loop through to update whatever is necessary:
```
/** Save Custom Metaboxes **/
function save_custom_meta_boxes( $post_id, $post ) {
/**
* Your Testing conditions should go here to ensure
* That we're in the correct place and actually need to
* run this query. I suggest checking against post type
*/
$user_query = new WP_User_Query( array(
'meta_key' => 'programme_id',
'meta_value'=> $post_id,
'fields' => 'ID',
) );
if( ! empty( $user_query->results ) ) {
foreach( $user_query->results as $user_id ) {
update_user_meta( $user_id, 'programme_end_date', $_POST['some_data_here'] );
}
}
}
add_action( 'save_post', 'save_custom_meta_boxes', 10, 2 );
```
I kept it as simple as possible and if you have a *ton* of users this may not be optimal. |
220,907 | <p>Inside functions.php:</p>
<pre><code>add_action('init','my_action');
function my_action() {
if($dontknow) {
$passme = "yes";
} else {
$passme = "no";
}
}
</code></pre>
<p>Inside index.php of the current theme:</p>
<pre><code>echo $passme;
</code></pre>
<p>Is there a global to use for this purpose? Shall I use add_option (this is not a good idea for each request I guess)? Shall I use a custom global variable?</p>
<p>Is there a better / usual / standard way to do this?</p>
| [
{
"answer_id": 220908,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 2,
"selected": false,
"text": "<p>It really depends on the use case. Anything that writes to the DB is probably overkill. Globals are messy. Y... | 2016/03/16 | [
"https://wordpress.stackexchange.com/questions/220907",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12035/"
] | Inside functions.php:
```
add_action('init','my_action');
function my_action() {
if($dontknow) {
$passme = "yes";
} else {
$passme = "no";
}
}
```
Inside index.php of the current theme:
```
echo $passme;
```
Is there a global to use for this purpose? Shall I use add\_option (this is not a good idea for each request I guess)? Shall I use a custom global variable?
Is there a better / usual / standard way to do this? | Use an object to keep the value of the variable and a custom action to print it out.
In your theme’s `functions.php`, create a class, or better: move the class to a separate file.
```
class PassCheck
{
private $passed = 'no';
public function check()
{
if ( is_user_logged_in() )
$this->passed = 'yes';
}
public function print_pass()
{
echo $this->passed;
}
}
```
Then register the callbacks:
```
$passcheck = new PassCheck;
add_action( 'init', [ $passcheck, 'check' ] );
add_action( 'print_pass', [ $passcheck, 'print_pass' ] );
```
And in your template just call the proper action:
```
do_action( 'print_pass' );
```
This way, the template has no static dependency on the class: if you ever decide to remove the class or to register a completely different callback for that action, the theme will not break.
You can also move the `check()` callback to another action (like `wp_loaded`) or separate it out into another class later.
As a rule of thumb: templates (views) should be decoupled from business logic as much as possible. They shouldn't know class or function names. This isn't completely possible in WordPress’ architecture, but still a good regulative idea. |
220,911 | <p>Came across this function to check if a page exists by its slug and it works great</p>
<pre><code>function the_slug_exists($post_name) {
global $wpdb;
if($wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $post_name . "'", 'ARRAY_A')) {
return true;
} else {
return false;
}
</code></pre>
<p>}</p>
<p>but what i'm needing to do now is check if that exists, then output the title for that page, any help is appreciated.</p>
<p>so when i put this code on the page to lookup the slug:</p>
<pre><code><?php if (the_slug_exists('page-name')) {
echo '$post_title';
} ?>
</code></pre>
<p>everything is perfect other than the fact I need the function to output the title as well as lookup the slug, hopefully that makes more sense.</p>
| [
{
"answer_id": 220913,
"author": "Motaz M. El Shazly",
"author_id": 90216,
"author_profile": "https://wordpress.stackexchange.com/users/90216",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an update to the same code for you</p>\n\n<pre><code>function the_slug_exists($post_name) ... | 2016/03/17 | [
"https://wordpress.stackexchange.com/questions/220911",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90734/"
] | Came across this function to check if a page exists by its slug and it works great
```
function the_slug_exists($post_name) {
global $wpdb;
if($wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $post_name . "'", 'ARRAY_A')) {
return true;
} else {
return false;
}
```
}
but what i'm needing to do now is check if that exists, then output the title for that page, any help is appreciated.
so when i put this code on the page to lookup the slug:
```
<?php if (the_slug_exists('page-name')) {
echo '$post_title';
} ?>
```
everything is perfect other than the fact I need the function to output the title as well as lookup the slug, hopefully that makes more sense. | looking at MySQL query in the function it becomes clear that though it matches the post\_name and returns true or false. What you want to find is, if a page exists by its slug. So, in that case, the function you have chosen is wrong.
To get the page by title you can simply use:
```
$page = get_page_by_title( 'Sample Page' );
echo $page->title
```
Just in case if you want to get page by slug you can use following code:
```
function get_page_title_for_slug($page_slug) {
$page = get_page_by_path( $page_slug , OBJECT );
if ( isset($page) )
return $page->post_title;
else
return "Match not found";
}
```
You may call above function like below:
```
echo "<h1>" . get_page_title_for_slug("sample-page") . "</h1>";
```
Let me know if that helps. |
220,930 | <p>I'm using V2.0 and trying to create a post using the /posts endpoint.</p>
<p>Here's the payload being sent with my request:</p>
<pre><code>var payload =
{
title : "some title",
format : "link",
tags: ["tag1", "tag2"],
categories: ["newsletter"],
content: "http://someurl.com",
status: "publish"
};
</code></pre>
<p>The posts are successfully being created and all other fields are added except for the category and tags. </p>
<p>I see that both of them are supposed to take an array of strings. What am I missing here?</p>
<p>Also, I've tried adding both categories and tags that already exist on the site, and brand new ones. both don't work.</p>
| [
{
"answer_id": 221047,
"author": "Jevuska",
"author_id": 18731,
"author_profile": "https://wordpress.stackexchange.com/users/18731",
"pm_score": 2,
"selected": false,
"text": "<p>You are using name in your terms. In default, try to use the existing term id ( in your case, cat ID and tag ... | 2016/03/17 | [
"https://wordpress.stackexchange.com/questions/220930",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37198/"
] | I'm using V2.0 and trying to create a post using the /posts endpoint.
Here's the payload being sent with my request:
```
var payload =
{
title : "some title",
format : "link",
tags: ["tag1", "tag2"],
categories: ["newsletter"],
content: "http://someurl.com",
status: "publish"
};
```
The posts are successfully being created and all other fields are added except for the category and tags.
I see that both of them are supposed to take an array of strings. What am I missing here?
Also, I've tried adding both categories and tags that already exist on the site, and brand new ones. both don't work. | You are using name in your terms. In default, try to use the existing term id ( in your case, cat ID and tag ID ).
If you see <https://plugins.trac.wordpress.org/browser/rest-api/trunk/lib/endpoints/class-wp-rest-posts-controller.php#L918> they will handle your term with sanitize them into non-negative integer using `absint`. I hope this help.
Here example code to hook `rest_insert_{$this->post_type}` to create terms ( tags and categories ) and set into post after post ID created by [`wp_insert_post`](https://developer.wordpress.org/reference/functions/wp_insert_post/). Note: tags and category request are in name array as OP sample code.
```
add_action( 'rest_insert_post', 'wpse220930_rest_insert_post', 1, 3 );
function wpse220930_rest_insert_post( $post, $request, $update = true )
{
if ( ! empty( $request['tags'] ) )
wp_set_object_terms( $post->ID, $request['tags'], 'post_tag', $update );
if ( ! empty( $request['categories'] ) )
wp_set_object_terms( $post->ID, $request['categories'], 'category', $update );
}
``` |
220,935 | <p>I'm trying to create a custom plugin where I want create a table when the plugin gets activated. I have tried the following code but it is not creating the table in the database </p>
<pre><code>function create_plugin_database_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'sandbox';
$sql = "CREATE TABLE $table_name (
id mediumint(9) unsigned NOT NULL AUTO_INCREMENT,
title varchar(50) NOT NULL,
structure longtext NOT NULL,
author longtext NOT NULL,
PRIMARY KEY (id)
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
register_activation_hook( __FILE__, 'create_plugin_database_table' );
</code></pre>
| [
{
"answer_id": 220939,
"author": "dipika",
"author_id": 90752,
"author_profile": "https://wordpress.stackexchange.com/users/90752",
"pm_score": 5,
"selected": true,
"text": "<p>You have to include wpadmin/upgrade-functions.php file to create a table \nexample </p>\n\n<pre><code>function ... | 2016/03/17 | [
"https://wordpress.stackexchange.com/questions/220935",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90556/"
] | I'm trying to create a custom plugin where I want create a table when the plugin gets activated. I have tried the following code but it is not creating the table in the database
```
function create_plugin_database_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'sandbox';
$sql = "CREATE TABLE $table_name (
id mediumint(9) unsigned NOT NULL AUTO_INCREMENT,
title varchar(50) NOT NULL,
structure longtext NOT NULL,
author longtext NOT NULL,
PRIMARY KEY (id)
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
register_activation_hook( __FILE__, 'create_plugin_database_table' );
``` | You have to include wpadmin/upgrade-functions.php file to create a table
example
```
function create_plugin_database_table()
{
global $table_prefix, $wpdb;
$tblname = 'pin';
$wp_track_table = $table_prefix . "$tblname ";
#Check to see if the table exists already, if not, then create it
if($wpdb->get_var( "show tables like '$wp_track_table'" ) != $wp_track_table)
{
$sql = "CREATE TABLE `". $wp_track_table . "` ( ";
$sql .= " `id` int(11) NOT NULL auto_increment, ";
$sql .= " `pincode` int(128) NOT NULL, ";
$sql .= " PRIMARY KEY `order_id` (`id`) ";
$sql .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ";
require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
dbDelta($sql);
}
}
register_activation_hook( __FILE__, 'create_plugin_database_table' );
``` |
220,942 | <p>I'm able to get certain info about the active theme using <code>wp_get_theme()</code>. For example:</p>
<pre><code>$theme = wp_get_theme();
echo $theme->get( 'TextDomain' ); // twentyfifteen
echo $theme->get( 'ThemeURI' ); // https://wordpress.org/themes/twentyfifteen/
</code></pre>
<p>Is there a way to get the theme's slug? In this case it'd be <em>twentyfifteen</em>. Please note the theme's slug isn't always the same as the theme's text domain. I'd also like to avoid performing string replacement on the theme's URL if possible.</p>
<p>Ref: <a href="https://codex.wordpress.org/Function_Reference/wp_get_theme" rel="noreferrer">https://codex.wordpress.org/Function_Reference/wp_get_theme</a></p>
| [
{
"answer_id": 220953,
"author": "Bhavesh Nariya",
"author_id": 90760,
"author_profile": "https://wordpress.stackexchange.com/users/90760",
"pm_score": -1,
"selected": false,
"text": "<p>Yo can get it by <code>get_template_directory_uri()</code></p>\n"
},
{
"answer_id": 220954,
... | 2016/03/17 | [
"https://wordpress.stackexchange.com/questions/220942",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22599/"
] | I'm able to get certain info about the active theme using `wp_get_theme()`. For example:
```
$theme = wp_get_theme();
echo $theme->get( 'TextDomain' ); // twentyfifteen
echo $theme->get( 'ThemeURI' ); // https://wordpress.org/themes/twentyfifteen/
```
Is there a way to get the theme's slug? In this case it'd be *twentyfifteen*. Please note the theme's slug isn't always the same as the theme's text domain. I'd also like to avoid performing string replacement on the theme's URL if possible.
Ref: <https://codex.wordpress.org/Function_Reference/wp_get_theme> | I found the closest thing to the theme's slug is the theme's directory name. This can be found using `get_template()`:
```
echo get_template(); // twentyfifteen
```
Ref: <https://codex.wordpress.org/Function_Reference/get_template> |
220,944 | <p>Is it possible to use 2 shortcodes with the same
function and change only the post type in the function
depending on what shortcode it is?</p>
<p>For instance, when I use <code>all_faq</code> shortcode the post type should be Faq. When I use <code>wordpress_faq</code> then the post type should be <code>wp-Faq</code>. It works now but is it possible to make the code shorter in one function? Like if <code>all_faq</code> is used change post type to <code>faq</code> and else if <code>wordpress faq</code> is used change post type to <code>wp-faq</code>.</p>
<pre><code>//shortcode NORMAL FAQ
add_shortcode( 'all_faq', 'display_custom_post_type' );
function display_custom_post_type(){
$args = array(
'post_type' => 'Faq',
'post_status' => 'publish',
'posts_per_page' => '-1'
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
$string .= '<div class="container-fluid">';
$string .= '<div class="grid-container">';
while( $query->have_posts() ){
$query->the_post();
$string .= '<div class="sub-grid">';
$string .= '<div class="faq-shortcode-title">' . get_the_title() . '</div>';
$string .= '<div class="faq-shortcode-content">' . get_the_content() . '</div>';
$string .= '</div>';
}
$string .= '</div>';
$string .= '</div>';
}
wp_reset_postdata();
return $string;
}
//shortcode WORDPRESS FAQ
add_shortcode( 'wordpress_faq', 'display_wordpress_faq' );
function display_wordpress_faq(){
$args = array(
'post_type' => 'wp-Faq',
'post_status' => 'publish',
'posts_per_page' => '-1'
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
$string .= '<div class="container-fluid">';
$string .= '<div class="grid-container">';
while( $query->have_posts() ){
$query->the_post();
$string .= '<div class="sub-grid">';
$string .= '<div class="faq-shortcode-title">' . get_the_title() . '</div>';
$string .= '<div class="faq-shortcode-content">' . get_the_content() . '</div>';
$string .= '</div>';
}
$string .= '</div>';
$string .= '</div>';
}
wp_reset_postdata();
return $string;
}
</code></pre>
| [
{
"answer_id": 220945,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 1,
"selected": false,
"text": "<p>the callback function has 3 parameters and the 3rd is the tag name : </p>\n\n<pre><code>add_shortcode( 'all_faq',... | 2016/03/17 | [
"https://wordpress.stackexchange.com/questions/220944",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90756/"
] | Is it possible to use 2 shortcodes with the same
function and change only the post type in the function
depending on what shortcode it is?
For instance, when I use `all_faq` shortcode the post type should be Faq. When I use `wordpress_faq` then the post type should be `wp-Faq`. It works now but is it possible to make the code shorter in one function? Like if `all_faq` is used change post type to `faq` and else if `wordpress faq` is used change post type to `wp-faq`.
```
//shortcode NORMAL FAQ
add_shortcode( 'all_faq', 'display_custom_post_type' );
function display_custom_post_type(){
$args = array(
'post_type' => 'Faq',
'post_status' => 'publish',
'posts_per_page' => '-1'
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
$string .= '<div class="container-fluid">';
$string .= '<div class="grid-container">';
while( $query->have_posts() ){
$query->the_post();
$string .= '<div class="sub-grid">';
$string .= '<div class="faq-shortcode-title">' . get_the_title() . '</div>';
$string .= '<div class="faq-shortcode-content">' . get_the_content() . '</div>';
$string .= '</div>';
}
$string .= '</div>';
$string .= '</div>';
}
wp_reset_postdata();
return $string;
}
//shortcode WORDPRESS FAQ
add_shortcode( 'wordpress_faq', 'display_wordpress_faq' );
function display_wordpress_faq(){
$args = array(
'post_type' => 'wp-Faq',
'post_status' => 'publish',
'posts_per_page' => '-1'
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
$string .= '<div class="container-fluid">';
$string .= '<div class="grid-container">';
while( $query->have_posts() ){
$query->the_post();
$string .= '<div class="sub-grid">';
$string .= '<div class="faq-shortcode-title">' . get_the_title() . '</div>';
$string .= '<div class="faq-shortcode-content">' . get_the_content() . '</div>';
$string .= '</div>';
}
$string .= '</div>';
$string .= '</div>';
}
wp_reset_postdata();
return $string;
}
``` | the callback function has 3 parameters and the 3rd is the tag name :
```
add_shortcode( 'all_faq', 'commonFunction' );
add_shortcode( 'wordpress_faq', 'commonFunction' );
function commonFunction($attr, $content, $tag) {
$cores = [
"all_faq" => "Faq",
"wordpress_faq" => "wp-Faq",
];
$args = array(
'post_type' => $cores[$tag],
'post_status' => 'publish',
'posts_per_page' => '-1'
);
// ...
}
``` |
220,946 | <p>I am creating a WordPress plugin to help people protect their content from being copied. There are many plugins to protect content from being copied when JavaScript is on, but no plugins which protect content even when JS is off.</p>
<p>How can I add the following custom CSS code in a PHP file, to protect content copy via CSS, and then install the PHP file as a WordPress plugin?</p>
<pre><code>body {
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
}
</code></pre>
| [
{
"answer_id": 220948,
"author": "RiaanP",
"author_id": 66345,
"author_profile": "https://wordpress.stackexchange.com/users/66345",
"pm_score": 2,
"selected": true,
"text": "<p>I know this sounds like it's a good idea, but anyone can simply just view the source of the page and take whate... | 2016/03/17 | [
"https://wordpress.stackexchange.com/questions/220946",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90758/"
] | I am creating a WordPress plugin to help people protect their content from being copied. There are many plugins to protect content from being copied when JavaScript is on, but no plugins which protect content even when JS is off.
How can I add the following custom CSS code in a PHP file, to protect content copy via CSS, and then install the PHP file as a WordPress plugin?
```
body {
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
}
``` | I know this sounds like it's a good idea, but anyone can simply just view the source of the page and take whatever they want from there. They can also simply just hit Ctrl+S on their keyboard and save that entire page to their hard drive. They could even screenshot the page and use OCR technology to simply pull the text out if they wanted to. There's also Photoshop.
In my opinion, this is a waste of time.
With that out of the way, you could start by looking here: <https://codex.wordpress.org/Writing_a_Plugin>
That will cover a lot of important aspects of creating a plugin.
Then, to understand the most simplest form of a plugin, have a look at the hello.php (Hello Dolly plugin) file in your Wordpress' wp-content/plugins/ directory. Changing that will allow you to achieve what you want.
If you simply want to add this to your own site, you can do this in the footer:
```
<?php
echo '<style>body {
user-select: none;
-moz-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
}</style>';
?>
``` |
220,979 | <p>I'd like to include in my website a feature for users to only see posts from a certain author and a certain category. I'm able to do it separately but I can't seem to understand how to do it simultaneously.</p>
| [
{
"answer_id": 220980,
"author": "Aamer Shahzad",
"author_id": 42772,
"author_profile": "https://wordpress.stackexchange.com/users/42772",
"pm_score": -1,
"selected": false,
"text": "<p>use WP_Query() author parameters & category parameters</p>\n\n<p><a href=\"https://codex.wordpress... | 2016/03/17 | [
"https://wordpress.stackexchange.com/questions/220979",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90779/"
] | I'd like to include in my website a feature for users to only see posts from a certain author and a certain category. I'm able to do it separately but I can't seem to understand how to do it simultaneously. | If you want your visitors to choose the category and author you can use the code below.
If your loop in the template hasn't been changed you should get away with adding a query to the URL like so:
`http://website.com/post-title/?author=1&cat=1`
If you have a custom query you could do the following:
```
$author = $_GET['author']; //Get Author ID from query
$cat = $_GET['cat']; //Get Category ID from query string
$args = array(
'posts_per_page' => 10
);
if ( $author ) { //If $author found add it to custom query
$args['author'] = $author;
}
if ( $cat ) { //If $cat found add it to custom query
$args['cat'] = $cat;
}
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) : $custom_query->the_post();
//post stuff
endwhile;
else :
echo 'No posts found...';
endif;
```
Then in your template:
```
<form class="post-filters">
<select name="author">
<?php
$author_options = array(
'1' => 'Author 1',
'2' => 'Author 2',
'3' => 'Author 3'
);
foreach( $orderby_options as $value => $label ) {
echo '<option ' . selected( $_GET['author'], $value ) . ' value="' . $value . '">$label</option>';
}
?>
</select>
<select name="cat">
<?php
$cat_options = array(
'1' => 'Category 1',
'2' => 'Category 2'
);
foreach( $orderby_options as $value => $label ) {
echo '<option ' . selected( $_GET['cat'], $value ) . ' value="' . $value. '">$label</option>';
}
?>
</select>
<button type="submit">Show Posts</button>
</form>
```
Else (forced to specific author / category basically what talentedaamer said)
```
$args = array(
'posts_per_page' => 10,
'author' => 1, //Author ID
'cat' => 1 //Category ID
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) : $custom_query->the_post();
//post stuff
endwhile;
else :
echo 'No posts found...';
endif;
``` |
221,019 | <p>this is my source</p>
<pre><code> global $page;
$page_exists = $page->post_title;
$another_db_user = 'user';
$another_db_pass = 'pass';
$another_db_name = 'name';
$another_db_host = 'localhost';
$another_tb_prefix = 'wp_';
$mydb = new wpdb($another_db_user,$another_db_pass,$another_db_name,$another_db_host);
$mydb->set_prefix($another_tb_prefix);
$result = $mydb->get_results("
SELECT
m0.post_title,
m0.id,
m0.post_name,
m0.guid
FROM ( select post_title, id, guid, post_name from wp_posts where post_type = 'bio' AND post_status = 'publish' ) AS m0
");
foreach ($result as $value) {
if( $value->post_title == $page_exists ) {
}
else {
$my_access = Array(
'post_author' => '1',
'post_title' => ''.$value->post_title.'',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_name' => ''.$value->post_name.'',
'post_type' => 'page',
'post_parent' => '115822',
'page_template' => 'template-profile-info.php'
);
wp_insert_post($my_access);
}
}
</code></pre>
| [
{
"answer_id": 220980,
"author": "Aamer Shahzad",
"author_id": 42772,
"author_profile": "https://wordpress.stackexchange.com/users/42772",
"pm_score": -1,
"selected": false,
"text": "<p>use WP_Query() author parameters & category parameters</p>\n\n<p><a href=\"https://codex.wordpress... | 2016/03/18 | [
"https://wordpress.stackexchange.com/questions/221019",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86437/"
] | this is my source
```
global $page;
$page_exists = $page->post_title;
$another_db_user = 'user';
$another_db_pass = 'pass';
$another_db_name = 'name';
$another_db_host = 'localhost';
$another_tb_prefix = 'wp_';
$mydb = new wpdb($another_db_user,$another_db_pass,$another_db_name,$another_db_host);
$mydb->set_prefix($another_tb_prefix);
$result = $mydb->get_results("
SELECT
m0.post_title,
m0.id,
m0.post_name,
m0.guid
FROM ( select post_title, id, guid, post_name from wp_posts where post_type = 'bio' AND post_status = 'publish' ) AS m0
");
foreach ($result as $value) {
if( $value->post_title == $page_exists ) {
}
else {
$my_access = Array(
'post_author' => '1',
'post_title' => ''.$value->post_title.'',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_name' => ''.$value->post_name.'',
'post_type' => 'page',
'post_parent' => '115822',
'page_template' => 'template-profile-info.php'
);
wp_insert_post($my_access);
}
}
``` | If you want your visitors to choose the category and author you can use the code below.
If your loop in the template hasn't been changed you should get away with adding a query to the URL like so:
`http://website.com/post-title/?author=1&cat=1`
If you have a custom query you could do the following:
```
$author = $_GET['author']; //Get Author ID from query
$cat = $_GET['cat']; //Get Category ID from query string
$args = array(
'posts_per_page' => 10
);
if ( $author ) { //If $author found add it to custom query
$args['author'] = $author;
}
if ( $cat ) { //If $cat found add it to custom query
$args['cat'] = $cat;
}
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) : $custom_query->the_post();
//post stuff
endwhile;
else :
echo 'No posts found...';
endif;
```
Then in your template:
```
<form class="post-filters">
<select name="author">
<?php
$author_options = array(
'1' => 'Author 1',
'2' => 'Author 2',
'3' => 'Author 3'
);
foreach( $orderby_options as $value => $label ) {
echo '<option ' . selected( $_GET['author'], $value ) . ' value="' . $value . '">$label</option>';
}
?>
</select>
<select name="cat">
<?php
$cat_options = array(
'1' => 'Category 1',
'2' => 'Category 2'
);
foreach( $orderby_options as $value => $label ) {
echo '<option ' . selected( $_GET['cat'], $value ) . ' value="' . $value. '">$label</option>';
}
?>
</select>
<button type="submit">Show Posts</button>
</form>
```
Else (forced to specific author / category basically what talentedaamer said)
```
$args = array(
'posts_per_page' => 10,
'author' => 1, //Author ID
'cat' => 1 //Category ID
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) : $custom_query->the_post();
//post stuff
endwhile;
else :
echo 'No posts found...';
endif;
``` |
221,092 | <p>I use Bootstrap Modals plugin.
I have put the following code for modal in my page-contact.php.</p>
<pre><code><h2>Small Modal</h2>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>This is a small modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div> `
</code></pre>
<p>After clicking the button open modal, modal is appearing, and suddenly disappears. Weird is also that in the right top angle I have an x for closing the modal.
Can someone advice?</p>
<p>Regards, Ivana</p>
| [
{
"answer_id": 220980,
"author": "Aamer Shahzad",
"author_id": 42772,
"author_profile": "https://wordpress.stackexchange.com/users/42772",
"pm_score": -1,
"selected": false,
"text": "<p>use WP_Query() author parameters & category parameters</p>\n\n<p><a href=\"https://codex.wordpress... | 2016/03/18 | [
"https://wordpress.stackexchange.com/questions/221092",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90864/"
] | I use Bootstrap Modals plugin.
I have put the following code for modal in my page-contact.php.
```
<h2>Small Modal</h2>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>This is a small modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div> `
```
After clicking the button open modal, modal is appearing, and suddenly disappears. Weird is also that in the right top angle I have an x for closing the modal.
Can someone advice?
Regards, Ivana | If you want your visitors to choose the category and author you can use the code below.
If your loop in the template hasn't been changed you should get away with adding a query to the URL like so:
`http://website.com/post-title/?author=1&cat=1`
If you have a custom query you could do the following:
```
$author = $_GET['author']; //Get Author ID from query
$cat = $_GET['cat']; //Get Category ID from query string
$args = array(
'posts_per_page' => 10
);
if ( $author ) { //If $author found add it to custom query
$args['author'] = $author;
}
if ( $cat ) { //If $cat found add it to custom query
$args['cat'] = $cat;
}
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) : $custom_query->the_post();
//post stuff
endwhile;
else :
echo 'No posts found...';
endif;
```
Then in your template:
```
<form class="post-filters">
<select name="author">
<?php
$author_options = array(
'1' => 'Author 1',
'2' => 'Author 2',
'3' => 'Author 3'
);
foreach( $orderby_options as $value => $label ) {
echo '<option ' . selected( $_GET['author'], $value ) . ' value="' . $value . '">$label</option>';
}
?>
</select>
<select name="cat">
<?php
$cat_options = array(
'1' => 'Category 1',
'2' => 'Category 2'
);
foreach( $orderby_options as $value => $label ) {
echo '<option ' . selected( $_GET['cat'], $value ) . ' value="' . $value. '">$label</option>';
}
?>
</select>
<button type="submit">Show Posts</button>
</form>
```
Else (forced to specific author / category basically what talentedaamer said)
```
$args = array(
'posts_per_page' => 10,
'author' => 1, //Author ID
'cat' => 1 //Category ID
);
$custom_query = new WP_Query( $args );
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) : $custom_query->the_post();
//post stuff
endwhile;
else :
echo 'No posts found...';
endif;
``` |
221,108 | <p>Just finished moving my local Wordpress install to a live server. Imported my DB, and uploaded my core files to the new server. I also changed the siteurl and home fields in the wp_options table and added the new credentials to the new wp_config file.</p>
<p>Basically followed all the directions <a href="http://www.wpbeginner.com/wp-tutorials/how-to-move-wordpress-from-local-server-to-live-site/" rel="nofollow">here</a>.</p>
<p>The issue is my links are not working. They're redirecting I assume to the parent Wordpress index install.</p>
<p>Heres the file structure of my server</p>
<pre><code>-public_html (I have 4 add-on domains here)
----merchantsofdesign.ca (also a wordpress install)
--------clients
------------creditassur
----------------wordpress (core files are here)
</code></pre>
<p>Can I even have a parent folder and child folder both running Wordpress? </p>
<p>Thanks and hope that makes sense</p>
| [
{
"answer_id": 221111,
"author": "nicogaldo",
"author_id": 87880,
"author_profile": "https://wordpress.stackexchange.com/users/87880",
"pm_score": 4,
"selected": true,
"text": "<p>Go to settings » permalinks and save changes again.</p>\n"
},
{
"answer_id": 399291,
"author": "... | 2016/03/18 | [
"https://wordpress.stackexchange.com/questions/221108",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87989/"
] | Just finished moving my local Wordpress install to a live server. Imported my DB, and uploaded my core files to the new server. I also changed the siteurl and home fields in the wp\_options table and added the new credentials to the new wp\_config file.
Basically followed all the directions [here](http://www.wpbeginner.com/wp-tutorials/how-to-move-wordpress-from-local-server-to-live-site/).
The issue is my links are not working. They're redirecting I assume to the parent Wordpress index install.
Heres the file structure of my server
```
-public_html (I have 4 add-on domains here)
----merchantsofdesign.ca (also a wordpress install)
--------clients
------------creditassur
----------------wordpress (core files are here)
```
Can I even have a parent folder and child folder both running Wordpress?
Thanks and hope that makes sense | Go to settings » permalinks and save changes again. |
221,201 | <p>I would like to style two MediaElement players on the same page differently, and figured out the easier way to do this (compared to adding a completely new shortcode and enqueueing a new stylesheet, <a href="https://stackoverflow.com/questions/36111811/wordpress-4-4-media-player-different-css-stylesheet-depending-on-shortcode">which I couldn't get working either</a>) is to assign a different class to the audio shortcode of player A.</p>
<p><a href="https://developer.wordpress.org/reference/functions/wp_audio_shortcode/#source-code" rel="nofollow noreferrer">The WordPress code reference</a>
mentions adding a <code>class</code> attribute to the shortcode, <strong>but I can't get it to work.</strong> For instance, writing</p>
<pre><code>[audio class="miniplayer" mp3="http://localhost/working_url.mp3"][/audio]
</code></pre>
<p>does give me a working player, but I can't see "miniplayer" assigned to it anywhere in my Firefox console. So how do I assign a class to my shortcode properly?</p>
| [
{
"answer_id": 221203,
"author": "Jevuska",
"author_id": 18731,
"author_profile": "https://wordpress.stackexchange.com/users/18731",
"pm_score": 2,
"selected": false,
"text": "<p>There are no options to add <code>class</code> as parameter in shortcode <a href=\"https://codex.wordpress.or... | 2016/03/20 | [
"https://wordpress.stackexchange.com/questions/221201",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90910/"
] | I would like to style two MediaElement players on the same page differently, and figured out the easier way to do this (compared to adding a completely new shortcode and enqueueing a new stylesheet, [which I couldn't get working either](https://stackoverflow.com/questions/36111811/wordpress-4-4-media-player-different-css-stylesheet-depending-on-shortcode)) is to assign a different class to the audio shortcode of player A.
[The WordPress code reference](https://developer.wordpress.org/reference/functions/wp_audio_shortcode/#source-code)
mentions adding a `class` attribute to the shortcode, **but I can't get it to work.** For instance, writing
```
[audio class="miniplayer" mp3="http://localhost/working_url.mp3"][/audio]
```
does give me a working player, but I can't see "miniplayer" assigned to it anywhere in my Firefox console. So how do I assign a class to my shortcode properly? | WordPress allows least three options to manipulate the code to your needs.
1. Use a global variable that you increment with @Jevuska 's answer.
```
global $my_audio_player_count;
$my_audio_player_count = 0;
add_filter( 'wp_audio_shortcode_class', 'wpse221201_audio_shortcode_class', 1, 1 );
function wpse221201_audio_shortcode_class( $class ) {
global $my_audio_player_count;
$class .= ' my-audio-player-'.$my_audio_player_count++;
return $class;
}
```
2. Remove the built-in shortcode and add your own
```
remove_shortcode('audio');
add_shortcode('audio', 'my_audio_shortcode');
function my_audio_shortcode($args) {
//TODO: Insert your own version of the shortcode
}
```
3. Use the `wp_audio_shortcode_override` filter hook to override
```
add_filter('wp_audio_shortcode_override', 'my_audio_shortcode');
function my_audio_shortcode($args) {
//TODO: Insert your own version of the shortcode
}
``` |
221,202 | <p>I am starting a bit with the REST API. If I am not completly mislead, the <code>init</code> action hook is also executed when its a REST API request. Now, I want to execute some code only, when it is not a REST API request.</p>
<p>So I was looking for a command like <code>is_rest()</code> in order to do something like</p>
<pre><code><?php
if( ! is_rest() ) echo 'no-rest-request';
?>
</code></pre>
<p>But I couldn't find something like this. Is there a <code>is_rest()</code> out there?</p>
| [
{
"answer_id": 221289,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>It's a good point by @Milo, the <code>REST_REQUEST</code> constant is <a href=\"https://github.com/WordPress/W... | 2016/03/20 | [
"https://wordpress.stackexchange.com/questions/221202",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48693/"
] | I am starting a bit with the REST API. If I am not completly mislead, the `init` action hook is also executed when its a REST API request. Now, I want to execute some code only, when it is not a REST API request.
So I was looking for a command like `is_rest()` in order to do something like
```
<?php
if( ! is_rest() ) echo 'no-rest-request';
?>
```
But I couldn't find something like this. Is there a `is_rest()` out there? | It's a good point by @Milo, the `REST_REQUEST` constant is [defined](https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/rest-api.php#L135-L141) as `true`, within `rest_api_loaded()` if `$GLOBALS['wp']->query_vars['rest_route']` is non-empty.
It's [hooked](https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/default-filters.php#L364-L367) into `parse_request` via:
```
add_action( 'parse_request', 'rest_api_loaded' );
```
but `parse_request` fires later than `init` - See for example the Codex [here](http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request).
There was a suggestion (by Daniel Bachhuber) in ticket [#34373](https://core.trac.wordpress.org/ticket/34373) regarding `WP_Query::is_rest()`, but it was postponed/cancelled. |
221,240 | <p>I am developing a site that has an SSL certificate. I've activated wp-admin being conducted over https (using <code>define('FORCE_SSL_ADMIN', true);</code> in wp-config.php).</p>
<p>It's created a lot of issues using wp-admin.</p>
<p>1) Whilst doing things in wp-admin I'll regularly get a message saying the session has expired. As far as I can tell, this mostly happens when jumping from one admin page (url) to another page (url).</p>
<p>2) In Chrome I'll often see a little silver shield in the address bar indicating there are "unsafe scripts" the page is trying to load. I have to then manually tell it to load those scripts (I gather these are scripts wp-admin is trying to load over http, rather than https).</p>
<p>3) Some pages load fine with full HTTPS support (no mixed content) and the EV greenbar, etc. But other pages (in admin) will generate mixed content errors. It seems to be that when switching from a URL with mixed content errors over to one with no such errors (or vice versa) this is when the session expiration issues occurs (not 100% sure about that, but certainly looks that way).</p>
<p>On the front end I used whynopadlock.com to show me which resources were loading over HTTP when using HTTPS, and fixed them (it was simply images in posts, etc.). But since wp-admin requires one to log in, I don't have that option available.</p>
<p>I have two questions:</p>
<p>Q1) Is there a recommended way to get wp-admin to work correctly over SSL?</p>
<p>Q2) What's a recommended way to troubleshoot why wp-admin over SSL is so unstable? (meaning it works on some admin pages, breaks on others, and causes session expiration on others).</p>
<p>Thank you,</p>
<p>Jonathan</p>
| [
{
"answer_id": 221289,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>It's a good point by @Milo, the <code>REST_REQUEST</code> constant is <a href=\"https://github.com/WordPress/W... | 2016/03/21 | [
"https://wordpress.stackexchange.com/questions/221240",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11064/"
] | I am developing a site that has an SSL certificate. I've activated wp-admin being conducted over https (using `define('FORCE_SSL_ADMIN', true);` in wp-config.php).
It's created a lot of issues using wp-admin.
1) Whilst doing things in wp-admin I'll regularly get a message saying the session has expired. As far as I can tell, this mostly happens when jumping from one admin page (url) to another page (url).
2) In Chrome I'll often see a little silver shield in the address bar indicating there are "unsafe scripts" the page is trying to load. I have to then manually tell it to load those scripts (I gather these are scripts wp-admin is trying to load over http, rather than https).
3) Some pages load fine with full HTTPS support (no mixed content) and the EV greenbar, etc. But other pages (in admin) will generate mixed content errors. It seems to be that when switching from a URL with mixed content errors over to one with no such errors (or vice versa) this is when the session expiration issues occurs (not 100% sure about that, but certainly looks that way).
On the front end I used whynopadlock.com to show me which resources were loading over HTTP when using HTTPS, and fixed them (it was simply images in posts, etc.). But since wp-admin requires one to log in, I don't have that option available.
I have two questions:
Q1) Is there a recommended way to get wp-admin to work correctly over SSL?
Q2) What's a recommended way to troubleshoot why wp-admin over SSL is so unstable? (meaning it works on some admin pages, breaks on others, and causes session expiration on others).
Thank you,
Jonathan | It's a good point by @Milo, the `REST_REQUEST` constant is [defined](https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/rest-api.php#L135-L141) as `true`, within `rest_api_loaded()` if `$GLOBALS['wp']->query_vars['rest_route']` is non-empty.
It's [hooked](https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/default-filters.php#L364-L367) into `parse_request` via:
```
add_action( 'parse_request', 'rest_api_loaded' );
```
but `parse_request` fires later than `init` - See for example the Codex [here](http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request).
There was a suggestion (by Daniel Bachhuber) in ticket [#34373](https://core.trac.wordpress.org/ticket/34373) regarding `WP_Query::is_rest()`, but it was postponed/cancelled. |
221,250 | <p>I want to get category id by name so I am using <a href="https://codex.wordpress.org/Function_Reference/get_term_by" rel="nofollow">get_term_by</a></p>
<p>This is working fine when name is simple but when '&' is coming in term name it is not fetching category id.</p>
<p>e.g I have a term named "Website Development & Designing" under <strong>skills</strong> taxonomy and I am using following query to get its term id.</p>
<pre><code>$value = "Website Development & Designing"
get_term_by('name',$value,'skills');
</code></pre>
<p>but it does not return term object :(</p>
| [
{
"answer_id": 221289,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>It's a good point by @Milo, the <code>REST_REQUEST</code> constant is <a href=\"https://github.com/WordPress/W... | 2016/03/21 | [
"https://wordpress.stackexchange.com/questions/221250",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89273/"
] | I want to get category id by name so I am using [get\_term\_by](https://codex.wordpress.org/Function_Reference/get_term_by)
This is working fine when name is simple but when '&' is coming in term name it is not fetching category id.
e.g I have a term named "Website Development & Designing" under **skills** taxonomy and I am using following query to get its term id.
```
$value = "Website Development & Designing"
get_term_by('name',$value,'skills');
```
but it does not return term object :( | It's a good point by @Milo, the `REST_REQUEST` constant is [defined](https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/rest-api.php#L135-L141) as `true`, within `rest_api_loaded()` if `$GLOBALS['wp']->query_vars['rest_route']` is non-empty.
It's [hooked](https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/default-filters.php#L364-L367) into `parse_request` via:
```
add_action( 'parse_request', 'rest_api_loaded' );
```
but `parse_request` fires later than `init` - See for example the Codex [here](http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request).
There was a suggestion (by Daniel Bachhuber) in ticket [#34373](https://core.trac.wordpress.org/ticket/34373) regarding `WP_Query::is_rest()`, but it was postponed/cancelled. |