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
|
---|---|---|---|---|---|---|
225,323 |
<p>How can I set placeholder and second argument for that kind of sql prepare</p>
<pre><code>$wpdb->prepare(
"SELECT ID
FROM {$wpdb->posts}
WHERE post_type = 'attachment' AND ID IN ('".implode("','",$slideshow_imgs)."')
ORDER BY menu_order ASC"
);
</code></pre>
<p>ANSWER??</p>
<p>I do it that way and there is no debug error:</p>
<pre><code>$str = 'attachment';
$ids_img = implode("','",$slideshow_imgs);
$images = $wpdb->get_col($wpdb->prepare("SELECT ID FROM {$wpdb->posts}
WHERE post_type = %s AND ID IN (%d) ORDER BY menu_order ASC",$str,$ids_img));
</code></pre>
|
[
{
"answer_id": 225325,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 2,
"selected": false,
"text": "<p>Just use <code>%s</code> for string and <code>%d</code> for digit replacements. Do not forget to use the proper <code>esc_*()</code> functions (use full text search for <code>esc_</code> in the <a href=\"https://codex.wordpress.org/Function_Reference\" rel=\"nofollow\">function reference</a>).</p>\n\n<pre><code>global $wpdb;\n$wpdb->show_errors = true;\n$wpdb->suppress_errors = false;\n! defined( 'DIEONDBERROR' ) and define( 'DIEONDBERROR', true );\n\n$sql = <<<SQL\nSELECT ID \nFROM {$wpdb->posts} \n WHERE post_type = 'attachment' \n AND ID IN (%s) \n ORDER BY menu_order \n ASC\nSQL;\n\n# Make sure to `esc_*()` the arguments properly!\n$statement = $wpdb->prepare( $sql, implode( \"','\", $slideshow_imgs ) );\n# Example: Query β¦Β there are other methods as well:\n$wpdb->query( $statement );\n# DUMP the result and any possible errors\nvar_dump( $wpdb->last_query, $wpdb->last_error );\n</code></pre>\n"
},
{
"answer_id": 225327,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>An alternative, instead of writing SQL queries by hand, is to use e.g.:</p>\n\n<pre><code>$post_ids = get_posts( \n [\n 'fields' => 'ids',\n 'post_type' => 'attachments',\n 'orderby' => 'menu_order',\n 'order' => 'ASC',\n 'post__in' => wp_parse_id_list( $input_ids )\n ]\n);\n</code></pre>\n\n<p>where the handy <a href=\"https://developer.wordpress.org/reference/functions/wp_parse_id_list/\" rel=\"nofollow\">wp_parse_id_list()</a> core function is used to:</p>\n\n<blockquote>\n <p>Clean up an array, comma- or space-separated list of IDs.</p>\n</blockquote>\n\n<p>This generates the following SQL query:</p>\n\n<pre><code>SELECT wp_posts.ID \nFROM wp_posts \nWHERE 1=1 \n AND wp_posts.ID IN (1,2,3) \n AND wp_posts.post_type = 'attachments' \n AND (wp_posts.post_status = 'publish') \nORDER BY wp_posts.menu_order ASC \nLIMIT 0, 5\n</code></pre>\n\n<p>if <code>$input_ids = [1,2,3]</code>.</p>\n\n<p>But actually <a href=\"https://github.com/WordPress/WordPress/blob/dc5815146e1a42523445267317a7d8c4ecc21dd4/wp-includes/query.php#L2761-2763\" rel=\"nofollow\">this is how</a> the <code>post__in</code> input is sanitized in <code>WP_Query</code>:</p>\n\n<pre><code>$post__in = implode(',', array_map( 'absint', $q['post__in'] ));\n$where .= \" AND {$wpdb->posts}.ID IN ($post__in)\";\n</code></pre>\n\n<p>ps: I now remember posting a ticket <a href=\"https://core.trac.wordpress.org/ticket/34525\" rel=\"nofollow\">#34525</a> suggesting using <code>wp_parse_id_list()</code> within <code>WP_Query</code> ;-)</p>\n"
}
] |
2016/05/01
|
[
"https://wordpress.stackexchange.com/questions/225323",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71139/"
] |
How can I set placeholder and second argument for that kind of sql prepare
```
$wpdb->prepare(
"SELECT ID
FROM {$wpdb->posts}
WHERE post_type = 'attachment' AND ID IN ('".implode("','",$slideshow_imgs)."')
ORDER BY menu_order ASC"
);
```
ANSWER??
I do it that way and there is no debug error:
```
$str = 'attachment';
$ids_img = implode("','",$slideshow_imgs);
$images = $wpdb->get_col($wpdb->prepare("SELECT ID FROM {$wpdb->posts}
WHERE post_type = %s AND ID IN (%d) ORDER BY menu_order ASC",$str,$ids_img));
```
|
Just use `%s` for string and `%d` for digit replacements. Do not forget to use the proper `esc_*()` functions (use full text search for `esc_` in the [function reference](https://codex.wordpress.org/Function_Reference)).
```
global $wpdb;
$wpdb->show_errors = true;
$wpdb->suppress_errors = false;
! defined( 'DIEONDBERROR' ) and define( 'DIEONDBERROR', true );
$sql = <<<SQL
SELECT ID
FROM {$wpdb->posts}
WHERE post_type = 'attachment'
AND ID IN (%s)
ORDER BY menu_order
ASC
SQL;
# Make sure to `esc_*()` the arguments properly!
$statement = $wpdb->prepare( $sql, implode( "','", $slideshow_imgs ) );
# Example: Query β¦Β there are other methods as well:
$wpdb->query( $statement );
# DUMP the result and any possible errors
var_dump( $wpdb->last_query, $wpdb->last_error );
```
|
225,387 |
<p>I have decided to use a WooCommerce Storefront child theme called Galleria, when I have previously used the Storefront theme I have used the common remove_action to unhook the defaults and replaced with my own add_action.</p>
<p>However as Galleria is a child theme of Storefront, it has its own add_action in the file class-galleria-structure.php though the structure of the add_action seems different.</p>
<p>A typical add_action in storefront looks like this...</p>
<pre><code>add_action( 'storefront_header', 'storefront_site_branding', 20 );
</code></pre>
<p>I would usually use the following to unhook it in my functions.php file like so...</p>
<pre><code>remove_action( 'storefront_header', 'storefront_site_branding', 20 );
</code></pre>
<p>In the Galleria child theme the add_actions looks like this...</p>
<pre><code>add_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ), 1 );
add_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ), 6 );
</code></pre>
<p>So I assumed that by doing the following it would simply unhook them...</p>
<pre><code>remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ), 1 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ), 6 );
</code></pre>
<p>Having tried this in my functions.php file I find it has no effect.</p>
<p>I tried the suggestion of using 'init' but that failed, however after some further digging I realised that they have created these hooks as part of a larger function as seen here...</p>
<pre><code><?php
/**
* Galleria Structure
*
* @author WooThemes
* @since 2.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'Galleria_Structure' ) ) :
class Galleria_Structure {
/**
* Setup class.
*
* @since 1.0
*/
public function __construct() {
add_action( 'wp', array( $this, 'layout_adjustments' ) );
add_filter( 'storefront_products_per_page', array( $this, 'products_per_page' ) );
add_filter( 'woocommerce_breadcrumb_defaults', array( $this, 'change_breadcrumb_delimeter' ) );
}
/**
* Layout adjustments
* @return rearrange markup through add_action and remove_action
*/
public function layout_adjustments() {
if ( is_woocommerce_activated() ) {
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 5 );
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
add_action( 'woocommerce_before_shop_loop_item_title', array( 'Galleria_Structure', 'galleria_product_loop_title_price_wrap' ), 11 );
add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 2 );
add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 1 );
add_action( 'woocommerce_after_shop_loop_item_title', array( 'Galleria_Structure', 'galleria_product_loop_title_price_wrap_close' ), 2 );
add_action( 'woocommerce_before_subcategory_title', array( 'Galleria_Structure', 'galleria_product_loop_title_price_wrap' ), 11 );
add_action( 'woocommerce_after_subcategory_title', array( 'Galleria_Structure', 'galleria_product_loop_title_price_wrap_close' ), 2 );
remove_action( 'storefront_header', 'storefront_header_cart', 60 );
add_action( 'storefront_header', 'storefront_header_cart', 4 );
remove_action( 'storefront_header', 'storefront_product_search', 40 );
add_action( 'storefront_header', 'storefront_product_search', 3 );
}
remove_action( 'storefront_header', 'storefront_secondary_navigation', 30 );
add_action( 'storefront_header', 'storefront_secondary_navigation', 6 );
remove_action( 'storefront_header', 'storefront_site_branding', 20 );
add_action( 'storefront_header', 'storefront_site_branding', 5 );
remove_action( 'woocommerce_cart_collaterals', 'woocommerce_cross_sell_display' );
add_action( 'woocommerce_after_cart', 'woocommerce_cross_sell_display', 30 );
add_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper' ), 49 );
add_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper_close' ), 61 );
add_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ), 1 );
add_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ), 6 );
}
/**
* Product title wrapper
* @return void
*/
public static function galleria_product_loop_title_price_wrap() {
echo '<section class="g-product-title">';
}
/**
* Product title wrapper close
* @return void
*/
public static function galleria_product_loop_title_price_wrap_close() {
echo '</section>';
}
/**
* Primary navigation wrapper
* @return void
*/
public static function galleria_primary_navigation_wrapper() {
echo '<section class="g-primary-navigation">';
}
/**
* Primary navigation wrapper close
* @return void
*/
public static function galleria_primary_navigation_wrapper_close() {
echo '</section>';
}
/**
* Top bar wrapper
* @return void
*/
public static function galleria_top_bar_wrapper() {
echo '<section class="g-top-bar">';
}
/**
* Top bar wrapper close
* @return void
*/
public static function galleria_top_bar_wrapper_close() {
echo '</section>';
}
/**
* Products per page
* @return int products to display per page
*/
public function products_per_page( $per_page ) {
$per_page = 19;
return intval( $per_page );
}
public function change_breadcrumb_delimeter( $defaults ) {
$defaults['delimiter'] = ' <span>/</span> ';
return $defaults;
}
}
endif;
return new Galleria_Structure();
</code></pre>
<p>Can someone please point me in the right direction? I am at a loss as to why this is not working.</p>
|
[
{
"answer_id": 225390,
"author": "Antony Gibbs",
"author_id": 93359,
"author_profile": "https://wordpress.stackexchange.com/users/93359",
"pm_score": 2,
"selected": false,
"text": "<p>Sorry I can not comment yet on this site</p>\n\n<p>Could you be removing an action before it is registered?\nHave you tried wrapping this with an on init hook?\nPerhaps using remove_filter would be a better choice.</p>\n\n<pre><code>function my_init() {\n remove_filter( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ) );\n remove_filter( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ) );\n\n\n}\nadd_action( 'init', 'my_init', 100 );\n</code></pre>\n"
},
{
"answer_id": 230049,
"author": "Paul",
"author_id": 93357,
"author_profile": "https://wordpress.stackexchange.com/users/93357",
"pm_score": 3,
"selected": true,
"text": "<p>I eventually figured this out, I don't know exactly why, but it seems the issue was due to the original use of init, once i replaced it with 'wp_head' it worked correctly, my final code looked like this</p>\n\n<pre><code>function change_default_galleria_header() {\nremove_action( 'storefront_header', 'storefront_header_cart', 4 );\nremove_action( 'storefront_header', 'storefront_product_search', 3 );\nremove_action( 'storefront_header', 'storefront_secondary_navigation', 6 );\nremove_action( 'storefront_header', 'storefront_site_branding', 5 );\nremove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper' ), 49 );\nremove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper_close' ), 61 );\nremove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ), 1 );\nremove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ), 6 );\n\n}\nadd_action( 'wp_head', 'change_default_galleria_header' );\n</code></pre>\n\n<p>I do hope this information helps someone else in future.\nThanks</p>\n"
}
] |
2016/05/02
|
[
"https://wordpress.stackexchange.com/questions/225387",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93357/"
] |
I have decided to use a WooCommerce Storefront child theme called Galleria, when I have previously used the Storefront theme I have used the common remove\_action to unhook the defaults and replaced with my own add\_action.
However as Galleria is a child theme of Storefront, it has its own add\_action in the file class-galleria-structure.php though the structure of the add\_action seems different.
A typical add\_action in storefront looks like this...
```
add_action( 'storefront_header', 'storefront_site_branding', 20 );
```
I would usually use the following to unhook it in my functions.php file like so...
```
remove_action( 'storefront_header', 'storefront_site_branding', 20 );
```
In the Galleria child theme the add\_actions looks like this...
```
add_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ), 1 );
add_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ), 6 );
```
So I assumed that by doing the following it would simply unhook them...
```
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ), 1 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ), 6 );
```
Having tried this in my functions.php file I find it has no effect.
I tried the suggestion of using 'init' but that failed, however after some further digging I realised that they have created these hooks as part of a larger function as seen here...
```
<?php
/**
* Galleria Structure
*
* @author WooThemes
* @since 2.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'Galleria_Structure' ) ) :
class Galleria_Structure {
/**
* Setup class.
*
* @since 1.0
*/
public function __construct() {
add_action( 'wp', array( $this, 'layout_adjustments' ) );
add_filter( 'storefront_products_per_page', array( $this, 'products_per_page' ) );
add_filter( 'woocommerce_breadcrumb_defaults', array( $this, 'change_breadcrumb_delimeter' ) );
}
/**
* Layout adjustments
* @return rearrange markup through add_action and remove_action
*/
public function layout_adjustments() {
if ( is_woocommerce_activated() ) {
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 5 );
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
add_action( 'woocommerce_before_shop_loop_item_title', array( 'Galleria_Structure', 'galleria_product_loop_title_price_wrap' ), 11 );
add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 2 );
add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 1 );
add_action( 'woocommerce_after_shop_loop_item_title', array( 'Galleria_Structure', 'galleria_product_loop_title_price_wrap_close' ), 2 );
add_action( 'woocommerce_before_subcategory_title', array( 'Galleria_Structure', 'galleria_product_loop_title_price_wrap' ), 11 );
add_action( 'woocommerce_after_subcategory_title', array( 'Galleria_Structure', 'galleria_product_loop_title_price_wrap_close' ), 2 );
remove_action( 'storefront_header', 'storefront_header_cart', 60 );
add_action( 'storefront_header', 'storefront_header_cart', 4 );
remove_action( 'storefront_header', 'storefront_product_search', 40 );
add_action( 'storefront_header', 'storefront_product_search', 3 );
}
remove_action( 'storefront_header', 'storefront_secondary_navigation', 30 );
add_action( 'storefront_header', 'storefront_secondary_navigation', 6 );
remove_action( 'storefront_header', 'storefront_site_branding', 20 );
add_action( 'storefront_header', 'storefront_site_branding', 5 );
remove_action( 'woocommerce_cart_collaterals', 'woocommerce_cross_sell_display' );
add_action( 'woocommerce_after_cart', 'woocommerce_cross_sell_display', 30 );
add_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper' ), 49 );
add_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper_close' ), 61 );
add_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ), 1 );
add_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ), 6 );
}
/**
* Product title wrapper
* @return void
*/
public static function galleria_product_loop_title_price_wrap() {
echo '<section class="g-product-title">';
}
/**
* Product title wrapper close
* @return void
*/
public static function galleria_product_loop_title_price_wrap_close() {
echo '</section>';
}
/**
* Primary navigation wrapper
* @return void
*/
public static function galleria_primary_navigation_wrapper() {
echo '<section class="g-primary-navigation">';
}
/**
* Primary navigation wrapper close
* @return void
*/
public static function galleria_primary_navigation_wrapper_close() {
echo '</section>';
}
/**
* Top bar wrapper
* @return void
*/
public static function galleria_top_bar_wrapper() {
echo '<section class="g-top-bar">';
}
/**
* Top bar wrapper close
* @return void
*/
public static function galleria_top_bar_wrapper_close() {
echo '</section>';
}
/**
* Products per page
* @return int products to display per page
*/
public function products_per_page( $per_page ) {
$per_page = 19;
return intval( $per_page );
}
public function change_breadcrumb_delimeter( $defaults ) {
$defaults['delimiter'] = ' <span>/</span> ';
return $defaults;
}
}
endif;
return new Galleria_Structure();
```
Can someone please point me in the right direction? I am at a loss as to why this is not working.
|
I eventually figured this out, I don't know exactly why, but it seems the issue was due to the original use of init, once i replaced it with 'wp\_head' it worked correctly, my final code looked like this
```
function change_default_galleria_header() {
remove_action( 'storefront_header', 'storefront_header_cart', 4 );
remove_action( 'storefront_header', 'storefront_product_search', 3 );
remove_action( 'storefront_header', 'storefront_secondary_navigation', 6 );
remove_action( 'storefront_header', 'storefront_site_branding', 5 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper' ), 49 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper_close' ), 61 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ), 1 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ), 6 );
}
add_action( 'wp_head', 'change_default_galleria_header' );
```
I do hope this information helps someone else in future.
Thanks
|
225,392 |
<p>I have added a drop down to the WooCommerce Inventory Tab where the user can choose message to show in front end.</p>
<p>In functions.php:</p>
<pre><code>// Display Fields in Back End
add_action( 'woocommerce_product_options_inventory_product_data', 'woo_add_custom_status_fields' );
function woo_add_custom_status_fields() {
global $woocommerce, $post;
// Add Select to WooCommerce Inventory Tab in Back End
woocommerce_wp_select(
array(
'id' => 'productstatus_select',
'label' => __( 'Product Status', 'woocommerce' ),
'options' => array(
'Message one' => __( 'The message', 'woocommerce' ),
'Message two' => __( 'The message', 'woocommerce' ),
'Message three' => __( 'The message', 'woocommerce' ),
)
)
);
}
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_status_fields_save' );
function woo_add_custom_status_fields_save( $post_id ){
$woocommerce_select = $_POST['productstatus_select'];
if( !empty( $woocommerce_select ) )
update_post_meta( $post_id, 'productstatus_select', esc_attr( $woocommerce_select ) );
}
</code></pre>
<p>The selected value is retrieved with following code in woocommerce/single-product/meta.php</p>
<pre><code> <?php
// Display Custom Field Value in Front End
echo '<p class="productstatus">' . get_post_meta( $post->ID, 'productstatus_select', true ) .'</p>';
?>
</code></pre>
<p>Now Iβm wondering if there is any possibility to assign separate classes to the different selections so I can style the outputted code. For example make Message One red, Message Two green, etc in front end. Iβm not sure if the options should be arrays or if I need an additional function to achieve that. Any suggestions are highly appreciated.</p>
|
[
{
"answer_id": 225390,
"author": "Antony Gibbs",
"author_id": 93359,
"author_profile": "https://wordpress.stackexchange.com/users/93359",
"pm_score": 2,
"selected": false,
"text": "<p>Sorry I can not comment yet on this site</p>\n\n<p>Could you be removing an action before it is registered?\nHave you tried wrapping this with an on init hook?\nPerhaps using remove_filter would be a better choice.</p>\n\n<pre><code>function my_init() {\n remove_filter( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ) );\n remove_filter( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ) );\n\n\n}\nadd_action( 'init', 'my_init', 100 );\n</code></pre>\n"
},
{
"answer_id": 230049,
"author": "Paul",
"author_id": 93357,
"author_profile": "https://wordpress.stackexchange.com/users/93357",
"pm_score": 3,
"selected": true,
"text": "<p>I eventually figured this out, I don't know exactly why, but it seems the issue was due to the original use of init, once i replaced it with 'wp_head' it worked correctly, my final code looked like this</p>\n\n<pre><code>function change_default_galleria_header() {\nremove_action( 'storefront_header', 'storefront_header_cart', 4 );\nremove_action( 'storefront_header', 'storefront_product_search', 3 );\nremove_action( 'storefront_header', 'storefront_secondary_navigation', 6 );\nremove_action( 'storefront_header', 'storefront_site_branding', 5 );\nremove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper' ), 49 );\nremove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper_close' ), 61 );\nremove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ), 1 );\nremove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ), 6 );\n\n}\nadd_action( 'wp_head', 'change_default_galleria_header' );\n</code></pre>\n\n<p>I do hope this information helps someone else in future.\nThanks</p>\n"
}
] |
2016/05/02
|
[
"https://wordpress.stackexchange.com/questions/225392",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92735/"
] |
I have added a drop down to the WooCommerce Inventory Tab where the user can choose message to show in front end.
In functions.php:
```
// Display Fields in Back End
add_action( 'woocommerce_product_options_inventory_product_data', 'woo_add_custom_status_fields' );
function woo_add_custom_status_fields() {
global $woocommerce, $post;
// Add Select to WooCommerce Inventory Tab in Back End
woocommerce_wp_select(
array(
'id' => 'productstatus_select',
'label' => __( 'Product Status', 'woocommerce' ),
'options' => array(
'Message one' => __( 'The message', 'woocommerce' ),
'Message two' => __( 'The message', 'woocommerce' ),
'Message three' => __( 'The message', 'woocommerce' ),
)
)
);
}
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_status_fields_save' );
function woo_add_custom_status_fields_save( $post_id ){
$woocommerce_select = $_POST['productstatus_select'];
if( !empty( $woocommerce_select ) )
update_post_meta( $post_id, 'productstatus_select', esc_attr( $woocommerce_select ) );
}
```
The selected value is retrieved with following code in woocommerce/single-product/meta.php
```
<?php
// Display Custom Field Value in Front End
echo '<p class="productstatus">' . get_post_meta( $post->ID, 'productstatus_select', true ) .'</p>';
?>
```
Now Iβm wondering if there is any possibility to assign separate classes to the different selections so I can style the outputted code. For example make Message One red, Message Two green, etc in front end. Iβm not sure if the options should be arrays or if I need an additional function to achieve that. Any suggestions are highly appreciated.
|
I eventually figured this out, I don't know exactly why, but it seems the issue was due to the original use of init, once i replaced it with 'wp\_head' it worked correctly, my final code looked like this
```
function change_default_galleria_header() {
remove_action( 'storefront_header', 'storefront_header_cart', 4 );
remove_action( 'storefront_header', 'storefront_product_search', 3 );
remove_action( 'storefront_header', 'storefront_secondary_navigation', 6 );
remove_action( 'storefront_header', 'storefront_site_branding', 5 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper' ), 49 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper_close' ), 61 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ), 1 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ), 6 );
}
add_action( 'wp_head', 'change_default_galleria_header' );
```
I do hope this information helps someone else in future.
Thanks
|
225,431 |
<p>There is a code in <a href="https://codex.wordpress.org/Function_Reference/wp_add_inline_style" rel="nofollow">here</a> that dynamically load custom script. </p>
<pre><code><?php
function my_styles_method() {
wp_enqueue_style(
'custom-style',
get_template_directory_uri() . '/css/custom_script.css'
);
$color = get_theme_mod( 'my-custom-color' ); //E.g. #FF0000
$custom_css = "
.mycolor{
background: {$color};
}";
wp_add_inline_style( 'custom-style', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'my_styles_method' );
?>
</code></pre>
<p>I actually need to load only dynamic CSS part (<code>$custom_css</code>) and I don't need to load custom_script.css. According to <a href="https://make.wordpress.org/core/2011/12/12/use-wp_enqueue_scripts-not-wp_print_styles-to-enqueue-scripts-and-styles-for-the-frontend/" rel="nofollow">this document</a> hook like <code>wp_print_styles</code> is discouraged. What would be the best way to load inline style in WordPress. Maybe I am missing something.</p>
<p>I have rejected <code>wp_head</code> also from the same reason as <code>wp_print_styles</code>.</p>
|
[
{
"answer_id": 225390,
"author": "Antony Gibbs",
"author_id": 93359,
"author_profile": "https://wordpress.stackexchange.com/users/93359",
"pm_score": 2,
"selected": false,
"text": "<p>Sorry I can not comment yet on this site</p>\n\n<p>Could you be removing an action before it is registered?\nHave you tried wrapping this with an on init hook?\nPerhaps using remove_filter would be a better choice.</p>\n\n<pre><code>function my_init() {\n remove_filter( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ) );\n remove_filter( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ) );\n\n\n}\nadd_action( 'init', 'my_init', 100 );\n</code></pre>\n"
},
{
"answer_id": 230049,
"author": "Paul",
"author_id": 93357,
"author_profile": "https://wordpress.stackexchange.com/users/93357",
"pm_score": 3,
"selected": true,
"text": "<p>I eventually figured this out, I don't know exactly why, but it seems the issue was due to the original use of init, once i replaced it with 'wp_head' it worked correctly, my final code looked like this</p>\n\n<pre><code>function change_default_galleria_header() {\nremove_action( 'storefront_header', 'storefront_header_cart', 4 );\nremove_action( 'storefront_header', 'storefront_product_search', 3 );\nremove_action( 'storefront_header', 'storefront_secondary_navigation', 6 );\nremove_action( 'storefront_header', 'storefront_site_branding', 5 );\nremove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper' ), 49 );\nremove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper_close' ), 61 );\nremove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ), 1 );\nremove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ), 6 );\n\n}\nadd_action( 'wp_head', 'change_default_galleria_header' );\n</code></pre>\n\n<p>I do hope this information helps someone else in future.\nThanks</p>\n"
}
] |
2016/05/02
|
[
"https://wordpress.stackexchange.com/questions/225431",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88606/"
] |
There is a code in [here](https://codex.wordpress.org/Function_Reference/wp_add_inline_style) that dynamically load custom script.
```
<?php
function my_styles_method() {
wp_enqueue_style(
'custom-style',
get_template_directory_uri() . '/css/custom_script.css'
);
$color = get_theme_mod( 'my-custom-color' ); //E.g. #FF0000
$custom_css = "
.mycolor{
background: {$color};
}";
wp_add_inline_style( 'custom-style', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'my_styles_method' );
?>
```
I actually need to load only dynamic CSS part (`$custom_css`) and I don't need to load custom\_script.css. According to [this document](https://make.wordpress.org/core/2011/12/12/use-wp_enqueue_scripts-not-wp_print_styles-to-enqueue-scripts-and-styles-for-the-frontend/) hook like `wp_print_styles` is discouraged. What would be the best way to load inline style in WordPress. Maybe I am missing something.
I have rejected `wp_head` also from the same reason as `wp_print_styles`.
|
I eventually figured this out, I don't know exactly why, but it seems the issue was due to the original use of init, once i replaced it with 'wp\_head' it worked correctly, my final code looked like this
```
function change_default_galleria_header() {
remove_action( 'storefront_header', 'storefront_header_cart', 4 );
remove_action( 'storefront_header', 'storefront_product_search', 3 );
remove_action( 'storefront_header', 'storefront_secondary_navigation', 6 );
remove_action( 'storefront_header', 'storefront_site_branding', 5 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper' ), 49 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_primary_navigation_wrapper_close' ), 61 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper' ), 1 );
remove_action( 'storefront_header', array( 'Galleria_Structure', 'galleria_top_bar_wrapper_close' ), 6 );
}
add_action( 'wp_head', 'change_default_galleria_header' );
```
I do hope this information helps someone else in future.
Thanks
|
225,439 |
<p>I use the following code in my PHP script to automatically download the latest version of WordPress...</p>
<pre><code>$wordpress_zip_file_url = 'https://wordpress.org/latest.zip';
file_put_contents("wordpress.zip", file_get_contents($wordpress_zip_file_url));
</code></pre>
<p>Does this work for plugins the same way? For example, I'd like to automatically download the latest backupwordpress plugin version --> <a href="https://wordpress.org/plugins/backupwordpress/" rel="nofollow noreferrer">https://wordpress.org/plugins/backupwordpress/</a></p>
<p>Is there a generic link to download the latest version of a plugin?</p>
|
[
{
"answer_id": 225444,
"author": "sΔlΔ",
"author_id": 93062,
"author_profile": "https://wordpress.stackexchange.com/users/93062",
"pm_score": 0,
"selected": false,
"text": "<p>When you're doing a plugin update, in the process where it shows you all the steps, you can also see the plugin download url. Usually the last version can be always found there.</p>\n"
},
{
"answer_id": 225493,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 5,
"selected": true,
"text": "<p><code>https://downloads.wordpress.org/plugin/{plugin-name}.latest-stable.zip</code></p>\n\n<p>The structure should be the same for all WordPress.org plugins and the link you're looking for is:</p>\n\n<p><a href=\"https://downloads.wordpress.org/plugin/backupwordpress.latest-stable.zip\" rel=\"noreferrer\"><code>https://downloads.wordpress.org/plugin/backupwordpress.latest-stable.zip</code></a>.</p>\n\n<p>You can see an example <a href=\"https://wordpress.stackexchange.com/a/219429/84219\">here</a> on how this might be used.</p>\n\n<hr>\n\n<p>To <a href=\"http://wp-cli.org/commands/plugin/update/\" rel=\"noreferrer\">update plugins</a> through WP-CLI:</p>\n\n<pre><code>wp plugin update backupwordpress\n</code></pre>\n"
},
{
"answer_id": 225498,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": false,
"text": "<p>Sounds like what you are really after is <a href=\"http://wp-cli.org/\" rel=\"noreferrer\">wp-cli</a> which will let you write shell script that automate such tasks.</p>\n"
}
] |
2016/05/02
|
[
"https://wordpress.stackexchange.com/questions/225439",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93195/"
] |
I use the following code in my PHP script to automatically download the latest version of WordPress...
```
$wordpress_zip_file_url = 'https://wordpress.org/latest.zip';
file_put_contents("wordpress.zip", file_get_contents($wordpress_zip_file_url));
```
Does this work for plugins the same way? For example, I'd like to automatically download the latest backupwordpress plugin version --> <https://wordpress.org/plugins/backupwordpress/>
Is there a generic link to download the latest version of a plugin?
|
`https://downloads.wordpress.org/plugin/{plugin-name}.latest-stable.zip`
The structure should be the same for all WordPress.org plugins and the link you're looking for is:
[`https://downloads.wordpress.org/plugin/backupwordpress.latest-stable.zip`](https://downloads.wordpress.org/plugin/backupwordpress.latest-stable.zip).
You can see an example [here](https://wordpress.stackexchange.com/a/219429/84219) on how this might be used.
---
To [update plugins](http://wp-cli.org/commands/plugin/update/) through WP-CLI:
```
wp plugin update backupwordpress
```
|
225,449 |
<p>How do you change the user that gets the notification email announcement for new comments and comment moderation?</p>
<p>WordPress sends the notices to the <em>admin</em> user. My client is the editor of the site. I want the comment notices to get mailed to the editor user and not the <em>admin</em> user.</p>
<p>How do you do that?</p>
|
[
{
"answer_id": 225455,
"author": "N00b",
"author_id": 80903,
"author_profile": "https://wordpress.stackexchange.com/users/80903",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not aware of any hook that could change only the comment notification recipient... You would probably need to overwrite some kind of core function, but here's a small workaround you could use:</p>\n\n<p><strong>1.</strong> Disable the email feature from WordPress comments settings (<em>unless you want to get notified too</em>)</p>\n\n<p><strong>2.</strong> Send it manually using the <code>comment_post</code> action hook. Just add this function to <code>functions.php</code></p>\n\n<pre><code> add_filter( 'comment_post', 'comment_notification' );\n\n function comment_notification( $comment_ID, $comment_approved ) {\n\n // Send email only when it's not approved\n if( $comment_approved == 0 ) {\n\n $subject = 'subject here';\n $message = 'message here';\n\n wp_mail( '[email protected]' , $subject, $message );\n }\n }\n\n // Remove if statement if you want to recive email even if it doesn't require moderation\n\n`comment_post` is an action triggered immediately after a comment is inserted into the database.\n</code></pre>\n"
},
{
"answer_id": 227190,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": false,
"text": "<p>There's a great article explaining how to hook into 2 filters for this at <a href=\"https://web.archive.org/web/20200216075253/http://www.sourcexpress.com/customize-wordpress-comment-notification-emails/\" rel=\"noreferrer\">https://web.archive.org/web/20200216075253/http://www.sourcexpress.com/customize-wordpress-comment-notification-emails/</a></p>\n<p>To send your notifications to a particular user and not the site admin, try this for a user with ID 123:</p>\n<pre><code>function se_comment_moderation_recipients( $emails, $comment_id ) {\n $comment = get_comment( $comment_id );\n $post = get_post( $comment->comment_post_ID );\n $user = get_user_by( 'id', '123' );\n\n // Return only the post author if the author can modify.\n if ( user_can( $user->ID, 'edit_published_posts' ) && ! empty( $user->user_email ) ) {\n $emails = array( $user->user_email );\n }\n\n return $emails;\n}\nadd_filter( 'comment_moderation_recipients', 'se_comment_moderation_recipients', 11, 2 );\nadd_filter( 'comment_notification_recipients', 'se_comment_moderation_recipients', 11, 2 );\n</code></pre>\n"
},
{
"answer_id": 300635,
"author": "Ric Johnson",
"author_id": 141689,
"author_profile": "https://wordpress.stackexchange.com/users/141689",
"pm_score": -1,
"selected": false,
"text": "<p>There is a filter for changing the text of the comment moderation email:</p>\n\n<pre><code>function change_comment_email( $body, $comment_id ) {\n $body = preg_replace( \"/(A new )comment/s\", \"$1review\", $body );\n $body = preg_replace( \"/(Currently \\d+ )comment/s\", \"$1review\", $body );\n $body = preg_replace( \"/Comment:/\", \"Review:\", $body );\n return $body;\n}\n\nadd_filter( 'comment_moderation_text', 'change_comment_email', 20, 2 );\nadd_filter( 'comment_notification_text', 'change_comment_email', 20, 2 );\n</code></pre>\n"
},
{
"answer_id": 302561,
"author": "paulzag",
"author_id": 78598,
"author_profile": "https://wordpress.stackexchange.com/users/78598",
"pm_score": -1,
"selected": false,
"text": "<p>An alternative and more flexible way to the code hacking in the other answers is:</p>\n\n<p>Create an email address for the admin account of the blog. For example, <em>[email protected]</em> that is different from <em>[email protected]</em> and <em>[email protected]</em>.</p>\n\n<p>Option A: Forward site@ email to both the editor and the technical admin. I create site@ as an alias. This works if your editor is okay with receiving a copy of all the automatic email generated by the site. They just filter irrelevant email out or learn what actually happens with a site. This is good for small clients.</p>\n\n<p>Option B: Set up a mail filter for site@ to automatically forward emails about comment alerts to the editor and all email to the technical admin. The technical admin can then filter to archive/delete all comment alerts so they never appear in their inbox. This initial forward to editor@ can be done on the mail server using something like <a href=\"https://en.wikipedia.org/wiki/Procmail\" rel=\"nofollow noreferrer\">procmail</a>. Alternatively you can do it on your email client if it's up 24/7 or you can even use Gmail, <a href=\"https://en.wikipedia.org/wiki/Hotmail\" rel=\"nofollow noreferrer\">Hotmail</a>, etc. and manually build the filter.</p>\n"
},
{
"answer_id": 373918,
"author": "amitdutt24",
"author_id": 188153,
"author_profile": "https://wordpress.stackexchange.com/users/188153",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to send this email to multiple people then use below code in functions.php -</p>\n<pre><code>function se_comment_moderation_recipients( $emails, $comment_id ) {\n\n $comment = get_comment( $comment_id );\n $post = get_post( $comment->comment_post_ID );\n $emails = array();\n // $users = array(set of user IDs t whome you want to send mails)\n $users = array( 1, 16628, 15983 );\n foreach($users as $uid){\n $user = get_user_by( 'id', $uid );\n // Return emails of users .\n if ( !empty( $user->user_email ) ) {\n $emails[] = $user->user_email;\n }\n }\n $emails_list = array(implode(",",$emails));\n return $emails_list;\n\n}\nadd_filter( 'comment_moderation_recipients', 'se_comment_moderation_recipients', 11, 2 );\nadd_filter( 'comment_notification_recipients', 'se_comment_moderation_recipients', 11, 2 );\n\n</code></pre>\n"
}
] |
2016/05/03
|
[
"https://wordpress.stackexchange.com/questions/225449",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93385/"
] |
How do you change the user that gets the notification email announcement for new comments and comment moderation?
WordPress sends the notices to the *admin* user. My client is the editor of the site. I want the comment notices to get mailed to the editor user and not the *admin* user.
How do you do that?
|
There's a great article explaining how to hook into 2 filters for this at <https://web.archive.org/web/20200216075253/http://www.sourcexpress.com/customize-wordpress-comment-notification-emails/>
To send your notifications to a particular user and not the site admin, try this for a user with ID 123:
```
function se_comment_moderation_recipients( $emails, $comment_id ) {
$comment = get_comment( $comment_id );
$post = get_post( $comment->comment_post_ID );
$user = get_user_by( 'id', '123' );
// Return only the post author if the author can modify.
if ( user_can( $user->ID, 'edit_published_posts' ) && ! empty( $user->user_email ) ) {
$emails = array( $user->user_email );
}
return $emails;
}
add_filter( 'comment_moderation_recipients', 'se_comment_moderation_recipients', 11, 2 );
add_filter( 'comment_notification_recipients', 'se_comment_moderation_recipients', 11, 2 );
```
|
225,452 |
<p>I have a plugin used on a parent theme which uses shortcode. The plugin (shortcode) works on the parent theme but when I switch to child theme it no longer works. I've only added the child theme code in the child theme function... this is the only script currently in child function.</p>
<pre><code> function prpin_scripts_child_theme_scripts() {
wp_enqueue_style( 'parent-theme-css', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'prpin_scripts_child_theme_scripts' );
</code></pre>
<p>I thought functions like that are inherited from parent. Any advice?</p>
|
[
{
"answer_id": 225455,
"author": "N00b",
"author_id": 80903,
"author_profile": "https://wordpress.stackexchange.com/users/80903",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not aware of any hook that could change only the comment notification recipient... You would probably need to overwrite some kind of core function, but here's a small workaround you could use:</p>\n\n<p><strong>1.</strong> Disable the email feature from WordPress comments settings (<em>unless you want to get notified too</em>)</p>\n\n<p><strong>2.</strong> Send it manually using the <code>comment_post</code> action hook. Just add this function to <code>functions.php</code></p>\n\n<pre><code> add_filter( 'comment_post', 'comment_notification' );\n\n function comment_notification( $comment_ID, $comment_approved ) {\n\n // Send email only when it's not approved\n if( $comment_approved == 0 ) {\n\n $subject = 'subject here';\n $message = 'message here';\n\n wp_mail( '[email protected]' , $subject, $message );\n }\n }\n\n // Remove if statement if you want to recive email even if it doesn't require moderation\n\n`comment_post` is an action triggered immediately after a comment is inserted into the database.\n</code></pre>\n"
},
{
"answer_id": 227190,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": false,
"text": "<p>There's a great article explaining how to hook into 2 filters for this at <a href=\"https://web.archive.org/web/20200216075253/http://www.sourcexpress.com/customize-wordpress-comment-notification-emails/\" rel=\"noreferrer\">https://web.archive.org/web/20200216075253/http://www.sourcexpress.com/customize-wordpress-comment-notification-emails/</a></p>\n<p>To send your notifications to a particular user and not the site admin, try this for a user with ID 123:</p>\n<pre><code>function se_comment_moderation_recipients( $emails, $comment_id ) {\n $comment = get_comment( $comment_id );\n $post = get_post( $comment->comment_post_ID );\n $user = get_user_by( 'id', '123' );\n\n // Return only the post author if the author can modify.\n if ( user_can( $user->ID, 'edit_published_posts' ) && ! empty( $user->user_email ) ) {\n $emails = array( $user->user_email );\n }\n\n return $emails;\n}\nadd_filter( 'comment_moderation_recipients', 'se_comment_moderation_recipients', 11, 2 );\nadd_filter( 'comment_notification_recipients', 'se_comment_moderation_recipients', 11, 2 );\n</code></pre>\n"
},
{
"answer_id": 300635,
"author": "Ric Johnson",
"author_id": 141689,
"author_profile": "https://wordpress.stackexchange.com/users/141689",
"pm_score": -1,
"selected": false,
"text": "<p>There is a filter for changing the text of the comment moderation email:</p>\n\n<pre><code>function change_comment_email( $body, $comment_id ) {\n $body = preg_replace( \"/(A new )comment/s\", \"$1review\", $body );\n $body = preg_replace( \"/(Currently \\d+ )comment/s\", \"$1review\", $body );\n $body = preg_replace( \"/Comment:/\", \"Review:\", $body );\n return $body;\n}\n\nadd_filter( 'comment_moderation_text', 'change_comment_email', 20, 2 );\nadd_filter( 'comment_notification_text', 'change_comment_email', 20, 2 );\n</code></pre>\n"
},
{
"answer_id": 302561,
"author": "paulzag",
"author_id": 78598,
"author_profile": "https://wordpress.stackexchange.com/users/78598",
"pm_score": -1,
"selected": false,
"text": "<p>An alternative and more flexible way to the code hacking in the other answers is:</p>\n\n<p>Create an email address for the admin account of the blog. For example, <em>[email protected]</em> that is different from <em>[email protected]</em> and <em>[email protected]</em>.</p>\n\n<p>Option A: Forward site@ email to both the editor and the technical admin. I create site@ as an alias. This works if your editor is okay with receiving a copy of all the automatic email generated by the site. They just filter irrelevant email out or learn what actually happens with a site. This is good for small clients.</p>\n\n<p>Option B: Set up a mail filter for site@ to automatically forward emails about comment alerts to the editor and all email to the technical admin. The technical admin can then filter to archive/delete all comment alerts so they never appear in their inbox. This initial forward to editor@ can be done on the mail server using something like <a href=\"https://en.wikipedia.org/wiki/Procmail\" rel=\"nofollow noreferrer\">procmail</a>. Alternatively you can do it on your email client if it's up 24/7 or you can even use Gmail, <a href=\"https://en.wikipedia.org/wiki/Hotmail\" rel=\"nofollow noreferrer\">Hotmail</a>, etc. and manually build the filter.</p>\n"
},
{
"answer_id": 373918,
"author": "amitdutt24",
"author_id": 188153,
"author_profile": "https://wordpress.stackexchange.com/users/188153",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to send this email to multiple people then use below code in functions.php -</p>\n<pre><code>function se_comment_moderation_recipients( $emails, $comment_id ) {\n\n $comment = get_comment( $comment_id );\n $post = get_post( $comment->comment_post_ID );\n $emails = array();\n // $users = array(set of user IDs t whome you want to send mails)\n $users = array( 1, 16628, 15983 );\n foreach($users as $uid){\n $user = get_user_by( 'id', $uid );\n // Return emails of users .\n if ( !empty( $user->user_email ) ) {\n $emails[] = $user->user_email;\n }\n }\n $emails_list = array(implode(",",$emails));\n return $emails_list;\n\n}\nadd_filter( 'comment_moderation_recipients', 'se_comment_moderation_recipients', 11, 2 );\nadd_filter( 'comment_notification_recipients', 'se_comment_moderation_recipients', 11, 2 );\n\n</code></pre>\n"
}
] |
2016/05/03
|
[
"https://wordpress.stackexchange.com/questions/225452",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45462/"
] |
I have a plugin used on a parent theme which uses shortcode. The plugin (shortcode) works on the parent theme but when I switch to child theme it no longer works. I've only added the child theme code in the child theme function... this is the only script currently in child function.
```
function prpin_scripts_child_theme_scripts() {
wp_enqueue_style( 'parent-theme-css', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'prpin_scripts_child_theme_scripts' );
```
I thought functions like that are inherited from parent. Any advice?
|
There's a great article explaining how to hook into 2 filters for this at <https://web.archive.org/web/20200216075253/http://www.sourcexpress.com/customize-wordpress-comment-notification-emails/>
To send your notifications to a particular user and not the site admin, try this for a user with ID 123:
```
function se_comment_moderation_recipients( $emails, $comment_id ) {
$comment = get_comment( $comment_id );
$post = get_post( $comment->comment_post_ID );
$user = get_user_by( 'id', '123' );
// Return only the post author if the author can modify.
if ( user_can( $user->ID, 'edit_published_posts' ) && ! empty( $user->user_email ) ) {
$emails = array( $user->user_email );
}
return $emails;
}
add_filter( 'comment_moderation_recipients', 'se_comment_moderation_recipients', 11, 2 );
add_filter( 'comment_notification_recipients', 'se_comment_moderation_recipients', 11, 2 );
```
|
225,477 |
<p>Is there a way to wrap the submit button with html element while using wordpress function comment_form function.</p>
<pre><code>$comments_args = array(
'id_form' => 'main-contact-form',
'class_form' => 'contact-form',
'class_submit' => 'btn btn-primary btn-lg',
'label_submit' => 'Add Comment',
'fields' => $fields,
'title_reply_before' => '<div class="message_heading"><h4>',
'title_reply_after' => '</h4><p>Make sure you enter the(*)required information where indicate.HTML code is not allowed</p></div>',
'comment_field' => '
<div class="row"><div class="col-sm-7">
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
</div>'
);
comment_form($comments_args);
</code></pre>
<p>I want output code for submit button be like:</p>
<pre><code> <div class="form-group">
<input type="submit" class="btn btn-primary btn-lg>
</div>
</code></pre>
|
[
{
"answer_id": 225480,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 5,
"selected": true,
"text": "<p>We can use <a href=\"https://developer.wordpress.org/reference/functions/comment_form/\" rel=\"noreferrer\"><code>comment_form</code></a> function's <strong><code>submit_button</code></strong> parameter to change submit button HTML.</p>\n\n<p>Default HTML for <code>submit_button</code> is </p>\n\n<pre><code><input name=\"%1$s\" type=\"submit\" id=\"%2$s\" class=\"%3$s\" value=\"%4$s\" />\n</code></pre>\n\n<p>You can change your code like this.</p>\n\n<pre><code>$comments_args = array(\n ....\n\n 'submit_button' => '<div class=\"form-group\">\n <input name=\"%1$s\" type=\"submit\" id=\"%2$s\" class=\"%3$s\" value=\"%4$s\" />\n </div>'\n\n ....\n);\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>Regarding <code>%1$s</code> , <code>%2$s</code> and so on..</p>\n\n<p>If you take a look at <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/comment-template.php#L2111\" rel=\"noreferrer\">comment_form()</a> source, you can see that <a href=\"https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/comment-template.php#L2340\" rel=\"noreferrer\"><code>submit_button</code></a> is going through sprintf like this.</p>\n\n<pre><code>$submit_button = sprintf(\n $args['submit_button'],\n esc_attr( $args['name_submit'] ),\n esc_attr( $args['id_submit'] ),\n esc_attr( $args['class_submit'] ),\n esc_attr( $args['label_submit'] )\n);\n</code></pre>\n"
},
{
"answer_id": 225481,
"author": "Prasad Nevase",
"author_id": 62283,
"author_profile": "https://wordpress.stackexchange.com/users/62283",
"pm_score": 3,
"selected": false,
"text": "<p>Please place below code in your theme's functions.php file and it will wrap the submit button inside div:</p>\n\n<pre><code>// define the comment_form_submit_button callback\nfunction filter_comment_form_submit_button( $submit_button, $args ) {\n // make filter magic happen here...\n $submit_before = '<div class=\"form-group\">';\n $submit_after = '</div>';\n return $submit_before . $submit_button . $submit_after;\n};\n\n// add the filter\nadd_filter( 'comment_form_submit_button', 'filter_comment_form_submit_button', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 325335,
"author": "Bican M. Valeriu",
"author_id": 97285,
"author_profile": "https://wordpress.stackexchange.com/users/97285",
"pm_score": 0,
"selected": false,
"text": "<p>Even more updated answer: </p>\n\n<pre><code>'submit_field' => '<p class=\"form-submit\">%1$s %2$s</p>',\n</code></pre>\n"
}
] |
2016/05/03
|
[
"https://wordpress.stackexchange.com/questions/225477",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75767/"
] |
Is there a way to wrap the submit button with html element while using wordpress function comment\_form function.
```
$comments_args = array(
'id_form' => 'main-contact-form',
'class_form' => 'contact-form',
'class_submit' => 'btn btn-primary btn-lg',
'label_submit' => 'Add Comment',
'fields' => $fields,
'title_reply_before' => '<div class="message_heading"><h4>',
'title_reply_after' => '</h4><p>Make sure you enter the(*)required information where indicate.HTML code is not allowed</p></div>',
'comment_field' => '
<div class="row"><div class="col-sm-7">
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
</div>'
);
comment_form($comments_args);
```
I want output code for submit button be like:
```
<div class="form-group">
<input type="submit" class="btn btn-primary btn-lg>
</div>
```
|
We can use [`comment_form`](https://developer.wordpress.org/reference/functions/comment_form/) function's **`submit_button`** parameter to change submit button HTML.
Default HTML for `submit_button` is
```
<input name="%1$s" type="submit" id="%2$s" class="%3$s" value="%4$s" />
```
You can change your code like this.
```
$comments_args = array(
....
'submit_button' => '<div class="form-group">
<input name="%1$s" type="submit" id="%2$s" class="%3$s" value="%4$s" />
</div>'
....
);
```
**Update:**
Regarding `%1$s` , `%2$s` and so on..
If you take a look at [comment\_form()](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/comment-template.php#L2111) source, you can see that [`submit_button`](https://core.trac.wordpress.org/browser/tags/4.5/src/wp-includes/comment-template.php#L2340) is going through sprintf like this.
```
$submit_button = sprintf(
$args['submit_button'],
esc_attr( $args['name_submit'] ),
esc_attr( $args['id_submit'] ),
esc_attr( $args['class_submit'] ),
esc_attr( $args['label_submit'] )
);
```
|
225,499 |
<p>I have a custom sign up form in my Wordpress site which has confirmation email functionality for activating the account. For the confirmation step am keeping another DB table where am keeping the pending users info and when they are going with confirmation link then am copying the info from that table and adding to wp_users table. The issue is that i have First Name and Surname fields which info is being kept in another Wp table called wp_usermeta.</p>
<p>So my question is how i can insert the corresponding user firstname, surname when am adding the user to wp_users after confirmation like this</p>
<pre><code>$checkUserID = $wpdb->get_results("SELECT * FROM pendingwpusers WHERE token = '".$gettokenval."'");
$checkUserIDMain = $wpdb->query("SELECT * FROM store_users WHERE TrackNumber = '".$gettokenval."'");
//$aaaa = mysql_num_rows($checkUserIDMain);
//var_dump($checkUserIDMain);
if($checkUserID && $checkUserIDMain == 0){
foreach ($checkUserID as $checkUser) {
//if(wp_mail($to, $subject, $message, $header)){}else{mail($to, $subject, $message, $header);}
$hashedpass = md5($checkUser->user_pass);
$wpdb->insert(
'store_users',
array(
'user_login' => $checkUser->user_login,
'user_pass' => $hashedpass,
'user_nicename' => $checkUser->user_nicename,
'user_email' => $checkUser->user_email,
'user_registered' => $checkUser->user_registered,
'display_name' => $checkUser->display_name,
'TrackNumber' => $checkUser->token
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)
);
}
}
</code></pre>
|
[
{
"answer_id": 225507,
"author": "Refilon",
"author_id": 92815,
"author_profile": "https://wordpress.stackexchange.com/users/92815",
"pm_score": 5,
"selected": true,
"text": "<p>If you have the ID of the user you can do this:</p>\n<pre><code>wp_update_user([\n 'ID' => $userId, // this is the ID of the user you want to update.\n 'first_name' => $firstName,\n 'last_name' => $lastName,\n]);\n</code></pre>\n<p>You can update / insert almost all fields with this function. Take a look at the documentation <a href=\"https://developer.wordpress.org/reference/functions/wp_update_user/\" rel=\"noreferrer\">here</a></p>\n"
},
{
"answer_id": 301198,
"author": "jmullee",
"author_id": 142024,
"author_profile": "https://wordpress.stackexchange.com/users/142024",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar issue (woocommerce test users) and wrote this shell script:</p>\n\n<pre><code>#!/bin/bash\n\n# set for your local setup\nDB=wordpress ; DBUSER=wordpress ; DBPASS=wordpress\n\nINS_WPU=\"INSERT INTO wp_users (ID, user_login, user_pass, user_nicename, user_email, user_url, user_registered, user_activation_key, user_status, display_name) VALUES\"\nINS_WPM=\"INSERT INTO wp_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES\"\n# password is 'testuser'\nTESTUSERPASS='$P$BptzXm87Y8pxffjyy4Ur0ANs8uqW7J.'\n\nfunction ins_test_user(){\n # 2 parameters : firstname, lastname\n NAM1=\"$1\"\n NAM2=\"$2\"\n\n # get the last unused wp_users ID\n SQL=\"select 1+max(ID) from wp_users into @wpuid;\\n\"\n # get the last unused wp_usermeta ID\n SQL=\"${SQL}select 1+max(umeta_id) from wp_usermeta into @wpmid;\\n\"\n\n # insert wp_users record\n SQL=\"${SQL}${INS_WPU} (@wpuid, '${NAM1}${NAM2}','${TESTUSERPASS}','${NAM1} ${NAM2}','${NAM1}.${NAM2}@example.org','http://${NAM1}.${NAM2}.example.com',now(),'',0,'test user ${CODE}');\\n\"\n\n # insert wp_usermeta records\n SQL=\"${SQL}${INS_WPM}(0+@wpmid,@wpuid,'billing_phone','');\\n\"\n SQL=\"${SQL}${INS_WPM}(1+@wpmid,@wpuid,'nickname','${NAM1} ${NAM2}');\\n\"\n SQL=\"${SQL}${INS_WPM}(2+@wpmid,@wpuid,'first_name','${NAM1}');\\n\"\n SQL=\"${SQL}${INS_WPM}(3+@wpmid,@wpuid,'last_name','${NAM2}');\\n\"\n SQL=\"${SQL}${INS_WPM}(4+@wpmid,@wpuid,'description','');\\n\"\n SQL=\"${SQL}${INS_WPM}(5+@wpmid,@wpuid,'rich_editing','true');\\n\"\n SQL=\"${SQL}${INS_WPM}(6+@wpmid,@wpuid,'syntax_highlighting','true');\\n\"\n SQL=\"${SQL}${INS_WPM}(7+@wpmid,@wpuid,'comment_shortcuts','false');\\n\"\n SQL=\"${SQL}${INS_WPM}(8+@wpmid,@wpuid,'admin_color','fresh');\\n\"\n SQL=\"${SQL}${INS_WPM}(9+@wpmid,@wpuid,'use_ssl','0');\\n\"\n SQL=\"${SQL}${INS_WPM}(10+@wpmid,@wpuid,'show_admin_bar_front','true');\\n\"\n SQL=\"${SQL}${INS_WPM}(11+@wpmid,@wpuid,'locale','');\\n\"\n SQL=\"${SQL}${INS_WPM}(12+@wpmid,@wpuid,'wp_capabilities','a:1:{s:8:\\\"customer\\\";b:1;}');\\n\"\n SQL=\"${SQL}${INS_WPM}(13+@wpmid,@wpuid,'wp_user_level','0');\\n\"\n SQL=\"${SQL}${INS_WPM}(14+@wpmid,@wpuid,'dismissed_wp_pointers','');\\n\"\n SQL=\"${SQL}${INS_WPM}(15+@wpmid,@wpuid,'billing_first_name','${NAM1}');\\n\"\n SQL=\"${SQL}${INS_WPM}(16+@wpmid,@wpuid,'billing_last_name','${NAM2}');\\n\"\n SQL=\"${SQL}${INS_WPM}(17+@wpmid,@wpuid,'billing_company','');\\n\"\n SQL=\"${SQL}${INS_WPM}(18+@wpmid,@wpuid,'billing_address_1','somewhere');\\n\"\n SQL=\"${SQL}${INS_WPM}(19+@wpmid,@wpuid,'billing_address_2','la la land');\\n\"\n SQL=\"${SQL}${INS_WPM}(20+@wpmid,@wpuid,'billing_city','X');\\n\"\n SQL=\"${SQL}${INS_WPM}(21+@wpmid,@wpuid,'billing_postcode','90210');\\n\"\n SQL=\"${SQL}${INS_WPM}(22+@wpmid,@wpuid,'billing_country','AF');\\n\"\n SQL=\"${SQL}${INS_WPM}(23+@wpmid,@wpuid,'billing_state','');\\n\"\n SQL=\"${SQL}${INS_WPM}(24+@wpmid,@wpuid,'billing_email','${NAM1}.${NAM2}@example.org');\\n\"\n SQL=\"${SQL}${INS_WPM}(25+@wpmid,@wpuid,'shipping_first_name','');\\n\"\n SQL=\"${SQL}${INS_WPM}(26+@wpmid,@wpuid,'shipping_last_name','');\\n\"\n SQL=\"${SQL}${INS_WPM}(27+@wpmid,@wpuid,'shipping_company','');\\n\"\n SQL=\"${SQL}${INS_WPM}(28+@wpmid,@wpuid,'shipping_address_1','');\\n\"\n SQL=\"${SQL}${INS_WPM}(29+@wpmid,@wpuid,'shipping_address_2','');\\n\"\n SQL=\"${SQL}${INS_WPM}(30+@wpmid,@wpuid,'shipping_city','');\\n\"\n SQL=\"${SQL}${INS_WPM}(31+@wpmid,@wpuid,'shipping_postcode','');\\n\"\n SQL=\"${SQL}${INS_WPM}(32+@wpmid,@wpuid,'shipping_country','');\\n\"\n SQL=\"${SQL}${INS_WPM}(33+@wpmid,@wpuid,'shipping_state','');\\n\"\n\n # commit after each user\n SQL=\"${SQL}commit;\\n\"\n\n echo -e \"$SQL\"\n }\n\n{\necho \"set autocommit=off;\\n\"\n\nins_test_user jane doe\nins_test_user joe bloggs\nins_test_user architeuthis dux\nins_test_user ftagn fnord\nins_test_user pete brick\nins_test_user kaiser soze\n\necho \"set autocommit=on;\\n\"\n} | mysql -D $DB -u $DBUSER --password=\"$DBPASS\"\n</code></pre>\n"
}
] |
2016/05/03
|
[
"https://wordpress.stackexchange.com/questions/225499",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77773/"
] |
I have a custom sign up form in my Wordpress site which has confirmation email functionality for activating the account. For the confirmation step am keeping another DB table where am keeping the pending users info and when they are going with confirmation link then am copying the info from that table and adding to wp\_users table. The issue is that i have First Name and Surname fields which info is being kept in another Wp table called wp\_usermeta.
So my question is how i can insert the corresponding user firstname, surname when am adding the user to wp\_users after confirmation like this
```
$checkUserID = $wpdb->get_results("SELECT * FROM pendingwpusers WHERE token = '".$gettokenval."'");
$checkUserIDMain = $wpdb->query("SELECT * FROM store_users WHERE TrackNumber = '".$gettokenval."'");
//$aaaa = mysql_num_rows($checkUserIDMain);
//var_dump($checkUserIDMain);
if($checkUserID && $checkUserIDMain == 0){
foreach ($checkUserID as $checkUser) {
//if(wp_mail($to, $subject, $message, $header)){}else{mail($to, $subject, $message, $header);}
$hashedpass = md5($checkUser->user_pass);
$wpdb->insert(
'store_users',
array(
'user_login' => $checkUser->user_login,
'user_pass' => $hashedpass,
'user_nicename' => $checkUser->user_nicename,
'user_email' => $checkUser->user_email,
'user_registered' => $checkUser->user_registered,
'display_name' => $checkUser->display_name,
'TrackNumber' => $checkUser->token
),
array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)
);
}
}
```
|
If you have the ID of the user you can do this:
```
wp_update_user([
'ID' => $userId, // this is the ID of the user you want to update.
'first_name' => $firstName,
'last_name' => $lastName,
]);
```
You can update / insert almost all fields with this function. Take a look at the documentation [here](https://developer.wordpress.org/reference/functions/wp_update_user/)
|
225,527 |
<p>I generally use the <a href="https://wordpress.org/plugins/intuitive-custom-post-order" rel="nofollow">Intuitive Custom Post Order</a> plugin for any WordPress sites I work with so clients can order their posts visually.</p>
<p>For this project, I'm using WordPress as an admin panel and consuming it's data with an Ember.js front-end.</p>
<p>(using wp-api V.2) The re-ordered order doesn't show in the JSON and I'm guessing the plugin stores the new order in an in-between piece of PHP.</p>
<p>Besides manually changing the date of each post, what are my options to allow my client an intuitive way to re-order posts in a way that persists?</p>
|
[
{
"answer_id": 225692,
"author": "Ahed Eid",
"author_id": 81934,
"author_profile": "https://wordpress.stackexchange.com/users/81934",
"pm_score": 0,
"selected": false,
"text": "<p>Ordering posts with menu_order as orderby parameter will give invalid parameter error e.g. </p>\n\n<p><code>http://example.com/wp-json/wp/v2/posts?orderby=menu_order&order=asc</code></p>\n\n<p><code>Invalid parameter(s): orderby (orderby is not one of date, id, include, title, slug)</code></p>\n\n<p>At this time there's no filter to add another orderby option\n<a href=\"https://github.com/WP-API/WP-API/blob/2.0-beta13/lib/endpoints/class-wp-rest-posts-controller.php#L1666\" rel=\"nofollow\">https://github.com/WP-API/WP-API/blob/2.0-beta13/lib/endpoints/class-wp-rest-posts-controller.php#L1666</a></p>\n\n<p>you should hook at <code>posts_clauses</code> for example</p>\n\n<pre><code>/**\n * Class Custom_Rest\n * @author \n */\nclass Custom_Rest\n{\n /**\n * init \n * Add Rest Hooks\n *\n * @return void\n * @author \n */\n public static function init()\n {\n add_filter( 'posts_clauses' , 'Custom_Rest::orderby' );\n }\n\n\n /**\n * orderby\n * Order posts by menu_order\n *\n * @return void\n * @author \n */\n public static function orderby($v) {\n\n if ( $GLOBALS['wp']->query_vars['rest_route'] == '/wp/v2/posts' ) {\n // old value is \"wp_posts.post_date DESC\"\n $v['orderby'] = str_replace('post_date', 'menu_order', $v['orderby']);\n return $v;\n }\n\n }\n\n}\n\n\nadd_action( 'rest_api_init', 'Custom_Rest::init' );\n</code></pre>\n"
},
{
"answer_id": 225718,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>Let's assume it stores the custom order into the <code>menu_order</code> column in the <code>wp_posts</code> table.</p>\n\n<p>If you mean the hierarchical <code>page</code> post type (supports <em>page-attributes</em>) then one can order with the query variables: </p>\n\n<pre><code>/wp-json/wp/v2/pages/?orderby=menu_order&order=asc\n</code></pre>\n\n<p>If you mean the <code>post</code> post type with:</p>\n\n<pre><code>/wp-json/wp/v2/posts/\n</code></pre>\n\n<p>there's a way using the <code>rest_{post_type}_query</code> filter:</p>\n\n<pre><code>/**\n * Set orderby to 'menu_order' for the 'post' post type\n */\nadd_filter( \"rest_post_query\", function( $args, $request )\n{\n $args['orderby'] = 'menu_order';\n return $args;\n}, 10, 2 );\n</code></pre>\n\n<p>We might want to restrict this further. Skimming through the <code>WP_REST_Request</code> class we can see there's a handy <code>get_param()</code> public method that we could make use of:</p>\n\n<pre><code>/**\n * Support for 'wpse_custom_order=menu_order' for the 'post' post type\n */\nadd_filter( \"rest_post_query\", function( $args, $request )\n{\n if( 'menu_order' === $request->get_param( 'wpse_custom_order' ) )\n $args['orderby'] = 'menu_order';\n\n return $args;\n}, 10, 2 );\n</code></pre>\n\n<p>where we activate it through a custom <code>wpse_custom_order</code> parameter:</p>\n\n<pre><code>/wp-json/wp/v2/posts/?wpse_custom_order=menu_order&order=asc\n</code></pre>\n\n<p>There's also the dynamically generated <code>rest_query_var-orderby</code> filter.</p>\n"
}
] |
2016/05/03
|
[
"https://wordpress.stackexchange.com/questions/225527",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27168/"
] |
I generally use the [Intuitive Custom Post Order](https://wordpress.org/plugins/intuitive-custom-post-order) plugin for any WordPress sites I work with so clients can order their posts visually.
For this project, I'm using WordPress as an admin panel and consuming it's data with an Ember.js front-end.
(using wp-api V.2) The re-ordered order doesn't show in the JSON and I'm guessing the plugin stores the new order in an in-between piece of PHP.
Besides manually changing the date of each post, what are my options to allow my client an intuitive way to re-order posts in a way that persists?
|
Let's assume it stores the custom order into the `menu_order` column in the `wp_posts` table.
If you mean the hierarchical `page` post type (supports *page-attributes*) then one can order with the query variables:
```
/wp-json/wp/v2/pages/?orderby=menu_order&order=asc
```
If you mean the `post` post type with:
```
/wp-json/wp/v2/posts/
```
there's a way using the `rest_{post_type}_query` filter:
```
/**
* Set orderby to 'menu_order' for the 'post' post type
*/
add_filter( "rest_post_query", function( $args, $request )
{
$args['orderby'] = 'menu_order';
return $args;
}, 10, 2 );
```
We might want to restrict this further. Skimming through the `WP_REST_Request` class we can see there's a handy `get_param()` public method that we could make use of:
```
/**
* Support for 'wpse_custom_order=menu_order' for the 'post' post type
*/
add_filter( "rest_post_query", function( $args, $request )
{
if( 'menu_order' === $request->get_param( 'wpse_custom_order' ) )
$args['orderby'] = 'menu_order';
return $args;
}, 10, 2 );
```
where we activate it through a custom `wpse_custom_order` parameter:
```
/wp-json/wp/v2/posts/?wpse_custom_order=menu_order&order=asc
```
There's also the dynamically generated `rest_query_var-orderby` filter.
|
225,582 |
<p>I am working on a custom post type and I don't want it to get all the clutter from <code>wp_head()</code>. However, I do want to show a specific hook, for example the YoastSEO meta tags.</p>
<p>How do I call a specific single hook in the template file without <code>wp_head()</code>? I tried adding a filter to <code>wp_head</code> that removes the parts I don't want, e.g.:</p>
<pre><code>if ( 'customtype' === get_post_type() )
{
remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'feed_links' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'wp_generator' );
remove_action( 'wp_head', 'start_post_rel_link' );
remove_action( 'wp_head', 'index_rel_link' );
remove_action( 'wp_head', 'adjacent_posts_rel_link' );
remove_action( 'wp_head', 'wp_shortlink_wp_head' );
}
</code></pre>
<p>However, this seems inefficient and I would have to maintain any additional plugins or functions that manipulate or add actions to <code>wp_head()</code>.</p>
<p>Is there a way to remove ALL actions and keep the one(s) I want? I'd prefer not including <code>wp_head</code> at all and just call whatever action I need for that custom post type.</p>
|
[
{
"answer_id": 225585,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": true,
"text": "<p><code>wp_head</code> is an essential part of the theme, and there is too many things that might fall apart if it is not there. Hunting and fixing them one by one might be time consuming and the worthiness of the all operation questionable.</p>\n\n<p>In you snippet for example you want to remove things that make no sense to remove specifically only for one CPT, and if you have them on other post types there is no real reason not to have them on that one. </p>\n"
},
{
"answer_id": 225591,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Since plugins hook directly into <code>wp_head</code> nothing will happen if it's not there unless you change the plugin code. So, you'd have to create your own hook in the theme, then scan the Yoast files for any calls to wp_head and change them. Not recommended, though.</p>\n\n<p>A better course of action would be to generate these metatags yourself. They're pretty straightforward.</p>\n"
}
] |
2016/05/04
|
[
"https://wordpress.stackexchange.com/questions/225582",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82468/"
] |
I am working on a custom post type and I don't want it to get all the clutter from `wp_head()`. However, I do want to show a specific hook, for example the YoastSEO meta tags.
How do I call a specific single hook in the template file without `wp_head()`? I tried adding a filter to `wp_head` that removes the parts I don't want, e.g.:
```
if ( 'customtype' === get_post_type() )
{
remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'feed_links' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'wp_generator' );
remove_action( 'wp_head', 'start_post_rel_link' );
remove_action( 'wp_head', 'index_rel_link' );
remove_action( 'wp_head', 'adjacent_posts_rel_link' );
remove_action( 'wp_head', 'wp_shortlink_wp_head' );
}
```
However, this seems inefficient and I would have to maintain any additional plugins or functions that manipulate or add actions to `wp_head()`.
Is there a way to remove ALL actions and keep the one(s) I want? I'd prefer not including `wp_head` at all and just call whatever action I need for that custom post type.
|
`wp_head` is an essential part of the theme, and there is too many things that might fall apart if it is not there. Hunting and fixing them one by one might be time consuming and the worthiness of the all operation questionable.
In you snippet for example you want to remove things that make no sense to remove specifically only for one CPT, and if you have them on other post types there is no real reason not to have them on that one.
|
225,587 |
<p>I'm wondering how you can receive a categories parent name and link for a breadcrumb I've written.</p>
<p>I basically want to have the following structure</p>
<pre><code>if child category
blog > parent_category
else if grandchild category
blog > grand_parent_category > parent_category
</code></pre>
|
[
{
"answer_id": 225596,
"author": "Ahed Eid",
"author_id": 81934,
"author_profile": "https://wordpress.stackexchange.com/users/81934",
"pm_score": 1,
"selected": true,
"text": "<p>This query will help you </p>\n\n<pre><code>global $wpdb;\n\n$cat_id = 65;\n\n// this query will get parent relationships from term_taxonomy table and get category names from terms table\n$category = $wpdb->get_row(\n \"SELECT t4.term_id as parent_id, t4.name as parent_name, t5.term_id as grandparent_id, t5.name as grandparent_name FROM `{$wpdb->prefix}term_taxonomy` t1\nleft join `{$wpdb->prefix}term_taxonomy` t2 on t2.term_id = t1.parent\nleft join `{$wpdb->prefix}term_taxonomy` t3 on t3.term_id = t2.parent\nleft join `{$wpdb->prefix}terms` t4 on t4.term_id = t2.term_id\nleft join `{$wpdb->prefix}terms` t5 on t5.term_id = t3.term_id\nwhere t1.term_id={$cat_id}\"\n);\n\nif ($category->grandparent_id) {\n echo \"blog > {$category->grandparent_name} > {$category->parent_name}\";\n} else if ($category->parent_id) {\n echo \"blog > {$category->parent_name}\";\n}\n</code></pre>\n"
},
{
"answer_id": 225599,
"author": "550",
"author_id": 92492,
"author_profile": "https://wordpress.stackexchange.com/users/92492",
"pm_score": -1,
"selected": false,
"text": "<p>Ok managed to get the children and parents to loop out correctly.</p>\n\n<pre><code>$catid = get_query_var( 'cat' );\n\nwhile( $catid ) {\n $cat = get_category( $catid ); // Get the object for the catid.\n $catid = $cat->category_parent; // assign parent ID (if exists) to $catid\n // the while loop will continue whilst there is a $catid\n // when there is no longer a parent $catid will be NULL so we can assign our $catParent\n $category_parent = $cat->cat_name;\n $category_parent_link = get_category_link( $cat->cat_ID );\n\n echo '<li class=\"' . esc_attr( $root_item_class ) . '\" itemprop=\"itemListElement\" itemscope itemtype=\"http://schema.org/ListItem\" aria-level=\"3\"><a href=\"' . esc_url( $category_parent_link ) . '\" itemprop=\"item\"><span itemprop=\"name\">' . $category_parent . '</span></a><meta itemprop=\"position\" content=\"3\" /></li>';\n}\n</code></pre>\n\n<p>Problems I have now are \nI need to reverse the output of the loop as it currently loops. </p>\n\n<pre><code>child > parent > grandparent\n</code></pre>\n\n<p>if they exist.</p>\n\n<p>Also at every stage of the the loop I need to add the correct value for schema and accessbiliity logic. With each level needing to increase by 1 depending on the number of ancestors.</p>\n\n<p>For example</p>\n\n<pre><code><meta itemprop=\"position\" content=\"3\" /> AND aria-level=\"3\" by each level.\n</code></pre>\n\n<p>with great grand parent[3] > grand parent[4] > parent[5] etc.</p>\n"
}
] |
2016/05/04
|
[
"https://wordpress.stackexchange.com/questions/225587",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92492/"
] |
I'm wondering how you can receive a categories parent name and link for a breadcrumb I've written.
I basically want to have the following structure
```
if child category
blog > parent_category
else if grandchild category
blog > grand_parent_category > parent_category
```
|
This query will help you
```
global $wpdb;
$cat_id = 65;
// this query will get parent relationships from term_taxonomy table and get category names from terms table
$category = $wpdb->get_row(
"SELECT t4.term_id as parent_id, t4.name as parent_name, t5.term_id as grandparent_id, t5.name as grandparent_name FROM `{$wpdb->prefix}term_taxonomy` t1
left join `{$wpdb->prefix}term_taxonomy` t2 on t2.term_id = t1.parent
left join `{$wpdb->prefix}term_taxonomy` t3 on t3.term_id = t2.parent
left join `{$wpdb->prefix}terms` t4 on t4.term_id = t2.term_id
left join `{$wpdb->prefix}terms` t5 on t5.term_id = t3.term_id
where t1.term_id={$cat_id}"
);
if ($category->grandparent_id) {
echo "blog > {$category->grandparent_name} > {$category->parent_name}";
} else if ($category->parent_id) {
echo "blog > {$category->parent_name}";
}
```
|
225,588 |
<p>I have a snippet that will select a data from database table. But I encounter an error: <code>Warning: Invalid argument supplied for foreach()</code></p>
<p>I encounter a new error: <code>Notice: Trying to get property of non-object</code>in this line <code>echo $result->Name;</code></p>
<p>Snippet (updated):</p>
<pre><code>$results = $wpdb->get_results( 'SELECT DATE_FORMAT(FROM_UNIXTIME(submit_time), "%b %e, %Y %l:%i %p") AS Submitted,
MAX(IF(field_name="Name", field_value, NULL )) AS "Name",
MAX(IF(field_name="Email", field_value, NULL )) AS "Email",
MAX(IF(field_name="Subject", field_value, NULL )) AS "Position",
MAX(IF(field_name="Message", field_value, NULL )) AS "Message"
FROM tablename
WHERE form_name = "Resume"
GROUP BY submit_time
ORDER BY submit_time DESC', ARRAY_A);
foreach($results as $result){
echo $result->Name;
}
</code></pre>
<p><a href="http://bit.ly/1W8opml" rel="nofollow">Link</a></p>
|
[
{
"answer_id": 225598,
"author": "Ahed Eid",
"author_id": 81934,
"author_profile": "https://wordpress.stackexchange.com/users/81934",
"pm_score": 3,
"selected": true,
"text": "<p>You have a problem with your query which is you can't use <code>GROUP BY</code> and <code>ORDER BY</code> before <code>WHERE</code></p>\n\n<p>replace </p>\n\n<pre><code>FROM tablename GROUP BY submit_time ORDER BY submit_time DESC\n</code></pre>\n\n<p>with </p>\n\n<pre><code>FROM tablename\n</code></pre>\n\n<p>This is your query </p>\n\n<pre><code>$results = $wpdb->get_results( 'SELECT DATE_FORMAT(FROM_UNIXTIME(submit_time), \"%b %e, %Y %l:%i %p\") AS Submitted,\n MAX(IF(field_name=\"Name\", field_value, NULL )) AS \"Name\",\n MAX(IF(field_name=\"Email\", field_value, NULL )) AS \"Email\",\n MAX(IF(field_name=\"Subject\", field_value, NULL )) AS \"Position\",\n MAX(IF(field_name=\"Message\", field_value, NULL )) AS \"Message\"\n FROM tablename\n WHERE\n form_name = \"Resume\"\n GROUP BY submit_time\n ORDER BY submit_time DESC', ARRAY_A);\n</code></pre>\n"
},
{
"answer_id": 225610,
"author": "Jamie",
"author_id": 30708,
"author_profile": "https://wordpress.stackexchange.com/users/30708",
"pm_score": 2,
"selected": false,
"text": "<p>Going to take a wild stab, but <code>ARRAY_A</code> will return an associative array</p>\n\n<p>You are then trying to access this associative array as an object</p>\n\n<p>Simple change: </p>\n\n<pre><code>foreach($results as $result){\n echo $result->Name;\n}\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>foreach($results as $result){\n echo $result['Name'];\n}\n</code></pre>\n\n<p>and the error should go away!</p>\n"
},
{
"answer_id": 225611,
"author": "Swopnil Dangol",
"author_id": 90685,
"author_profile": "https://wordpress.stackexchange.com/users/90685",
"pm_score": 0,
"selected": false,
"text": "<p><code>$wpdb->get_results</code> returns a multi-dimensional array.\nSo the argument for the foreach should be:</p>\n\n<pre><code>foreach($results as $object=>$result){\n echo $result->Name;\n}\n</code></pre>\n\n<p>Always var_dump your objects and arrays before accessing them.</p>\n"
}
] |
2016/05/04
|
[
"https://wordpress.stackexchange.com/questions/225588",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93475/"
] |
I have a snippet that will select a data from database table. But I encounter an error: `Warning: Invalid argument supplied for foreach()`
I encounter a new error: `Notice: Trying to get property of non-object`in this line `echo $result->Name;`
Snippet (updated):
```
$results = $wpdb->get_results( 'SELECT DATE_FORMAT(FROM_UNIXTIME(submit_time), "%b %e, %Y %l:%i %p") AS Submitted,
MAX(IF(field_name="Name", field_value, NULL )) AS "Name",
MAX(IF(field_name="Email", field_value, NULL )) AS "Email",
MAX(IF(field_name="Subject", field_value, NULL )) AS "Position",
MAX(IF(field_name="Message", field_value, NULL )) AS "Message"
FROM tablename
WHERE form_name = "Resume"
GROUP BY submit_time
ORDER BY submit_time DESC', ARRAY_A);
foreach($results as $result){
echo $result->Name;
}
```
[Link](http://bit.ly/1W8opml)
|
You have a problem with your query which is you can't use `GROUP BY` and `ORDER BY` before `WHERE`
replace
```
FROM tablename GROUP BY submit_time ORDER BY submit_time DESC
```
with
```
FROM tablename
```
This is your query
```
$results = $wpdb->get_results( 'SELECT DATE_FORMAT(FROM_UNIXTIME(submit_time), "%b %e, %Y %l:%i %p") AS Submitted,
MAX(IF(field_name="Name", field_value, NULL )) AS "Name",
MAX(IF(field_name="Email", field_value, NULL )) AS "Email",
MAX(IF(field_name="Subject", field_value, NULL )) AS "Position",
MAX(IF(field_name="Message", field_value, NULL )) AS "Message"
FROM tablename
WHERE
form_name = "Resume"
GROUP BY submit_time
ORDER BY submit_time DESC', ARRAY_A);
```
|
225,616 |
<p>I'm trying to find the first hook that will pass the current post ID, as I would like to update the current post (by getting its ID) and the variables submitted to that page.</p>
<p>This is the code I'm using:</p>
<pre><code>class my_class {
public function __construct(){
add_action( 'init', array( $this, 'my_method' ) );
}
public function my_method( $atts ){
// do my stuff with current page id here.
// even just: echo post id and die();.
}
}
</code></pre>
<p>Any hook, action or filter, and which one to use and why.</p>
|
[
{
"answer_id": 298396,
"author": "knsheely",
"author_id": 70429,
"author_profile": "https://wordpress.stackexchange.com/users/70429",
"pm_score": 0,
"selected": false,
"text": "<p>I think you are looking for <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/the_post\" rel=\"nofollow noreferrer\"><code>the_post</code></a> (see <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request\" rel=\"nofollow noreferrer\">action reference</a>.). That is the first hook within the loop.</p>\n"
},
{
"answer_id": 356199,
"author": "lepe",
"author_id": 97843,
"author_profile": "https://wordpress.stackexchange.com/users/97843",
"pm_score": 3,
"selected": false,
"text": "<p>Answer by @Pieter Goosen :</p>\n<blockquote>\n<p>If you need to update the page before the main query fires and returns\nthe page object, you will manually need to parse the URL (probably on\ninit) and get the page ID from get_page_by_title() or\nget_page_by_path().</p>\n<p>Otherwise, 'wp' would be earliest hook to get the page ID, for example:</p>\n</blockquote>\n<pre><code>function my_early_id() {\n $post = get_post();\n echo $post->ID;\n}\nadd_action( 'wp', 'my_early_id' );\n</code></pre>\n"
}
] |
2016/05/04
|
[
"https://wordpress.stackexchange.com/questions/225616",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57389/"
] |
I'm trying to find the first hook that will pass the current post ID, as I would like to update the current post (by getting its ID) and the variables submitted to that page.
This is the code I'm using:
```
class my_class {
public function __construct(){
add_action( 'init', array( $this, 'my_method' ) );
}
public function my_method( $atts ){
// do my stuff with current page id here.
// even just: echo post id and die();.
}
}
```
Any hook, action or filter, and which one to use and why.
|
Answer by @Pieter Goosen :
>
> If you need to update the page before the main query fires and returns
> the page object, you will manually need to parse the URL (probably on
> init) and get the page ID from get\_page\_by\_title() or
> get\_page\_by\_path().
>
>
> Otherwise, 'wp' would be earliest hook to get the page ID, for example:
>
>
>
```
function my_early_id() {
$post = get_post();
echo $post->ID;
}
add_action( 'wp', 'my_early_id' );
```
|
225,625 |
<p>Which hook or filter is used to edit the post content before <code>the_content</code> filter is applied to it.</p>
<p>For instance, if I wanted to add <strong>Hello World,</strong> as the first text in every post.</p>
|
[
{
"answer_id": 225627,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>There is no other global filter applied before <code>the_content</code> - you can use the <a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow\"><code>$priority</code></a> argument in your <code>add_filter</code> call to ensure your function runs before any others:</p>\n\n<pre><code>function wpse_225625_to_the_top( $content ) {\n return \"Hello World\\n\\n\\$content\";\n}\n\nadd_filter( 'the_content', 'wpse_225625_to_the_top', -1 /* Super important yo */ );\n</code></pre>\n"
},
{
"answer_id": 225628,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 5,
"selected": true,
"text": "<p>You can use <code>the_content</code> with an high prioriety (lower number).</p>\n\n<pre><code>add_filter( 'the_content', function( $content ) {\n return 'Hello World '.$content;\n}, 0);\n</code></pre>\n\n<p>You can even use negative priority:</p>\n\n<pre><code>add_filter( 'the_content', function( $content ) {\n return 'Hello World '.$content;\n}, -10);\n</code></pre>\n\n<p>Note that this will apply everytime <code>'the_content'</code> is used, no matter the post type, or if the target post is part of main query or not.</p>\n\n<p>For more control you can use <code>loop_start</code> / <code>loop_end</code> actions to add and remove the filter:</p>\n\n<pre><code>// the function that edits post content\nfunction my_edit_content( $content ) {\n global $post;\n // only edit specific post types\n $types = array( 'post', 'page' );\n if ( $post && in_array( $post->post_type, $types, true ) ) {\n $content = 'Hello World '. $content;\n }\n\n return $content;\n}\n\n// add the filter when main loop starts\nadd_action( 'loop_start', function( WP_Query $query ) {\n if ( $query->is_main_query() ) {\n add_filter( 'the_content', 'my_edit_content', -10 );\n }\n} );\n\n// remove the filter when main loop ends\nadd_action( 'loop_end', function( WP_Query $query ) {\n if ( has_filter( 'the_content', 'my_edit_content' ) ) {\n remove_filter( 'the_content', 'my_edit_content' );\n }\n} );\n</code></pre>\n"
}
] |
2016/05/04
|
[
"https://wordpress.stackexchange.com/questions/225625",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/20557/"
] |
Which hook or filter is used to edit the post content before `the_content` filter is applied to it.
For instance, if I wanted to add **Hello World,** as the first text in every post.
|
You can use `the_content` with an high prioriety (lower number).
```
add_filter( 'the_content', function( $content ) {
return 'Hello World '.$content;
}, 0);
```
You can even use negative priority:
```
add_filter( 'the_content', function( $content ) {
return 'Hello World '.$content;
}, -10);
```
Note that this will apply everytime `'the_content'` is used, no matter the post type, or if the target post is part of main query or not.
For more control you can use `loop_start` / `loop_end` actions to add and remove the filter:
```
// the function that edits post content
function my_edit_content( $content ) {
global $post;
// only edit specific post types
$types = array( 'post', 'page' );
if ( $post && in_array( $post->post_type, $types, true ) ) {
$content = 'Hello World '. $content;
}
return $content;
}
// add the filter when main loop starts
add_action( 'loop_start', function( WP_Query $query ) {
if ( $query->is_main_query() ) {
add_filter( 'the_content', 'my_edit_content', -10 );
}
} );
// remove the filter when main loop ends
add_action( 'loop_end', function( WP_Query $query ) {
if ( has_filter( 'the_content', 'my_edit_content' ) ) {
remove_filter( 'the_content', 'my_edit_content' );
}
} );
```
|
225,635 |
<p>Is there any way to disable or remove the "Auto add pages - Automatically add new top-level pages to this menu" functionality via a theme?</p>
<p>I suppose I could hide it with a bit of CSS, but I'd rather do more cleanly if possible.</p>
<p>Many clients click that not realizing what it does and chaos ensues. </p>
|
[
{
"answer_id": 239668,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>As per comments and <a href=\"https://github.com/WordPress/WordPress/blob/788c3680f90b7570f8f9b5277f5d6bf57d7d9209/wp-admin/nav-menus.php#L801\" rel=\"nofollow\">verifiable in the source</a>:</p>\n\n<pre><code><dl class=\"auto-add-pages\">\n <dt class=\"howto\"><?php _e( 'Auto add pages' ); ?></dt>\n <dd class=\"checkbox-input\"><input type=\"checkbox\"<?php checked( $auto_add ); ?> name=\"auto-add-pages\" id=\"auto-add-pages\" value=\"1\" /> <label for=\"auto-add-pages\"><?php printf( __('Automatically add new top-level pages to this menu' ), esc_url( admin_url( 'edit.php?post_type=page' ) ) ); ?></label></dd>\n</dl>\n</code></pre>\n\n<p>there is no filter to get rid of Auto Add Pages in a clean way. You'll have to use css or javascript.</p>\n"
},
{
"answer_id": 239673,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 2,
"selected": false,
"text": "<p>Since there is no filter to remove this option, your best best to to stick to using CSS by putting the following in your child theme's <code>functions.php</code>:</p>\n\n<pre><code>add_action( 'admin_head', 'wpse_225635_menu_css' );\nfunction wpse_225635_menu_css() {\n global $pagenow;\n if ( $pagenow == 'nav-menus.php' ) {\n ?>\n <style type=\"text/css\">\n .auto-add-pages {\n display: none;\n }\n </style>\n <?php\n }\n}\n</code></pre>\n"
}
] |
2016/05/04
|
[
"https://wordpress.stackexchange.com/questions/225635",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83367/"
] |
Is there any way to disable or remove the "Auto add pages - Automatically add new top-level pages to this menu" functionality via a theme?
I suppose I could hide it with a bit of CSS, but I'd rather do more cleanly if possible.
Many clients click that not realizing what it does and chaos ensues.
|
Since there is no filter to remove this option, your best best to to stick to using CSS by putting the following in your child theme's `functions.php`:
```
add_action( 'admin_head', 'wpse_225635_menu_css' );
function wpse_225635_menu_css() {
global $pagenow;
if ( $pagenow == 'nav-menus.php' ) {
?>
<style type="text/css">
.auto-add-pages {
display: none;
}
</style>
<?php
}
}
```
|
225,641 |
<p>After rolling back a Wordpress database to a backup version it seems that all the tables lost their auto_increment on the primary key columns. I read on another post this could be to do with InnoDB storing the auto_increment value in memory. I've rolled back and migrated databases before without such issues. Anyone ran in a similar issue before? Thanks in advance for any help.</p>
|
[
{
"answer_id": 225647,
"author": "N00b",
"author_id": 80903,
"author_profile": "https://wordpress.stackexchange.com/users/80903",
"pm_score": 3,
"selected": false,
"text": "<p>Why did it happen? It's hard to tell for sure because there are lots of variables to consider: mistakes made in exporting or importing, MySQL version <em>etc</em>. </p>\n\n<p>This is rather specific MySQL database question and doesn't have much to do with WordPress itself. To get a specific non-speculative answer to question <strong>why</strong>, I suggest to ask it in <a href=\"https://stackoverflow.com/\">SO</a> or <a href=\"https://dba.stackexchange.com/questions\">DBA</a> with plenty of details about your backup process.</p>\n\n<hr>\n\n<p><strong>Solution</strong>: <code>ALTER TABLE table_name AUTO_INCREMENT = increment_number</code> </p>\n\n<ul>\n<li>This sets <code>AUTO_INCREMENT</code> manually to a selected number</li>\n<li><code>increment_number</code> value <strong>must be</strong> at least one number higher than\nyour current highest number of that table's primary key that is auto\nincremeted</li>\n<li>Also, don't forget to change <code>table_name</code></li>\n</ul>\n\n<hr>\n\n<p>Example: <code>ALTER TABLE wp_posts AUTO_INCREMENT = 2043</code> <code><-</code> biggest number in ID column + 1</p>\n\n<p>Extra notes: </p>\n\n<ul>\n<li>You will need to repeat this for each table that has messed up auto increment</li>\n<li>There might be a way to alter all tables at once but Im not SQL guru (<strong>correct me if there is</strong>)</li>\n<li>It will take some time for huge tables because <code>ALTER TABLE</code> causes a\nrebuild of the entire table</li>\n</ul>\n\n<hr>\n\n<p>More information: <strong><a href=\"https://stackoverflow.com/questions/8923114/how-to-reset-auto-increment-in-mysql\">here</a></strong> and <strong><a href=\"https://stackoverflow.com/questions/2681869/resetting-auto-increment-is-taking-a-long-time-in-mysqlhttps://stackoverflow.com/questions/2681869/resetting-auto-increment-is-taking-a-long-time-in-mysql\">here</a></strong></p>\n"
},
{
"answer_id": 251093,
"author": "Tim",
"author_id": 92467,
"author_profile": "https://wordpress.stackexchange.com/users/92467",
"pm_score": 5,
"selected": false,
"text": "<p>I had a similar issue, I solved it and since this comes up high on Google for what I was looking for it may help others.</p>\n\n<p>I migrated several Wordpress databases from AWS RDS MySQL to MySQL running on an EC2 instance, using the database migration service. What I didn't know is it doesn't copy indexes, keys, auto increment, or really anything other than the basics. Of course the best approach would be to dump the database using mysqldump and import it manually, but one Wordpress install had significant changes and I didn't want to redo them. Instead I manually recreated the auto_increment values and indexes.</p>\n\n<p>I've documented how I <a href=\"https://www.photographerstechsupport.com/tutorials/fixing-wordpress-indexes-foreign-keys-and-auto_increment-fields/\" rel=\"noreferrer\">fixed Wordpress auto increment here on my website</a>, here's a copy of what worked for me. It's possible I'll make further changes, I'll update the website but I may not remember to update this question.</p>\n\n<pre><code>ALTER TABLE wp_termmeta MODIFY COLUMN meta_id bigint(20) unsigned NOT NULL auto_increment;\nALTER TABLE wp_terms MODIFY COLUMN term_id bigint(20) unsigned NOT NULL auto_increment;\nALTER TABLE wp_term_taxonomy MODIFY COLUMN term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment;\nALTER TABLE wp_commentmeta MODIFY COLUMN meta_id bigint(20) unsigned NOT NULL auto_increment;\nALTER TABLE wp_comments MODIFY COLUMN comment_ID bigint(20) unsigned NOT NULL auto_increment;\nALTER TABLE wp_links MODIFY COLUMN link_id bigint(20) unsigned NOT NULL auto_increment;\nALTER TABLE wp_options MODIFY COLUMN option_id bigint(20) unsigned NOT NULL auto_increment;\nALTER TABLE wp_postmeta MODIFY COLUMN meta_id bigint(20) unsigned NOT NULL auto_increment;\nALTER TABLE wp_users MODIFY COLUMN ID bigint(20) unsigned NOT NULL auto_increment;\nALTER TABLE wp_posts MODIFY COLUMN ID bigint(20) unsigned NOT NULL auto_increment;\nALTER TABLE wp_usermeta MODIFY COLUMN umeta_id bigint(20) unsigned NOT NULL auto_increment;\n\nCREATE INDEX term_id on wp_termmeta (term_id);\nCREATE INDEX meta_key on wp_termmeta (meta_key(191));\nCREATE INDEX slug on wp_terms (slug(191));\nCREATE INDEX name on wp_terms (name(191));\nCREATE UNIQUE INDEX term_id_taxonomy on wp_term_taxonomy (term_id, taxonomy);\nCREATE INDEX taxonomy on wp_term_taxonomy (taxonomy );\nCREATE INDEX comment_id on wp_commentmeta (comment_id);\nCREATE INDEX meta_key on wp_commentmeta (meta_key(191));\nCREATE INDEX comment_post_ID on wp_comments (comment_post_ID);\nCREATE INDEX comment_approved_date_gmt on wp_comments (comment_approved,comment_date_gmt);\nCREATE INDEX comment_date_gmt on wp_comments (comment_date_gmt);\nCREATE INDEX comment_parent on wp_comments (comment_parent);\nCREATE INDEX comment_author_email on wp_comments (comment_author_email(10));\nCREATE INDEX link_visible on wp_links (link_visible);\nCREATE UNIQUE INDEX option_name on wp_options (option_name);\nCREATE INDEX post_id on wp_postmeta (post_id);\nCREATE INDEX meta_key on wp_postmeta (meta_key);\nCREATE INDEX post_name on wp_posts (post_name(191));\nCREATE INDEX type_status_date on wp_posts (post_type,post_status,post_date,ID);\nCREATE INDEX post_parent on wp_posts (post_parent);\nCREATE INDEX post_author on wp_posts (post_author);\nCREATE INDEX user_login_key on wp_users (user_login);\nCREATE INDEX user_nicename on wp_users (user_nicename);\nCREATE INDEX user_email on wp_users (user_email);\nCREATE INDEX user_id on wp_usermeta (user_id);\nCREATE INDEX meta_key on wp_usermeta (meta_key(191));\n\nALTER TABLE wp_terms AUTO_INCREMENT = 10000;\nALTER TABLE wp_term_taxonomy AUTO_INCREMENT = 10000;\nALTER TABLE wp_commentmeta AUTO_INCREMENT = 10000;\nALTER TABLE wp_comments AUTO_INCREMENT = 10000;\nALTER TABLE wp_links AUTO_INCREMENT = 10000;\nALTER TABLE wp_options AUTO_INCREMENT = 10000;\nALTER TABLE wp_postmeta AUTO_INCREMENT = 10000;\nALTER TABLE wp_users AUTO_INCREMENT = 10000;\nALTER TABLE wp_posts AUTO_INCREMENT = 10000;\nALTER TABLE wp_usermeta AUTO_INCREMENT = 10000;\n</code></pre>\n\n<p>Notes</p>\n\n<ul>\n<li>You should check your tables and make sure to set your auto_increment to a value that makes sense for that table. </li>\n<li>If you get the error βalter table causes auto_increment resequencing resulting in duplicate entry 1β (or 0, or something else). This is usually fixed by deleting the entry with the ID 0 or 1 in the table. Note that you should be careful doing this as it could delete an important row.</li>\n</ul>\n"
},
{
"answer_id": 310341,
"author": "Paresh Barad",
"author_id": 147975,
"author_profile": "https://wordpress.stackexchange.com/users/147975",
"pm_score": 1,
"selected": false,
"text": "<p>I forgot to import indexes from last of the MySQL file so I fetched the same issue and its hard to fire autoincrement query one by one so created script, Its take a dynamic table and check for primary key If script found and primary key then it will be applied to autoincrement dynamically.</p>\n\n<blockquote>\n <p><strong>Take db connection variable from your wp-config.php and save in youWordPressss root and run by url.</strong></p>\n</blockquote>\n\n<pre><code>// Database configration\n$host = 'localhost';\n$dbuser = 'dbuser';\n$dbpassword = 'dbpassword';\n$dbname = 'database';\n\n// connect to DB\n$conn = new mysqli($host, $dbuser, $dbpassword);\ntry {\n $connection = new PDO(\"mysql:host=$host;dbname=$dbname\", $dbuser, $dbpassword, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET sql_mode=\"NO_ZERO_DATE\"'));\n $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n echo \"Connected successfully\";\n} catch (PDOException $e) {\n exit(\"Connection failed: \" . $e->getMessage());\n}\n\n// get all tables from DB\n$stmt = $connection->prepare('SHOW TABLES');\n$stmt->execute();\n$table_names = array();\nforeach ($stmt->fetchAll() as $row) {\n $table_names[] = $row[0];\n}\n\n// for all tables\nforeach ($table_names as $table_name) {\n\n // get the name of primary key\n $stmt = $connection->prepare(\"show keys from $table_name where Key_name = 'PRIMARY'\");\n $stmt->execute();\n $key_name = $stmt->fetch()['Column_name'];\n\n // get the type of primary key\n $stmt = $connection->prepare(\"show fields from $table_name where Field = '$key_name'\");\n $stmt->execute();\n $key_type = $stmt->fetch()['Type'];\n\n // primary already exist then going to add auto increment\n if ($key_name) {\n\n try {\n // if auto_increment was missing there might be a row with key=0 . compute the next available primary key\n $sql = \"select (ifnull( max($key_name), 0)+1) as next_id from $table_name\";\n $stmt = $connection->prepare($sql);\n $stmt->execute();\n $next_id = $stmt->fetch()['next_id'];\n\n // give a sane primary key to a row that has key = 0 if it exists\n $sql = \"update $table_name set $key_name = $next_id where $key_name = 0\";\n $stmt = $connection->prepare($sql);\n $stmt->execute();\n\n // set auto_increment to the primary key\n $sql = \"alter table $table_name modify column $key_name $key_type auto_increment\";\n $stmt = $connection->prepare($sql);\n $stmt->execute();\n\n } catch (PDOException $e) {\n echo $e->getMessage() . '\\n';\n }\n } else {\n echo \"primary key not found in table $table_name.\\n\";\n }\n}\n$connection = null;\n</code></pre>\n"
},
{
"answer_id": 311093,
"author": "Ben Erwin",
"author_id": 147969,
"author_profile": "https://wordpress.stackexchange.com/users/147969",
"pm_score": 3,
"selected": false,
"text": "<p>Why did this happen? Here's what went wrong for me:</p>\n\n<p>If you exported your database using phpadmin and had an error on reimporting it, the code that adds the primary key doesn't run because it's at the end of the SQL file, not at its creation.</p>\n\n<p>Before I figured this out, I updated to the phpmyadmin 5 beta and it imported the files with the key even though I still had the error. </p>\n\n<p>Lesson one is, don't let your import crash, even if your tables are there. Mine crashed on table that began with wp_w so it came after user and rekt my auto increments. </p>\n\n<p>If you look at the bottom of your SQL export, you will find the alter table for adding the Primary Key and the auto increment. </p>\n\n<p><strong>You don't need to specify the auto increment</strong> it automatically knows what the next increment is like so:</p>\n\n<pre><code>ALTER TABLE wp_posts CHANGE ID ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;\n</code></pre>\n\n<p>If you had admin activity since this happened, you have zeros in your key field, which will not allow you to set a primary key, and without that, you can't auto increment. So you need to run a delete script vs each table \nlike so:</p>\n\n<pre><code>DELETE FROM wp_posts WHERE ID=0;\n</code></pre>\n\n<p>Here's a complete set of updates\nIf your table has these, it will throw and error.</p>\n\n<pre><code>DELETE FROM wp_termmeta WHERE meta_id=0;\nDELETE FROM wp_terms WHERE term_id=0;\nDELETE FROM wp_term_taxonomy WHERE term_taxonomy_id=0;\nDELETE FROM wp_commentmeta WHERE meta_id=0;\nDELETE FROM wp_comments WHERE comment_ID=0;\nDELETE FROM wp_links WHERE link_id=0;\nDELETE FROM wp_options WHERE option_id=0;\nDELETE FROM wp_postmeta WHERE meta_id=0;\nDELETE FROM wp_users WHERE ID=0;\nDELETE FROM wp_posts WHERE ID=0;\nDELETE FROM wp_usermeta WHERE umeta_id=0;\n\nALTER TABLE wp_termmeta ADD PRIMARY KEY(meta_id);\nALTER TABLE wp_terms ADD PRIMARY KEY(term_id);\nALTER TABLE wp_term_taxonomy ADD PRIMARY KEY(term_taxonomy_id);\nALTER TABLE wp_commentmeta ADD PRIMARY KEY(meta_id);\nALTER TABLE wp_comments ADD PRIMARY KEY(comment_ID);\nALTER TABLE wp_links ADD PRIMARY KEY(link_id);\nALTER TABLE wp_options ADD PRIMARY KEY(option_id);\nALTER TABLE wp_postmeta ADD PRIMARY KEY(meta_id);\nALTER TABLE wp_users ADD PRIMARY KEY(ID);\nALTER TABLE wp_posts ADD PRIMARY KEY(ID);\nALTER TABLE wp_usermeta ADD PRIMARY KEY(umeta_id);\n\nALTER TABLE wp_termmeta CHANGE meta_id meta_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;\nALTER TABLE wp_terms CHANGE term_id term_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;\nALTER TABLE wp_term_taxonomy CHANGE term_taxonomy_id term_taxonomy_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;\nALTER TABLE wp_commentmeta CHANGE meta_id meta_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;\nALTER TABLE wp_comments CHANGE comment_ID comment_ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;\nALTER TABLE wp_links CHANGE link_id link_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;\nALTER TABLE wp_options CHANGE option_id option_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;\nALTER TABLE wp_postmeta CHANGE meta_id meta_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;\nALTER TABLE wp_users CHANGE ID ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;\nALTER TABLE wp_posts CHANGE ID ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;\nALTER TABLE wp_usermeta CHANGE umeta_id umeta_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;\n</code></pre>\n"
},
{
"answer_id": 330222,
"author": "Ramon Fincken",
"author_id": 36159,
"author_profile": "https://wordpress.stackexchange.com/users/36159",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote an update for this.</p>\n\n<p>I uses the build in WP Core schema to ensure <em>all</em> WP Core tables are there (even in the future when 5.1.1 or higher is released ). It removes corrupt rows and re-adds keys an primary keys. The free script (and more explanation) can be seen over here: <a href=\"https://wpindexfixer.tools.managedwphosting.nl/\" rel=\"nofollow noreferrer\">https://wpindexfixer.tools.managedwphosting.nl/</a></p>\n\n<p>No need to guess the auto-increment value too.</p>\n"
}
] |
2016/05/04
|
[
"https://wordpress.stackexchange.com/questions/225641",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93506/"
] |
After rolling back a Wordpress database to a backup version it seems that all the tables lost their auto\_increment on the primary key columns. I read on another post this could be to do with InnoDB storing the auto\_increment value in memory. I've rolled back and migrated databases before without such issues. Anyone ran in a similar issue before? Thanks in advance for any help.
|
I had a similar issue, I solved it and since this comes up high on Google for what I was looking for it may help others.
I migrated several Wordpress databases from AWS RDS MySQL to MySQL running on an EC2 instance, using the database migration service. What I didn't know is it doesn't copy indexes, keys, auto increment, or really anything other than the basics. Of course the best approach would be to dump the database using mysqldump and import it manually, but one Wordpress install had significant changes and I didn't want to redo them. Instead I manually recreated the auto\_increment values and indexes.
I've documented how I [fixed Wordpress auto increment here on my website](https://www.photographerstechsupport.com/tutorials/fixing-wordpress-indexes-foreign-keys-and-auto_increment-fields/), here's a copy of what worked for me. It's possible I'll make further changes, I'll update the website but I may not remember to update this question.
```
ALTER TABLE wp_termmeta MODIFY COLUMN meta_id bigint(20) unsigned NOT NULL auto_increment;
ALTER TABLE wp_terms MODIFY COLUMN term_id bigint(20) unsigned NOT NULL auto_increment;
ALTER TABLE wp_term_taxonomy MODIFY COLUMN term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment;
ALTER TABLE wp_commentmeta MODIFY COLUMN meta_id bigint(20) unsigned NOT NULL auto_increment;
ALTER TABLE wp_comments MODIFY COLUMN comment_ID bigint(20) unsigned NOT NULL auto_increment;
ALTER TABLE wp_links MODIFY COLUMN link_id bigint(20) unsigned NOT NULL auto_increment;
ALTER TABLE wp_options MODIFY COLUMN option_id bigint(20) unsigned NOT NULL auto_increment;
ALTER TABLE wp_postmeta MODIFY COLUMN meta_id bigint(20) unsigned NOT NULL auto_increment;
ALTER TABLE wp_users MODIFY COLUMN ID bigint(20) unsigned NOT NULL auto_increment;
ALTER TABLE wp_posts MODIFY COLUMN ID bigint(20) unsigned NOT NULL auto_increment;
ALTER TABLE wp_usermeta MODIFY COLUMN umeta_id bigint(20) unsigned NOT NULL auto_increment;
CREATE INDEX term_id on wp_termmeta (term_id);
CREATE INDEX meta_key on wp_termmeta (meta_key(191));
CREATE INDEX slug on wp_terms (slug(191));
CREATE INDEX name on wp_terms (name(191));
CREATE UNIQUE INDEX term_id_taxonomy on wp_term_taxonomy (term_id, taxonomy);
CREATE INDEX taxonomy on wp_term_taxonomy (taxonomy );
CREATE INDEX comment_id on wp_commentmeta (comment_id);
CREATE INDEX meta_key on wp_commentmeta (meta_key(191));
CREATE INDEX comment_post_ID on wp_comments (comment_post_ID);
CREATE INDEX comment_approved_date_gmt on wp_comments (comment_approved,comment_date_gmt);
CREATE INDEX comment_date_gmt on wp_comments (comment_date_gmt);
CREATE INDEX comment_parent on wp_comments (comment_parent);
CREATE INDEX comment_author_email on wp_comments (comment_author_email(10));
CREATE INDEX link_visible on wp_links (link_visible);
CREATE UNIQUE INDEX option_name on wp_options (option_name);
CREATE INDEX post_id on wp_postmeta (post_id);
CREATE INDEX meta_key on wp_postmeta (meta_key);
CREATE INDEX post_name on wp_posts (post_name(191));
CREATE INDEX type_status_date on wp_posts (post_type,post_status,post_date,ID);
CREATE INDEX post_parent on wp_posts (post_parent);
CREATE INDEX post_author on wp_posts (post_author);
CREATE INDEX user_login_key on wp_users (user_login);
CREATE INDEX user_nicename on wp_users (user_nicename);
CREATE INDEX user_email on wp_users (user_email);
CREATE INDEX user_id on wp_usermeta (user_id);
CREATE INDEX meta_key on wp_usermeta (meta_key(191));
ALTER TABLE wp_terms AUTO_INCREMENT = 10000;
ALTER TABLE wp_term_taxonomy AUTO_INCREMENT = 10000;
ALTER TABLE wp_commentmeta AUTO_INCREMENT = 10000;
ALTER TABLE wp_comments AUTO_INCREMENT = 10000;
ALTER TABLE wp_links AUTO_INCREMENT = 10000;
ALTER TABLE wp_options AUTO_INCREMENT = 10000;
ALTER TABLE wp_postmeta AUTO_INCREMENT = 10000;
ALTER TABLE wp_users AUTO_INCREMENT = 10000;
ALTER TABLE wp_posts AUTO_INCREMENT = 10000;
ALTER TABLE wp_usermeta AUTO_INCREMENT = 10000;
```
Notes
* You should check your tables and make sure to set your auto\_increment to a value that makes sense for that table.
* If you get the error βalter table causes auto\_increment resequencing resulting in duplicate entry 1β (or 0, or something else). This is usually fixed by deleting the entry with the ID 0 or 1 in the table. Note that you should be careful doing this as it could delete an important row.
|
225,642 |
<p>I need to add the author name as a subdirectory prefix for all user's posts and pages.</p>
<p>For example:</p>
<pre><code>example.com/johndoe/ //The author page for John Doe
example.com/johndoe/category/test-post/ //Test post by user John Doe
example.com/johndoe/test-page/ //Test page by user John Doe
</code></pre>
<p>If I change the permalink structure to: <code>/%author%/%category%/%postname%/</code> this works fine for displaying a user's post but not a user's page.</p>
<p>However I'm not sure if there is something I can do in <code>.htaccess</code> or <code>functions.php</code> that will allow me to get the <code>pages</code> to work in the same manner.</p>
<p>I understand this can be accomplished with Multisite, however I'm trying to avoid using this because the client doesn't want to use it.</p>
|
[
{
"answer_id": 339561,
"author": "Paul G.",
"author_id": 41288,
"author_profile": "https://wordpress.stackexchange.com/users/41288",
"pm_score": 1,
"selected": false,
"text": "<p>By the looks of it, there's a plugin to achieve exactly this, so save you rolling your own for it.</p>\n\n<p>The plugin is: <a href=\"https://wordpress.org/plugins/permalinks-customizer/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/permalinks-customizer/</a></p>\n\n<p>I installed it to test that it does what you're looking for. Here's a screenshot that shows what you'd do:</p>\n\n<p><a href=\"https://i.stack.imgur.com/eRxHU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eRxHU.png\" alt=\"Permalinks Customizer\"></a></p>\n"
},
{
"answer_id": 340566,
"author": "laxandrea",
"author_id": 169104,
"author_profile": "https://wordpress.stackexchange.com/users/169104",
"pm_score": 0,
"selected": false,
"text": "<p><em>Tested with Wordpress 5.0.4</em></p>\n\n<p>The first problem to solve it's the <em>post_name</em> value for pages that would share the same slug (e.g. <em>about-me</em>). </p>\n\n<p>The simpler solution I found is to add the author <em>nicename</em> (beware: in my solution it should not contain a hyphen!) as the first part of the slug:</p>\n\n<p>about-me page post_name for john: <em>john-about-me</em><br>\nabout-me page post_name for mary: <em>mary-about-me</em></p>\n\n<p>This could be achieved using the <strong>wp_insert_post_data</strong> filter hook (see <em>wp_insert_post()</em> function defined in <em>wp-includes/post.php</em>) when creating the page:</p>\n\n<pre><code>// about-me => <author_name>-about-me\n\nadd_filter( 'wp_insert_post_data', 'custom_wp_insert_post_data', 99, 2);\n\nfunction custom_wp_insert_post_data($data, $postarr)\n{\n if(($data[\"post_type\"] == \"page\") && ($data[\"post_status\"] != \"auto-draft\"))\n {\n $author_name = get_the_author_meta( 'user_nicename', $data[\"post_author\"] );\n\n // insert\n if($postarr['hidden_post_status'] == \"draft\") { \n $data[\"post_name\"] = $author_name . \"-\" . $data[\"post_name\"]; \n }\n // update\n else {\n list($author, $slug) = explode(\"-\", basename($data[\"post_name\"]), 2 );\n\n // wrong permalink -> prepend the author\n if($author != $author_name) { \n $data[\"post_name\"] = $author_name . \"-\" . $data[\"post_name\"];\n }\n }\n }\n\n return $data; \n}\n</code></pre>\n\n<p>Next step it will be to change the wp <strong>rewrite rules</strong> to reflect our desires (you need also to update the <em>settings > permalinks</em>):</p>\n\n<pre><code>add_filter('page_rewrite_rules', 'custom_page_rewrite_rules');\n\nfunction custom_page_rewrite_rules($page_rewrite) \n{ \n // remove : john/about-me => index.php?pagename=john/about-me\n unset($page_rewrite[\"(.?.+?)(?:/([0-9]+))?/?$\"]); \n\n // add: john/about-me => index.php?pagename=john-about-me\n $page_rewrite[\"(.?.+?)/(.+?)/?$\"] = \"index.php?pagename=\\$matches[1]-\\$matches[2]\";\n\n return $page_rewrite; \n}\n\nadd_filter('post_rewrite_rules', 'custom_post_rewrite_rules'); \n\n// posts have the /%author%/%category%/%postname% permalink structure\nfunction custom_post_rewrite_rules($post_rewrite) \n{ \n // remove: john/about-me => index.php?category_name=about-me&author_name=john\n unset($post_rewrite[\"([^/]+)/(.+?)/?$\"]);\n\n return $post_rewrite; \n}\n</code></pre>\n\n<p>Last step it will be to change the value returned when the code asks for a page permalink (e.g. in menus).<br>\nTo do that we have to use the <strong>page_link</strong> filter hook (located in <em>get_page_link()</em> function defined in <em>wp-includes/link-template.php</em>)..</p>\n\n<pre><code>// http://www.example.com/john-about-me => http://www.example.com/john/about-me\nadd_filter('page_link', 'custom_page_link', 99, 3);\n\nfunction custom_page_link( $link, $ID, $sample ) \n{\n list($author, $slug) = explode(\"-\", basename($link), 2 );\n\n return ( site_url() . \"/\" . $author . \"/\" . $slug ); \n}\n</code></pre>\n\n<p>..but it won't work if you don't set to <em>false</em> the <strong>use_verbose_page_rules</strong> property of <strong>$wp_rewrite global</strong> instance; this will stop <em>parse_request()</em> to check if a \"wrong\" matched pagepath exixts: </p>\n\n<pre><code>add_action('init', 'disable_verbose_page_rule');\n\nfunction disable_verbose_page_rule()\n{\n global $wp_rewrite;\n\n $wp_rewrite->use_verbose_page_rules = false; \n}\n</code></pre>\n\n<p>That's all.. Well, to be honest this is the main part, but it will be some other work to do, like change the rewrite rules also for all the <em>attachment/comments/feed/embed</em> stuff linked to a page and may be something else that I didn't have enough time to discover.</p>\n\n<p>This is my first post; I hope it will help someone, like many others helped me.</p>\n"
}
] |
2016/05/04
|
[
"https://wordpress.stackexchange.com/questions/225642",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57849/"
] |
I need to add the author name as a subdirectory prefix for all user's posts and pages.
For example:
```
example.com/johndoe/ //The author page for John Doe
example.com/johndoe/category/test-post/ //Test post by user John Doe
example.com/johndoe/test-page/ //Test page by user John Doe
```
If I change the permalink structure to: `/%author%/%category%/%postname%/` this works fine for displaying a user's post but not a user's page.
However I'm not sure if there is something I can do in `.htaccess` or `functions.php` that will allow me to get the `pages` to work in the same manner.
I understand this can be accomplished with Multisite, however I'm trying to avoid using this because the client doesn't want to use it.
|
By the looks of it, there's a plugin to achieve exactly this, so save you rolling your own for it.
The plugin is: <https://wordpress.org/plugins/permalinks-customizer/>
I installed it to test that it does what you're looking for. Here's a screenshot that shows what you'd do:
[](https://i.stack.imgur.com/eRxHU.png)
|
225,673 |
<p>I'm not very expert of wordpress and I'm trying to create a frontend form sending information to my php function through ajax. I'd need help about uploading images and files as attachments of the post.</p>
<p>My jQuery / Ajax is sending everything correctly to my php file. The only thing I don't understand is why images are uploaded and files aren't being in the same function?</p>
<p>My html inputs are relatively named:</p>
<ul>
<li><code>name="moreimages"</code></li>
<li><code>name="morefiles"</code></li>
</ul>
<p>I use this php code for both images and files</p>
<pre><code>if ($_FILES)
{
// Get the upload images
$images = $_FILES['moreimages'];
foreach ($images['name'] as $key => $value)
{
if ($images['name'][$key])
{
$image = array(
'name' => $images['name'][$key],
'type' => $images['type'][$key],
'tmp_name' => $images['tmp_name'][$key],
'error' => $images['error'][$key],
'size' => $images['size'][$key]
);
$_FILES = array("moreimages" => $image);
foreach ($_FILES as $image => $array)
{
$newupload = project_images($image,$pid);
}
}
}
// Get the upload attachment files
$files = $_FILES['morefiles'];
foreach ($files['name'] as $key => $value)
{
if ($files['name'][$key])
{
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("morefiles" => $file);
foreach ($_FILES as $file => $array)
{
$uploadfile = project_file($file,$pid);
}
}
}
}
function project_images($file_handler, $pid)
{
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$image_id = media_handle_upload( $file_handler, $pid );
return $image_id;
}
function project_file($file_handler, $pid)
{
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$file_id = media_handle_upload( $file_handler, $pid );
//here is the only difference where I update the post meta
update_post_meta($file_id,'is_prj_file','1');
return $file_id;
}
</code></pre>
<p>I can't see the problem. Can you drive me maybe suggesting a similar question answered? Thanks.</p>
|
[
{
"answer_id": 225675,
"author": "Tim Malone",
"author_id": 46066,
"author_profile": "https://wordpress.stackexchange.com/users/46066",
"pm_score": 3,
"selected": true,
"text": "<p>I mentioned in a comment how it's important to debug your code. Here's why:</p>\n\n<p>The images are added first.\nIn the image adding section, you're running this line of code:</p>\n\n<pre><code>$_FILES = array(\"moreimages\" => $image);\n</code></pre>\n\n<p>Then when you get to your routine that adds the files, you start with this:</p>\n\n<pre><code>$files = $_FILES['morefiles'];\n</code></pre>\n\n<p>Can you see what's wrong here? At this point, <code>$_FILES</code> <em>only</em> contains <code>\"moreimages\"</code> and nothing else, because you overwrote it earlier.</p>\n\n<p>You could simply create a new variable rather than resetting <code>$_FILES</code> (eg. <code>$my_processed_images = array(\"moreimages\" => $image);</code> and then <code>foreach ($my_processed_images...</code>), but there's a lot of other things that can be done to make this code more redundant and easier to follow too.</p>\n\n<p>A quick point on debugging: <code>print_r()</code> is your friend. For example, if you're expecting a variable to be holding something, <code>print_r($_FILES)</code> so you can see if it really is. This will help avoid hours of head scratching :)</p>\n"
},
{
"answer_id": 225678,
"author": "fsenna",
"author_id": 93436,
"author_profile": "https://wordpress.stackexchange.com/users/93436",
"pm_score": 1,
"selected": false,
"text": "<p>If you are not very familiar and want a plugin that can do all that for you using drag and drop, try WP-TYPES and their CRED plugin.</p>\n\n<p>Just don't mind their support, it's really frustrating.</p>\n"
}
] |
2016/05/04
|
[
"https://wordpress.stackexchange.com/questions/225673",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92398/"
] |
I'm not very expert of wordpress and I'm trying to create a frontend form sending information to my php function through ajax. I'd need help about uploading images and files as attachments of the post.
My jQuery / Ajax is sending everything correctly to my php file. The only thing I don't understand is why images are uploaded and files aren't being in the same function?
My html inputs are relatively named:
* `name="moreimages"`
* `name="morefiles"`
I use this php code for both images and files
```
if ($_FILES)
{
// Get the upload images
$images = $_FILES['moreimages'];
foreach ($images['name'] as $key => $value)
{
if ($images['name'][$key])
{
$image = array(
'name' => $images['name'][$key],
'type' => $images['type'][$key],
'tmp_name' => $images['tmp_name'][$key],
'error' => $images['error'][$key],
'size' => $images['size'][$key]
);
$_FILES = array("moreimages" => $image);
foreach ($_FILES as $image => $array)
{
$newupload = project_images($image,$pid);
}
}
}
// Get the upload attachment files
$files = $_FILES['morefiles'];
foreach ($files['name'] as $key => $value)
{
if ($files['name'][$key])
{
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("morefiles" => $file);
foreach ($_FILES as $file => $array)
{
$uploadfile = project_file($file,$pid);
}
}
}
}
function project_images($file_handler, $pid)
{
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$image_id = media_handle_upload( $file_handler, $pid );
return $image_id;
}
function project_file($file_handler, $pid)
{
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$file_id = media_handle_upload( $file_handler, $pid );
//here is the only difference where I update the post meta
update_post_meta($file_id,'is_prj_file','1');
return $file_id;
}
```
I can't see the problem. Can you drive me maybe suggesting a similar question answered? Thanks.
|
I mentioned in a comment how it's important to debug your code. Here's why:
The images are added first.
In the image adding section, you're running this line of code:
```
$_FILES = array("moreimages" => $image);
```
Then when you get to your routine that adds the files, you start with this:
```
$files = $_FILES['morefiles'];
```
Can you see what's wrong here? At this point, `$_FILES` *only* contains `"moreimages"` and nothing else, because you overwrote it earlier.
You could simply create a new variable rather than resetting `$_FILES` (eg. `$my_processed_images = array("moreimages" => $image);` and then `foreach ($my_processed_images...`), but there's a lot of other things that can be done to make this code more redundant and easier to follow too.
A quick point on debugging: `print_r()` is your friend. For example, if you're expecting a variable to be holding something, `print_r($_FILES)` so you can see if it really is. This will help avoid hours of head scratching :)
|
225,683 |
<p>I am creating a plugin that registers a custom post type, and I want it to be displayed using the theme's page.php template, rather than the post.php. I set the <code>hierarchical</code> flag when I register it, but the post.php template is still called.</p>
<p>Way, way down inside wp-includes/post.php, where it appears to decide which template to use, is the code:</p>
<pre><code>if ( ! empty( $postarr['page_template'] ) && 'page' == $data['post_type'] ) {
$post->page_template = $postarr['page_template'];
$page_templates = wp_get_theme()->get_page_templates( $post );
...
</code></pre>
<p>which makes me think that the post template is used unless <code>post_type</code> is exactly <code>'page'</code>.</p>
<p>I don't want to define a template of my own, because I want to work with any theme. I just want to tell WordPress which of the current theme's templates to use.</p>
<p>There's an action hook, called <code>get_template_part_{$slug}</code> that might do the trick, but I'm not sure what it expects, and the documentation for that one is unusually spotty.</p>
|
[
{
"answer_id": 225684,
"author": "frogg3862",
"author_id": 83367,
"author_profile": "https://wordpress.stackexchange.com/users/83367",
"pm_score": 0,
"selected": false,
"text": "<p>That's exactly it. You should be able to use something like this, replacing the <code>your_post_type</code>:</p>\n\n<pre><code>function get_custom_post_type_template($single_template) {\n global $post;\n\n if ($post->post_type == 'your_post_type') {\n $single_template = get_stylesheet_directory_uri() . '/page.php';\n }\n return $single_template;\n}\nadd_filter( 'single_template', 'get_custom_post_type_template' );\n</code></pre>\n"
},
{
"answer_id": 225699,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 1,
"selected": false,
"text": "<p>You can filter <code>template_include</code> and then let WordPress search for a page template in all valid templates like <code>page.php</code>, <code>index.php</code> and even files from a parent theme.</p>\n\n<pre><code>add_filter( 'template_include', function( $template ) {\n return is_singular( [ 'YOUR_POST_TYPE' ] ) ? get_page_template() : $template;\n});\n</code></pre>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225683",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93443/"
] |
I am creating a plugin that registers a custom post type, and I want it to be displayed using the theme's page.php template, rather than the post.php. I set the `hierarchical` flag when I register it, but the post.php template is still called.
Way, way down inside wp-includes/post.php, where it appears to decide which template to use, is the code:
```
if ( ! empty( $postarr['page_template'] ) && 'page' == $data['post_type'] ) {
$post->page_template = $postarr['page_template'];
$page_templates = wp_get_theme()->get_page_templates( $post );
...
```
which makes me think that the post template is used unless `post_type` is exactly `'page'`.
I don't want to define a template of my own, because I want to work with any theme. I just want to tell WordPress which of the current theme's templates to use.
There's an action hook, called `get_template_part_{$slug}` that might do the trick, but I'm not sure what it expects, and the documentation for that one is unusually spotty.
|
You can filter `template_include` and then let WordPress search for a page template in all valid templates like `page.php`, `index.php` and even files from a parent theme.
```
add_filter( 'template_include', function( $template ) {
return is_singular( [ 'YOUR_POST_TYPE' ] ) ? get_page_template() : $template;
});
```
|
225,686 |
<p>I have a custom field that is an Image and the return value of the field is Image URL. </p>
<p>I have custom page templates where I render these image fields. Is there a way to get the meta info for the image through the image url. I do not want to change the return value to Image Object or Image ID. </p>
|
[
{
"answer_id": 225707,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>I can already tell that you're using ACF - if you don't want to change the return settings for the field, you can bypass ACF and just pull the image ID directly from post meta:</p>\n\n<pre><code>$image_url = get_field( 'my_field_name' );\n$image_id = get_post_meta( $post->ID, 'my_field_name', true );\n$image_meta = wp_get_attachment_metadata( $image_id );\n</code></pre>\n"
},
{
"answer_id": 226555,
"author": "essjay",
"author_id": 93528,
"author_profile": "https://wordpress.stackexchange.com/users/93528",
"pm_score": 1,
"selected": true,
"text": "<p>I needed the code in functions.php so that I could re-use it. Here's my solution below:</p>\n\n<pre><code>function get_img_alt($attachment) { \n $post = get_post();\n $image_id = get_post_meta( $post->ID, $attachment, true );\n $image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', true);\n print $image_alt;\n}\n</code></pre>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225686",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93528/"
] |
I have a custom field that is an Image and the return value of the field is Image URL.
I have custom page templates where I render these image fields. Is there a way to get the meta info for the image through the image url. I do not want to change the return value to Image Object or Image ID.
|
I needed the code in functions.php so that I could re-use it. Here's my solution below:
```
function get_img_alt($attachment) {
$post = get_post();
$image_id = get_post_meta( $post->ID, $attachment, true );
$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', true);
print $image_alt;
}
```
|
225,693 |
<p>How to add a CSS Class to <code>ul</code> and anchor element of Tag Cloud generated through <code>wp_tag_cloud</code> function?</p>
<p>I want the default class for <code>ul</code> of <code>wp-tag-cloud</code> to be <code>tag-cloud</code> and anchor tag would have <code>btn btn-xs btn-primary</code> class.</p>
<pre><code><ul class="tag-cloud">
<li><a class="btn btn-xs btn-primary" href="#">Apple</a></li>
<li><a class="btn btn-xs btn-primary" href="#">Barcelona</a></li>
<li><a class="btn btn-xs btn-primary" href="#">Ipod</a></li>
</ul>
</code></pre>
|
[
{
"answer_id": 225720,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>The classes are hardcoded in <code>wp_generate_tag_cloud()</code> function. Your only option there is to modify final string output via <code>wp_generate_tag_cloud</code> filter.</p>\n"
},
{
"answer_id": 269128,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>The tags are wrapped in a <code>DIV</code> element in the latest WordPress version the day i'm writing this answer (4.7.5), and their class is <code>tagcloud</code>, so i will move to the next thing that is asked in the question.</p>\n\n<p>The tags can be modified using the <code>wp_generate_tag_cloud</code> filter. By writing a <code>preg_replace</code> you can change the class to whatever you wish. Here is an example:</p>\n\n<pre><code>add_filter('wp_generate_tag_cloud', 'my_tag_cloud',10,1);\nfunction my_tag_cloud($string){\n return preg_replace('/class=\"tag-link-.+ tag-link-position-.+\"/', 'class=\"btn btn-xs btn-primary\"', $string);\n}\n</code></pre>\n\n<p>Anchors have the <code>tag-link-X tag-link-position-Y</code> class which X and Y are numbers.</p>\n"
},
{
"answer_id": 269135,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>We can also modify the anchor CSS class with the <a href=\"https://developer.wordpress.org/reference/hooks/wp_generate_tag_cloud_data/\" rel=\"nofollow noreferrer\"><code>wp_generate_tag_cloud_data</code></a> filter (4.3+).</p>\n\n<p>With that filter we can modify the following anchor data:</p>\n\n<ul>\n<li><code>id</code></li>\n<li><code>url</code></li>\n<li><code>role</code></li>\n<li><code>name</code></li>\n<li><code>title</code> (removed in 4.8)</li>\n<li><code>slug</code></li>\n<li><code>real_count</code></li>\n<li><code>class</code></li>\n<li><code>font_size</code></li>\n<li><code>formatted_count</code> (added in 4.8)</li>\n<li><code>aria_label</code> (added in 4.8)</li>\n<li><code>show_count</code> (added in 4.8)</li>\n</ul>\n\n<p>The style attribute is hardcoded, as can be seen from the 4.8 version:</p>\n\n<pre><code>$a[] = sprintf(\n '<a href=\"%1$s\"%2$s class=\"%3$s\" style=\"font-size: %4$s;\"%5$s>%6$s%7$s</a>',\n esc_url( $tag_data['url'] ),\n $tag_data['role'],\n esc_attr( $class ),\n esc_attr( str_replace( ',', '.', $tag_data['font_size'] ) . $args['unit'] ),\n $tag_data['aria_label'],\n esc_html( $tag_data['name'] ),\n $tag_data['show_count']\n );\n</code></pre>\n\n<p>Note that we can change the font-size <strong>unit</strong> with: </p>\n\n<pre><code>wp_tag_cloud( [ 'unit' => 'rem', 'smallest' => 1, 'largest' => 4 ] );\n</code></pre>\n\n<p>or e.g. with the <a href=\"https://developer.wordpress.org/reference/hooks/widget_tag_cloud_args/\" rel=\"nofollow noreferrer\"><code>widget_tag_cloud_args</code></a> filter for the tag cloud widgets.</p>\n\n<p><strong>Example:</strong></p>\n\n<p>Here we append the <code>btn btn-xs btn-primary</code> classes to anchors in all tag clouds:</p>\n\n<pre><code>add_filter( 'wp_generate_tag_cloud_data', function( $tag_data )\n{\n return array_map ( \n function ( $item )\n {\n $item['class'] .= ' btn btn-xs btn-primary';\n return $item;\n }, \n (array) $tag_data \n );\n\n} );\n</code></pre>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225693",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75767/"
] |
How to add a CSS Class to `ul` and anchor element of Tag Cloud generated through `wp_tag_cloud` function?
I want the default class for `ul` of `wp-tag-cloud` to be `tag-cloud` and anchor tag would have `btn btn-xs btn-primary` class.
```
<ul class="tag-cloud">
<li><a class="btn btn-xs btn-primary" href="#">Apple</a></li>
<li><a class="btn btn-xs btn-primary" href="#">Barcelona</a></li>
<li><a class="btn btn-xs btn-primary" href="#">Ipod</a></li>
</ul>
```
|
The classes are hardcoded in `wp_generate_tag_cloud()` function. Your only option there is to modify final string output via `wp_generate_tag_cloud` filter.
|
225,698 |
<p>Been pulling my hair out trying to get related articles going. I've tried a few methods but this is the only one that has given me results but random posts are shown rather than posts related to it by article.</p>
<pre><code><?php
$args=array('tag_in'=>$tags,
'exclude'=>$post->ID,
'post_per_page'=> 4,
'ignore_sticky_posts'=>1,
'post_type'=>array('ms','gnd','events','news_article','opinions','projects','tenders','videos','products'));
$rel_pst=get_posts($args);
$count = 0;
if($tags){
foreach($rel_pst as $rel):setup_postdata($rel);//Loop through and find related posts
if($count==4)
{
break;
}
$image = wp_get_attachment_image(get_post_thumbnail_id($rel->ID),'related-posts');
//$tagy=$tags[$count];
//Counts iterations to place aricles on seperate sides
if (($count == 0)||($count == 2)){// first article start
echo '<div class="posts_wrapper">';
echo '<article class="item_left">';
}
if(($count == 1)||($count == 3)){// second article start
echo'<article class="item_right">';
}
?>
<div class="pic"> <a href="<?php echo get_permalink($rel); ?>" class="w_hover img-link img-wrap"> <?php echo $image; ?></a> </div>
<h3><a href="<?php echo get_permalink($rel);?>"><?php echo get_the_title($rel); ?></a></h3>
<div class="post-info"> <a href="<?php echo get_permalink($rel);?>" class="post_date"></a> <a href="<?php echo get_permalink($rel); ?>" class="comments_count"></a> </div>
</article>
<?php
if(($count == 1)||($count == 3)){//second article/4th end
echo '</div>';
}
$count ++;
endforeach;
}
//wp_reset_postdata(); ?>
</code></pre>
<p>Any help will be appreciated</p>
|
[
{
"answer_id": 225701,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": false,
"text": "<p>Whithout knowing the value of <code>$tags</code> variable (you are not showing it to us), the only thing I see wrong in your code is the <code>tag_in</code> argumente, the correct one is <code>tag__in</code> (note the double <code>_</code>).</p>\n\n<p>Also, note that <code>tag__in</code> works with the core tag taxonomy. This taxonomy is not supported by custom post types by default, only by the standard post type.</p>\n"
},
{
"answer_id": 225706,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": true,
"text": "<p>1) It's <code>tag__in</code> (two underscores) 2) <code>get_the_tags()</code> returns an array of <em>objects</em>, you need IDs:</p>\n\n<pre><code>if ( $the_tags = get_the_tags() ) {\n // https://developer.wordpress.org/reference/functions/wp_list_pluck/\n $the_tags = wp_list_pluck( $the_tags, 'term_id' );\n}\n\n$rel_pst = get_posts( array(\n 'tag__in' => $the_tags,\n 'exclude' => $post->ID,\n 'post_per_page' => 4,\n 'ignore_sticky_posts' => true,\n 'post_type' => array(\n 'ms',\n 'gnd',\n 'events',\n 'news_article',\n 'opinions',\n 'projects',\n 'tenders',\n 'videos',\n 'products',\n ),\n));\n\nif ( $rel_pst ) {\n // Do your thing\n}\n</code></pre>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225698",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93537/"
] |
Been pulling my hair out trying to get related articles going. I've tried a few methods but this is the only one that has given me results but random posts are shown rather than posts related to it by article.
```
<?php
$args=array('tag_in'=>$tags,
'exclude'=>$post->ID,
'post_per_page'=> 4,
'ignore_sticky_posts'=>1,
'post_type'=>array('ms','gnd','events','news_article','opinions','projects','tenders','videos','products'));
$rel_pst=get_posts($args);
$count = 0;
if($tags){
foreach($rel_pst as $rel):setup_postdata($rel);//Loop through and find related posts
if($count==4)
{
break;
}
$image = wp_get_attachment_image(get_post_thumbnail_id($rel->ID),'related-posts');
//$tagy=$tags[$count];
//Counts iterations to place aricles on seperate sides
if (($count == 0)||($count == 2)){// first article start
echo '<div class="posts_wrapper">';
echo '<article class="item_left">';
}
if(($count == 1)||($count == 3)){// second article start
echo'<article class="item_right">';
}
?>
<div class="pic"> <a href="<?php echo get_permalink($rel); ?>" class="w_hover img-link img-wrap"> <?php echo $image; ?></a> </div>
<h3><a href="<?php echo get_permalink($rel);?>"><?php echo get_the_title($rel); ?></a></h3>
<div class="post-info"> <a href="<?php echo get_permalink($rel);?>" class="post_date"></a> <a href="<?php echo get_permalink($rel); ?>" class="comments_count"></a> </div>
</article>
<?php
if(($count == 1)||($count == 3)){//second article/4th end
echo '</div>';
}
$count ++;
endforeach;
}
//wp_reset_postdata(); ?>
```
Any help will be appreciated
|
1) It's `tag__in` (two underscores) 2) `get_the_tags()` returns an array of *objects*, you need IDs:
```
if ( $the_tags = get_the_tags() ) {
// https://developer.wordpress.org/reference/functions/wp_list_pluck/
$the_tags = wp_list_pluck( $the_tags, 'term_id' );
}
$rel_pst = get_posts( array(
'tag__in' => $the_tags,
'exclude' => $post->ID,
'post_per_page' => 4,
'ignore_sticky_posts' => true,
'post_type' => array(
'ms',
'gnd',
'events',
'news_article',
'opinions',
'projects',
'tenders',
'videos',
'products',
),
));
if ( $rel_pst ) {
// Do your thing
}
```
|
225,700 |
<p>I have an enqueued script called <code>custom_js</code> that loads the file <code>js/custom.js</code>. I want the file to change when a certain condition is true, but it does not seem to work. Here is my code:</p>
<pre><code>add_action('wp_print_scripts', 'my_custom_js', 11);
function my_custom_js()
{
wp_enqueue_script( 'custom_js', get_template_directory_uri().'/js/custom.js' );
if ( some condition )
{
wp_enqueue_script( 'custom_js', get_template_directory_uri().'/js/custom-2.js');
}
}
</code></pre>
<p>Enqueuing another script seems unnecessary to me; what is the best way to manipulate a script that has been enqueued? Also, it is not very clear to me - do I have to <code>register</code> custom enqueued scripts?</p>
|
[
{
"answer_id": 225702,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>The first <code>wp_enqueue_script()</code> in your code should be <code>wp_register_script()</code>. The enqueue function does the job while the register function is getting ready to do the job. </p>\n\n<p>It is always better to rather create a new js file to keep things organised. As to calling them, you can do the following</p>\n\n<pre><code>wp_register_script( 'abc', 'path_to' );\nwp_register_script( 'xyz', 'path_to' );\n\nif ( 'condition_a' ) {\n wp_enqueue_script( 'abc' );\n} else {\n wp_enqueue_script( 'xyz' );\n}\n</code></pre>\n\n<p>As to whether or not to use the <code>_register_</code> function, you can use it if you want to. When enqueueing scripts conditionaly, like above, you can use the register function to get the scripts ready for loading if they are called upon by the condition, <strong>BUT</strong>, it is not necesarry</p>\n\n<h2>EDIT</h2>\n\n<p>You can also use <code>wp_localize_script()</code> to pass PHP variables according to a certain condition to a js script, and then in your js script you can alter your script according to the value of the PHP condition</p>\n"
},
{
"answer_id": 225710,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": false,
"text": "<p>Just alter the script URL depending on the condition:</p>\n\n<pre><code>function my_custom_js() {\n $file = some_condition() ? 'custom' : 'custom-2';\n\n wp_enqueue_script(\n 'custom_js',\n get_template_directory_uri() . \"/js/$file.js\"\n /* array( 'jquery' ) */ /* dependencies, if any */\n );\n}\n\nadd_action( 'wp_enqueue_scripts', 'my_custom_js' );\n</code></pre>\n\n<p>You shouldn't be using <code>wp_print_scripts</code> - if you need the script to print after another, use the dependencies argument to specify which scripts yours requires.</p>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225700",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82468/"
] |
I have an enqueued script called `custom_js` that loads the file `js/custom.js`. I want the file to change when a certain condition is true, but it does not seem to work. Here is my code:
```
add_action('wp_print_scripts', 'my_custom_js', 11);
function my_custom_js()
{
wp_enqueue_script( 'custom_js', get_template_directory_uri().'/js/custom.js' );
if ( some condition )
{
wp_enqueue_script( 'custom_js', get_template_directory_uri().'/js/custom-2.js');
}
}
```
Enqueuing another script seems unnecessary to me; what is the best way to manipulate a script that has been enqueued? Also, it is not very clear to me - do I have to `register` custom enqueued scripts?
|
The first `wp_enqueue_script()` in your code should be `wp_register_script()`. The enqueue function does the job while the register function is getting ready to do the job.
It is always better to rather create a new js file to keep things organised. As to calling them, you can do the following
```
wp_register_script( 'abc', 'path_to' );
wp_register_script( 'xyz', 'path_to' );
if ( 'condition_a' ) {
wp_enqueue_script( 'abc' );
} else {
wp_enqueue_script( 'xyz' );
}
```
As to whether or not to use the `_register_` function, you can use it if you want to. When enqueueing scripts conditionaly, like above, you can use the register function to get the scripts ready for loading if they are called upon by the condition, **BUT**, it is not necesarry
EDIT
----
You can also use `wp_localize_script()` to pass PHP variables according to a certain condition to a js script, and then in your js script you can alter your script according to the value of the PHP condition
|
225,721 |
<p>I have the following code running in a plugin:</p>
<pre><code> add_filter('the_content','thousand_pay');
//Callback function
function thousand_pay($content)
{
echo $content;
if( !in_category( 'Stories') )
{
return;
}
?>
<hr></hr>
[Some HTML]
<?php
return
}
</code></pre>
<p>For some reason, on individual posts' pages the HTML gets printed multiple times:</p>
<p><a href="https://i.stack.imgur.com/nhaFj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nhaFj.png" alt="Bug where HTML is printed multiple times"></a></p>
<p>Can anyone think of why this would be? I read <a href="https://pippinsplugins.com/playing-nice-with-the-content-filter/" rel="noreferrer">here</a> that I might have to add to the conditional to check is_singular() and is_main_query(), so it would look like <code>if(!in_category('Stories') || !is_singular() || !is_main_query()</code>, but that just seems to stop the HTML getting printed at all on a post page. Any ideas?</p>
|
[
{
"answer_id": 225722,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 4,
"selected": true,
"text": "<p>It is normal for content to be accessed multiple times. For example SEO plugins need to do this to access it and generate meta data from.</p>\n\n<p>Also it is a <em>filter</em> hook. Filters should never echo anything to the page, they are meant to modify passed value and return it.</p>\n\n<p>If you do want to do something at that point, but only within the loop then <code>in_the_loop()</code> is condition you need.</p>\n"
},
{
"answer_id": 256881,
"author": "Eric",
"author_id": 34155,
"author_profile": "https://wordpress.stackexchange.com/users/34155",
"pm_score": 4,
"selected": false,
"text": "<p>I was having the same issue. My <code>the_content</code> filter was being called multiple times and this was slowing down page load as my <code>the_content</code> filter was calling an external API. So in my case, the API was being queried multiple times for the same data. </p>\n\n<p>I tried using <code>in_the_loop()</code>, <code>is_singular()</code> and <code>is_main_query()</code> but sometimes, depending on the theme, those failed to limit calls to my filter to one time.</p>\n\n<p>So I added a constant to my filter and that seems to have fixed the issue.</p>\n\n<p>Here's an example of how to limit your calls to the <code>the_content</code> filter to one time:</p>\n\n<pre><code>add_filter( 'the_content', 'se225721_the_content' );\n\nfunction se225721_the_content( $content ) {\n\n if ( ! in_the_loop() ) {\n return $content;\n }\n\n if ( ! is_singular() ) {\n return $content;\n }\n\n if ( ! is_main_query() ) {\n return $content;\n }\n\n $content = ucwords( $content );\n\n remove_filter( 'the_content', 'se225721_the_content' );\n\n return $content;\n}\n</code></pre>\n\n<p>Hope that helps!</p>\n\n<p>Eric</p>\n"
},
{
"answer_id": 389026,
"author": "NAbdulla",
"author_id": 207232,
"author_profile": "https://wordpress.stackexchange.com/users/207232",
"pm_score": 0,
"selected": false,
"text": "<p>I have found another way to achieve this by using the <code>did_action()</code> function and a custom action hook.</p>\n<p>Here is the solution:</p>\n<pre><code>$custom_hook = 'my_plugin_prefix_a_custom_action_hook';\nfunction my_plugin_prefi_my_filter_callback($content){\n if(did_action($custom_hook) == 0){\n do_action($custom_hook);\n //your filter action code goes here: modification of $content\n }\n return $content;\n}\n\nfunction my_plugin_prefix_custom_action_hook_callback(){\n //do nothing\n}\nadd_action($custom_hook, 'my_plugin_prefix_custom_action_hook_callback');\n</code></pre>\n<p>At first the run count of action hook <code>$custom_hook</code> will be 0 and <code>do_action($custom_hook);</code> statement will make the run count of <code>$custom_hook</code> to 1 and this will prevent subsequent execution of the body of the <code>if</code> statement.</p>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225721",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93552/"
] |
I have the following code running in a plugin:
```
add_filter('the_content','thousand_pay');
//Callback function
function thousand_pay($content)
{
echo $content;
if( !in_category( 'Stories') )
{
return;
}
?>
<hr></hr>
[Some HTML]
<?php
return
}
```
For some reason, on individual posts' pages the HTML gets printed multiple times:
[](https://i.stack.imgur.com/nhaFj.png)
Can anyone think of why this would be? I read [here](https://pippinsplugins.com/playing-nice-with-the-content-filter/) that I might have to add to the conditional to check is\_singular() and is\_main\_query(), so it would look like `if(!in_category('Stories') || !is_singular() || !is_main_query()`, but that just seems to stop the HTML getting printed at all on a post page. Any ideas?
|
It is normal for content to be accessed multiple times. For example SEO plugins need to do this to access it and generate meta data from.
Also it is a *filter* hook. Filters should never echo anything to the page, they are meant to modify passed value and return it.
If you do want to do something at that point, but only within the loop then `in_the_loop()` is condition you need.
|
225,728 |
<p>I'm putting together a basic landing page <a href="http://shurity.com/" rel="nofollow noreferrer">http://shurity.com/</a>, and in trying to clean up my code, I wanted to replace some static content with dynamic content for the user. </p>
<p>The element in question is the modal that pops up when you click subscribe...my text does not show up when I attempt to include it in the loop. The following code is a template file that matches the custom post type I created for the modal, and the post type has 3 custom fields for title, body and footer text of the modal. the_content() is pulling the actual form. </p>
<pre><code><?php
$modal_header = get_field('modal_header');
$modal_body = get_field('modal_body');
$modal_footer = get_field('modal_footer');
?>
<!-- MODAL
================================================== -->
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<?php
$args = array(
'post_type' => 'modal',
'posts_per_page' => 1
);
$loop = new WP_Query($args); ?>
<?php
if ( $loop -> have_posts() ) :
/* Start the Loop */
while ( $loop -> have_posts() ) : $loop -> the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
//get_template_part( 'template-parts/content', get_post_format() );
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel"><i class="fa fa-envelope"></i> <?php echo $modal_header; ?></h4>
</div><!-- modal-header -->
<div class="modal-body">
<p><?php echo $modal_body; ?></p>
<?php the_content(); ?>
</div><!-- modal-body -->
<hr>
<p><small><?php echo $modal_footer; ?></small></p>
<?php endwhile;
else :
get_template_part( 'template-parts/content', 'none' );
endif; ?>
<?php wp_reset_postdata(); ?>
</div><!-- modal-content -->
</div><!-- modal-dialog -->
</div><!-- modal -->
</code></pre>
<p>I am calling this template part in my footer.php. I am new to Wordpress so please excuse me if the mistake is obvious. Basically the form appears, but my three custom fields do not. This is what it looks like now..</p>
<p><a href="https://i.stack.imgur.com/e8Yqn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e8Yqn.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 225735,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 0,
"selected": false,
"text": "<p>Try the following code </p>\n\n<pre><code><?php\n/*\nTemplate Name: Template_Name\n*/\nget_header();\n$modal_header = get_field('modal_header');\n$modal_body = get_field('modal_body');\n$modal_footer = get_field('modal_footer');\necho '<pre>';print_r($modal_header);echo '</pre>'; // show the content of filed its for checking purpose.\necho '<pre>';print_r($modal_body);echo '</pre>';// show the content of filed its for checking purpose.\necho '<pre>';print_r($modal_footer);echo '</pre>';// show the content of filed its for checking purpose.\n ?>\n\n<!-- MODAL\n================================================== -->\n<div class=\"modal fade\" id=\"myModal\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n\n <?php\n $args = array(\n 'post_type' => 'modal',\n 'posts_per_page' => 1\n );\n\n $loop = new WP_Query($args); ?>\n\n\n <?php\n if ( $loop -> have_posts() ) :\n\n /* Start the Loop */\n while ( $loop -> have_posts() ) : $loop -> the_post();\n ?>\n\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>\n <h4 class=\"modal-title\" id=\"myModalLabel\"><i class=\"fa fa-envelope\"></i> <?php echo $modal_header; ?></h4>\n </div><!-- modal-header -->\n\n <div class=\"modal-body\">\n <p><?php echo $modal_body; ?></p>\n\n <?php the_content(); ?>\n </div><!-- modal-body -->\n\n <hr>\n\n <p><small><?php echo $modal_footer; ?></small></p>\n\n <?php endwhile;\n\n else :\n\n get_template_part( 'template-parts/content', 'none' );\n\n endif; ?>\n\n <?php wp_reset_postdata(); ?>\n\n </div><!-- modal-content -->\n </div><!-- modal-dialog -->\n</div><!-- modal -->\n\n<?php get_footer(); ?>\n</code></pre>\n"
},
{
"answer_id": 225742,
"author": "CZorio",
"author_id": 92793,
"author_profile": "https://wordpress.stackexchange.com/users/92793",
"pm_score": 1,
"selected": false,
"text": "<p>Answer found on Stackoverflow. Custom fields need to be called inside the loop like so...</p>\n\n<pre><code>while ( $loop -> have_posts() ) : $loop -> the_post();\n\n$modal_header = get_field('modal_header');\n$modal_body = get_field('modal_body');\n$modal_footer = get_field('modal_footer');\n\n....\n</code></pre>\n\n<p>Answer from <a href=\"http://Codeforest\" rel=\"nofollow\">Codeforest</a></p>\n"
},
{
"answer_id": 261391,
"author": "MahdiY",
"author_id": 105285,
"author_profile": "https://wordpress.stackexchange.com/users/105285",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:\n\n\n \n </p>\n\n<pre><code> <?php\n $args = array(\n 'post_type' => 'modal',\n 'posts_per_page' => 1\n );\n\n $loop = new WP_Query($args); ?>\n\n\n <?php\n if ( $loop->have_posts() ) :\n\n /* Start the Loop */\n while ( $loop->have_posts() ) : $loop->the_post();\n\n /*\n * Include the Post-Format-specific template for the content.\n * If you want to override this in a child theme, then include a file\n * called content-___.php (where ___ is the Post Format name) and that will be used instead.\n */\n //get_template_part( 'template-parts/content', get_post_format() );\n ?>\n\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>\n <h4 class=\"modal-title\" id=\"myModalLabel\"><i class=\"fa fa-envelope\"></i> <?php echo get_field('modal_header'); ?></h4>\n </div><!-- modal-header -->\n\n <div class=\"modal-body\">\n <p><?php echo get_field('modal_body'); ?></p>\n\n <?php the_content(); ?>\n </div><!-- modal-body -->\n\n <hr>\n\n <p><small><?php echo get_field('modal_footer'); ?></small></p>\n\n <?php endwhile;\n\n else :\n\n get_template_part( 'template-parts/content', 'none' );\n\n endif; ?>\n\n <?php wp_reset_postdata(); ?>\n\n </div><!-- modal-content -->\n</div><!-- modal-dialog -->\n</code></pre>\n\n<p></p>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225728",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92793/"
] |
I'm putting together a basic landing page <http://shurity.com/>, and in trying to clean up my code, I wanted to replace some static content with dynamic content for the user.
The element in question is the modal that pops up when you click subscribe...my text does not show up when I attempt to include it in the loop. The following code is a template file that matches the custom post type I created for the modal, and the post type has 3 custom fields for title, body and footer text of the modal. the\_content() is pulling the actual form.
```
<?php
$modal_header = get_field('modal_header');
$modal_body = get_field('modal_body');
$modal_footer = get_field('modal_footer');
?>
<!-- MODAL
================================================== -->
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<?php
$args = array(
'post_type' => 'modal',
'posts_per_page' => 1
);
$loop = new WP_Query($args); ?>
<?php
if ( $loop -> have_posts() ) :
/* Start the Loop */
while ( $loop -> have_posts() ) : $loop -> the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
//get_template_part( 'template-parts/content', get_post_format() );
?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel"><i class="fa fa-envelope"></i> <?php echo $modal_header; ?></h4>
</div><!-- modal-header -->
<div class="modal-body">
<p><?php echo $modal_body; ?></p>
<?php the_content(); ?>
</div><!-- modal-body -->
<hr>
<p><small><?php echo $modal_footer; ?></small></p>
<?php endwhile;
else :
get_template_part( 'template-parts/content', 'none' );
endif; ?>
<?php wp_reset_postdata(); ?>
</div><!-- modal-content -->
</div><!-- modal-dialog -->
</div><!-- modal -->
```
I am calling this template part in my footer.php. I am new to Wordpress so please excuse me if the mistake is obvious. Basically the form appears, but my three custom fields do not. This is what it looks like now..
[](https://i.stack.imgur.com/e8Yqn.png)
|
Answer found on Stackoverflow. Custom fields need to be called inside the loop like so...
```
while ( $loop -> have_posts() ) : $loop -> the_post();
$modal_header = get_field('modal_header');
$modal_body = get_field('modal_body');
$modal_footer = get_field('modal_footer');
....
```
Answer from [Codeforest](http://Codeforest)
|
225,737 |
<p>I want start saying that I'm learning and I'm trying to understand the use of <code>$_FILES</code> and <code>$file_handler</code> which are making me crazy into this function to upload attachments from a frontend form. </p>
<p>What I've discovered into mine yesterday <a href="https://wordpress.stackexchange.com/questions/225673/upload-images-and-attachments-from-frontend-form">question</a> was that using <code>$_FILES</code> into the same function makes it overwritten so some nice dude suggested to change this variable in something different like <code>$whatever</code>. Both files could be managed and uploaded then but of course this is not happening yet and <strong>only files are uploaded</strong>. Having 2 form inputs relatively named:</p>
<ul>
<li>For images: <code>name="moreimages"</code></li>
<li>For files: <code>name="morefiles"</code></li>
</ul>
<p>Basically I've arrived at this point in my php:</p>
<pre><code>if ($_FILES)
{
// Get the upload attachment files
$images = $_FILES['moreimages'];
foreach ($images['name'] as $key => $value)
{
if ($images['name'][$key])
{
$image = array(
'name' => $images['name'][$key],
'type' => $images['type'][$key],
'tmp_name' => $images['tmp_name'][$key],
'error' => $images['error'][$key],
'size' => $images['size'][$key]
);
//here I've changed the $_FILES variable into something else
$my_processed_images = array("moreimages" => $image);
foreach ($my_processed_images as $image => $array)
{
$newupload = project_images($image,$pid);
}
}
}
// Get the upload attachment files
$files = $_FILES['morefiles'];
foreach ($files['name'] as $key => $value)
{
if ($files['name'][$key])
{
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key],
'post_mime_type' => $files['type'][$key]
);
$_FILES = array("morefiles" => $file);
foreach ($_FILES as $file => $array)
{
$uploadfile = project_file($file,$pid);
}
}
}
}
</code></pre>
<p>and my functions look like</p>
<pre><code>function project_images($file_handler, $pid)
{
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$image_id = media_handle_upload( $file_handler, $pid );
return $image_id;
}
function project_file($file_handler, $pid)
{
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$file_id = media_handle_upload( $file_handler, $pid );
update_post_meta($file_id,'is_prj_file','1');
return $file_id;
}
</code></pre>
<p>I understand that there could be a problem with my <code>$file_handler</code> but I don't know how to manage it. What really is happening is that debugging the <code>$more_images</code> is null and not considered and <code>$_FILES</code> into the second loop <strong>is uploaded</strong> instead.
Can you drive me?</p>
<p><strong>EDIT</strong></p>
<p>My HTML form fields are like these for entire:</p>
<pre><code><input id="moreimages" accept="image/png, image/jpeg, image/gif" type="file" name="moreimages[]" >
<input id="morefiles" accept=".zip,.pdf,.rar,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.psd,.ai" type="file" name="morefiles[]" >
</code></pre>
<p>Furthermore My AJAX POST STATUS is OK sending these parameters for <code>moreimages</code>:</p>
<pre><code>Content-Disposition: form-data; name="moreimages[]"; filename="Screen Shot 2016-04-05 at 16.48.10.png"
Content-Type: image/png
PNG
</code></pre>
<p>and these parameters for <code>morefiles</code>:</p>
<pre><code>Content-Disposition: form-data; name="morefiles[]"; filename="articolo-slow-food-ararat.docx"
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
</code></pre>
<p>So I think the problem, once again, how these data are received into php.</p>
|
[
{
"answer_id": 225735,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 0,
"selected": false,
"text": "<p>Try the following code </p>\n\n<pre><code><?php\n/*\nTemplate Name: Template_Name\n*/\nget_header();\n$modal_header = get_field('modal_header');\n$modal_body = get_field('modal_body');\n$modal_footer = get_field('modal_footer');\necho '<pre>';print_r($modal_header);echo '</pre>'; // show the content of filed its for checking purpose.\necho '<pre>';print_r($modal_body);echo '</pre>';// show the content of filed its for checking purpose.\necho '<pre>';print_r($modal_footer);echo '</pre>';// show the content of filed its for checking purpose.\n ?>\n\n<!-- MODAL\n================================================== -->\n<div class=\"modal fade\" id=\"myModal\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n\n <?php\n $args = array(\n 'post_type' => 'modal',\n 'posts_per_page' => 1\n );\n\n $loop = new WP_Query($args); ?>\n\n\n <?php\n if ( $loop -> have_posts() ) :\n\n /* Start the Loop */\n while ( $loop -> have_posts() ) : $loop -> the_post();\n ?>\n\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>\n <h4 class=\"modal-title\" id=\"myModalLabel\"><i class=\"fa fa-envelope\"></i> <?php echo $modal_header; ?></h4>\n </div><!-- modal-header -->\n\n <div class=\"modal-body\">\n <p><?php echo $modal_body; ?></p>\n\n <?php the_content(); ?>\n </div><!-- modal-body -->\n\n <hr>\n\n <p><small><?php echo $modal_footer; ?></small></p>\n\n <?php endwhile;\n\n else :\n\n get_template_part( 'template-parts/content', 'none' );\n\n endif; ?>\n\n <?php wp_reset_postdata(); ?>\n\n </div><!-- modal-content -->\n </div><!-- modal-dialog -->\n</div><!-- modal -->\n\n<?php get_footer(); ?>\n</code></pre>\n"
},
{
"answer_id": 225742,
"author": "CZorio",
"author_id": 92793,
"author_profile": "https://wordpress.stackexchange.com/users/92793",
"pm_score": 1,
"selected": false,
"text": "<p>Answer found on Stackoverflow. Custom fields need to be called inside the loop like so...</p>\n\n<pre><code>while ( $loop -> have_posts() ) : $loop -> the_post();\n\n$modal_header = get_field('modal_header');\n$modal_body = get_field('modal_body');\n$modal_footer = get_field('modal_footer');\n\n....\n</code></pre>\n\n<p>Answer from <a href=\"http://Codeforest\" rel=\"nofollow\">Codeforest</a></p>\n"
},
{
"answer_id": 261391,
"author": "MahdiY",
"author_id": 105285,
"author_profile": "https://wordpress.stackexchange.com/users/105285",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:\n\n\n \n </p>\n\n<pre><code> <?php\n $args = array(\n 'post_type' => 'modal',\n 'posts_per_page' => 1\n );\n\n $loop = new WP_Query($args); ?>\n\n\n <?php\n if ( $loop->have_posts() ) :\n\n /* Start the Loop */\n while ( $loop->have_posts() ) : $loop->the_post();\n\n /*\n * Include the Post-Format-specific template for the content.\n * If you want to override this in a child theme, then include a file\n * called content-___.php (where ___ is the Post Format name) and that will be used instead.\n */\n //get_template_part( 'template-parts/content', get_post_format() );\n ?>\n\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>\n <h4 class=\"modal-title\" id=\"myModalLabel\"><i class=\"fa fa-envelope\"></i> <?php echo get_field('modal_header'); ?></h4>\n </div><!-- modal-header -->\n\n <div class=\"modal-body\">\n <p><?php echo get_field('modal_body'); ?></p>\n\n <?php the_content(); ?>\n </div><!-- modal-body -->\n\n <hr>\n\n <p><small><?php echo get_field('modal_footer'); ?></small></p>\n\n <?php endwhile;\n\n else :\n\n get_template_part( 'template-parts/content', 'none' );\n\n endif; ?>\n\n <?php wp_reset_postdata(); ?>\n\n </div><!-- modal-content -->\n</div><!-- modal-dialog -->\n</code></pre>\n\n<p></p>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225737",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92398/"
] |
I want start saying that I'm learning and I'm trying to understand the use of `$_FILES` and `$file_handler` which are making me crazy into this function to upload attachments from a frontend form.
What I've discovered into mine yesterday [question](https://wordpress.stackexchange.com/questions/225673/upload-images-and-attachments-from-frontend-form) was that using `$_FILES` into the same function makes it overwritten so some nice dude suggested to change this variable in something different like `$whatever`. Both files could be managed and uploaded then but of course this is not happening yet and **only files are uploaded**. Having 2 form inputs relatively named:
* For images: `name="moreimages"`
* For files: `name="morefiles"`
Basically I've arrived at this point in my php:
```
if ($_FILES)
{
// Get the upload attachment files
$images = $_FILES['moreimages'];
foreach ($images['name'] as $key => $value)
{
if ($images['name'][$key])
{
$image = array(
'name' => $images['name'][$key],
'type' => $images['type'][$key],
'tmp_name' => $images['tmp_name'][$key],
'error' => $images['error'][$key],
'size' => $images['size'][$key]
);
//here I've changed the $_FILES variable into something else
$my_processed_images = array("moreimages" => $image);
foreach ($my_processed_images as $image => $array)
{
$newupload = project_images($image,$pid);
}
}
}
// Get the upload attachment files
$files = $_FILES['morefiles'];
foreach ($files['name'] as $key => $value)
{
if ($files['name'][$key])
{
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key],
'post_mime_type' => $files['type'][$key]
);
$_FILES = array("morefiles" => $file);
foreach ($_FILES as $file => $array)
{
$uploadfile = project_file($file,$pid);
}
}
}
}
```
and my functions look like
```
function project_images($file_handler, $pid)
{
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$image_id = media_handle_upload( $file_handler, $pid );
return $image_id;
}
function project_file($file_handler, $pid)
{
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$file_id = media_handle_upload( $file_handler, $pid );
update_post_meta($file_id,'is_prj_file','1');
return $file_id;
}
```
I understand that there could be a problem with my `$file_handler` but I don't know how to manage it. What really is happening is that debugging the `$more_images` is null and not considered and `$_FILES` into the second loop **is uploaded** instead.
Can you drive me?
**EDIT**
My HTML form fields are like these for entire:
```
<input id="moreimages" accept="image/png, image/jpeg, image/gif" type="file" name="moreimages[]" >
<input id="morefiles" accept=".zip,.pdf,.rar,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.psd,.ai" type="file" name="morefiles[]" >
```
Furthermore My AJAX POST STATUS is OK sending these parameters for `moreimages`:
```
Content-Disposition: form-data; name="moreimages[]"; filename="Screen Shot 2016-04-05 at 16.48.10.png"
Content-Type: image/png
PNG
```
and these parameters for `morefiles`:
```
Content-Disposition: form-data; name="morefiles[]"; filename="articolo-slow-food-ararat.docx"
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
```
So I think the problem, once again, how these data are received into php.
|
Answer found on Stackoverflow. Custom fields need to be called inside the loop like so...
```
while ( $loop -> have_posts() ) : $loop -> the_post();
$modal_header = get_field('modal_header');
$modal_body = get_field('modal_body');
$modal_footer = get_field('modal_footer');
....
```
Answer from [Codeforest](http://Codeforest)
|
225,747 |
<p>I'm using <code>the_excerpt()</code> in my template loop to display post excerpt on the front page.</p>
<p>It's currently displaying unwanted shortcode directly on the front page</p>
<p>eg.</p>
<p><code>[box]post content[/box]</code></p>
<p><code>[alert]post content[/alert]</code></p>
<p>How can I filter out these shortcode only while keeping the actual content?</p>
|
[
{
"answer_id": 225751,
"author": "Shoeb Mirza",
"author_id": 36797,
"author_profile": "https://wordpress.stackexchange.com/users/36797",
"pm_score": 1,
"selected": false,
"text": "<pre class=\"lang-php prettyprint-override\"><code>function wpsesess_ddecode_excerpt( $excerpt )\n{\n return strip_shortcodes( $excerpt );\n}\nadd_filter( 'the_excerpt', 'wpsesess_ddecode_excerpt' );\n</code></pre>\n\n<p><strong>EDIT</strong> Can you please post this in functions.php and let me know?</p>\n"
},
{
"answer_id": 225763,
"author": "fsenna",
"author_id": 93436,
"author_profile": "https://wordpress.stackexchange.com/users/93436",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>$excerpt = $post->post_excerpt;\n$excerpt = apply_filters('the_content', $excerpt);\necho $excerpt;\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>$excerpt = $post->post_excerpt;\n$excerpt = apply_filters('the_excerpt', $excerpt);\necho $excerpt;\n</code></pre>\n"
},
{
"answer_id": 225766,
"author": "user5200704",
"author_id": 92477,
"author_profile": "https://wordpress.stackexchange.com/users/92477",
"pm_score": 3,
"selected": true,
"text": "<p>try this</p>\n\n<pre><code>add_filter( 'get_the_excerpt', 'strip_shortcodes', 20 );\n</code></pre>\n\n<p>or try this edit</p>\n\n<pre><code>echo strip_shortcodes( get_the_excerpt() );\n</code></pre>\n\n<p>if shortcode is not register with wordpress function add_shortcode </p>\n\n<pre><code>add_filter( 'the_excerpt', 'remove_shortcodes_in_excerpt', 20 );\n\nfunction remove_shortcodes_in_excerpt( $content){\n $content = strip_shortcodes($content);\n $tagnames = array('box', 'alert'); // add shortcode tag name [box]content[/box] tagname = box\n $content = do_shortcodes_in_html_tags( $content, true, $tagnames );\n\n $pattern = get_shortcode_regex( $tagnames );\n $content = preg_replace_callback( \"/$pattern/\", 'strip_shortcode_tag', $content );\n return $content;\n}\n</code></pre>\n"
},
{
"answer_id": 225780,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>Since your new theme doesn't register the shortcodes they're regarded as plain text. Any attempt at filtering is useless, because as far as WordPress is concerned they aren't shortcodes.</p>\n\n<p>The easiest way to solve this is to register the shortcodes in your new theme and hook them to an action that does nothing besides removing the shortcode.</p>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225747",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92505/"
] |
I'm using `the_excerpt()` in my template loop to display post excerpt on the front page.
It's currently displaying unwanted shortcode directly on the front page
eg.
`[box]post content[/box]`
`[alert]post content[/alert]`
How can I filter out these shortcode only while keeping the actual content?
|
try this
```
add_filter( 'get_the_excerpt', 'strip_shortcodes', 20 );
```
or try this edit
```
echo strip_shortcodes( get_the_excerpt() );
```
if shortcode is not register with wordpress function add\_shortcode
```
add_filter( 'the_excerpt', 'remove_shortcodes_in_excerpt', 20 );
function remove_shortcodes_in_excerpt( $content){
$content = strip_shortcodes($content);
$tagnames = array('box', 'alert'); // add shortcode tag name [box]content[/box] tagname = box
$content = do_shortcodes_in_html_tags( $content, true, $tagnames );
$pattern = get_shortcode_regex( $tagnames );
$content = preg_replace_callback( "/$pattern/", 'strip_shortcode_tag', $content );
return $content;
}
```
|
225,760 |
<p>I'm trying to fire some code only when a document type is created using save_post, but $update is always true, even when first publishing it.</p>
<p>I assume this is because there's an autodraft created first. Is there any way around this?</p>
|
[
{
"answer_id": 225764,
"author": "fsenna",
"author_id": 93436,
"author_profile": "https://wordpress.stackexchange.com/users/93436",
"pm_score": 1,
"selected": false,
"text": "<p>One approach is to use get_post_status()</p>\n\n<p>According to the codex <a href=\"http://codex.wordpress.org/Function_Reference/get_post_status\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/get_post_status</a></p>\n\n<pre><code>'publish' - A published post or page\n'pending' - post is pending review\n'draft' - a post in draft status\n'auto-draft' - a newly created post, with no content\n'future' - a post to publish in the future\n'private' - not visible to users who are not logged in\n'inherit' - a revision. see get_children.\n'trash' - post is in trashbin. added with Version 2.9.\n</code></pre>\n\n<p>Possibly in your code the status is auto-draft or draft. If the status is true for both, it's probably the first save. If not, it's an update.</p>\n"
},
{
"answer_id": 225822,
"author": "SinisterBeard",
"author_id": 63673,
"author_profile": "https://wordpress.stackexchange.com/users/63673",
"pm_score": 0,
"selected": false,
"text": "<p>A more reliable way of checking is to get <code>$_POST['original_publish']</code>, as that will return 'Publish' on first publishing it, and 'Update' on updating it.</p>\n"
},
{
"answer_id": 236064,
"author": "Alex Baulch",
"author_id": 38696,
"author_profile": "https://wordpress.stackexchange.com/users/38696",
"pm_score": 4,
"selected": true,
"text": "<p>So appreciate this is a bit late but I was having the exact same issue, the $update parameter is almost completely useless if you want to check whether it is a new post or not.</p>\n\n<p>The way I got around this was to compare the <code>$post->post_date</code> with <code>$post->post_modified</code>. Full code snippet below.</p>\n\n<pre><code>add_action( 'save_post', 'save_post_callback', 10, 3 );\n\nfunction save_post_callback($post_id, $post, $update) {\n $is_new = $post->post_date === $post->post_modified;\n if ( $is_new ) {\n // first publish\n } else {\n // an update\n }\n}\n</code></pre>\n\n<p>Hope that helps anybody else finding this.</p>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225760",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63673/"
] |
I'm trying to fire some code only when a document type is created using save\_post, but $update is always true, even when first publishing it.
I assume this is because there's an autodraft created first. Is there any way around this?
|
So appreciate this is a bit late but I was having the exact same issue, the $update parameter is almost completely useless if you want to check whether it is a new post or not.
The way I got around this was to compare the `$post->post_date` with `$post->post_modified`. Full code snippet below.
```
add_action( 'save_post', 'save_post_callback', 10, 3 );
function save_post_callback($post_id, $post, $update) {
$is_new = $post->post_date === $post->post_modified;
if ( $is_new ) {
// first publish
} else {
// an update
}
}
```
Hope that helps anybody else finding this.
|
225,772 |
<p>Help me figure out how to structure this meta_query within my post query!</p>
<p>There are two taxonomies attached to my post type ('audition_type', and 'union_requirement'). On a page of my site the user is able to use checkboxes to filter a query of the post type ('audition'). The below meta_query is working fine to get all posts that are in the terms that the user selects but it's not quite right.
I need it to return all the posts that match ANY of the terms selected in the 'audition_type' taxonomy and then narrow it down further by only getting posts that have the selected 'union_requirement' terms selected .
So, almost like a query within a query. That's where I can't quite figure out the logic.</p>
<pre><code>'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'audition_type',
'value' => $typeIDs,
),
array(
'key' => 'union_requirement',
'value' => $unionIDs
)
),
</code></pre>
<p><code>$typeIDs</code> and <code>$unionIDs</code> variables are arrays containing the term IDs if that wasn't obvious.</p>
|
[
{
"answer_id": 225817,
"author": "amit singh",
"author_id": 81713,
"author_profile": "https://wordpress.stackexchange.com/users/81713",
"pm_score": -1,
"selected": false,
"text": "<p>Try this code, meta query will not give you the results you want. Please go through the meta query for more details.\n<a href=\"https://codex.wordpress.org/Class_Reference/WP_Meta_Query\" rel=\"nofollow\">Meta query</a>\nOr go <a href=\"https://cheekymonkeymedia.ca/blog/using-wordpress-to-query-multiple-taxonomies\" rel=\"nofollow\">here</a> for reference.</p>\n\n<pre><code><?php \n$myquery = array(\n 'numberposts'=>-1,\n 'tax_query' => array(\n 'relation' => 'OR',\n array(\n 'taxonomy' => 'audition_type',\n 'terms' => $typeIDs\n ),\n array(\n 'taxonomy' => 'union_requirement',\n 'terms' => $unionIDs\n ),\n ),\n );\nquery_posts($myquery);\n</code></pre>\n\n<p>?></p>\n"
},
{
"answer_id": 225866,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>If I follow your description right you want posts which have <em>any</em> <code>$typeIDs</code>, but <em>all</em> of <code>$unionIDs</code> ?</p>\n\n<p>Aside from wrong <code>meta_query</code> choice, you miss <code>operator</code> argument which specifies which kind of match you want.</p>\n\n<p>I think your query should be something like this:</p>\n\n<pre><code>'tax_query' => array(\n 'relation' => 'AND', // you want both conditions to match\n array(\n 'taxonomy' => 'audition_type',\n 'terms' => $typeIDs,\n 'operator' => 'IN', // this is default, just showing you difference\n ),\n array(\n 'taxonomy' => 'union_requirement',\n 'terms' => $unionIDs,\n 'operator' => 'AND', // not default, we want matches to all terms\n )\n),\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow\">Taxonomy Parameters in Codex</a> for further documentation.</p>\n"
},
{
"answer_id": 226036,
"author": "Eckstein",
"author_id": 23492,
"author_profile": "https://wordpress.stackexchange.com/users/23492",
"pm_score": 1,
"selected": true,
"text": "<p>Sorry for the delay on this everyone, I was out of town! \nHere is what I figured out and am using today. I had to check for the cases where one taxonomy was selected and one was not, which actually only requires a simple tax query, but that was giving me null values and breaking the query, so I had to use some conditionals instead to build it.</p>\n\n<p>$typeIDs and $unionsIDs are arrays of taxonomies that are selected.</p>\n\n<p>Thanks for your suggestions!</p>\n\n<pre><code>//Set the proper tax_query based on what we're looking for\nif ($typeIDs && $unionIDs) {\n $args['tax_query'] = array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'audition_type',\n 'field' => 'term_id',\n 'terms' => $typeIDs,\n ),\n array(\n 'taxonomy' => 'union_requirement',\n 'field' => 'term_id',\n 'terms' => $unionIDs,\n 'operator' => 'AND'\n )\n );\n} elseif ($typeIDs) {\n $args['tax_query'] = array(\n array(\n 'taxonomy' => 'audition_type',\n 'field' => 'term_id',\n 'terms' => $typeIDs,\n )\n );\n} else if ($unionIDs) {\n $args['tax_query'] = array(\n array(\n 'taxonomy' => 'union_requirement',\n 'field' => 'term_id',\n 'terms' => $unionIDs,\n )\n );\n} else {\n $args['tax_query'] = false;\n}\n</code></pre>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225772",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23492/"
] |
Help me figure out how to structure this meta\_query within my post query!
There are two taxonomies attached to my post type ('audition\_type', and 'union\_requirement'). On a page of my site the user is able to use checkboxes to filter a query of the post type ('audition'). The below meta\_query is working fine to get all posts that are in the terms that the user selects but it's not quite right.
I need it to return all the posts that match ANY of the terms selected in the 'audition\_type' taxonomy and then narrow it down further by only getting posts that have the selected 'union\_requirement' terms selected .
So, almost like a query within a query. That's where I can't quite figure out the logic.
```
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'audition_type',
'value' => $typeIDs,
),
array(
'key' => 'union_requirement',
'value' => $unionIDs
)
),
```
`$typeIDs` and `$unionIDs` variables are arrays containing the term IDs if that wasn't obvious.
|
Sorry for the delay on this everyone, I was out of town!
Here is what I figured out and am using today. I had to check for the cases where one taxonomy was selected and one was not, which actually only requires a simple tax query, but that was giving me null values and breaking the query, so I had to use some conditionals instead to build it.
$typeIDs and $unionsIDs are arrays of taxonomies that are selected.
Thanks for your suggestions!
```
//Set the proper tax_query based on what we're looking for
if ($typeIDs && $unionIDs) {
$args['tax_query'] = array(
'relation' => 'AND',
array(
'taxonomy' => 'audition_type',
'field' => 'term_id',
'terms' => $typeIDs,
),
array(
'taxonomy' => 'union_requirement',
'field' => 'term_id',
'terms' => $unionIDs,
'operator' => 'AND'
)
);
} elseif ($typeIDs) {
$args['tax_query'] = array(
array(
'taxonomy' => 'audition_type',
'field' => 'term_id',
'terms' => $typeIDs,
)
);
} else if ($unionIDs) {
$args['tax_query'] = array(
array(
'taxonomy' => 'union_requirement',
'field' => 'term_id',
'terms' => $unionIDs,
)
);
} else {
$args['tax_query'] = false;
}
```
|
225,774 |
<p>I'm loading a custom script file using an enqueue and here's the output:</p>
<p><code><script type='text/javascript' src='.../wp-content/themes/enfold-child/js/custom_script.js?ver=4.5.1'></script></code></p>
<p>curious why it's appending that "?ver=4.5.1" at end. When I remove in console file loads fine, but when it's there blank file. Not sure if that's a caching thing or I should be loading some other way. Here's my enqueue code:</p>
<pre><code>add_action('wp_enqueue_scripts','enqueue_our_required_stylesheets');
function my_scripts_method() {
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/js/custom_script.js',
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
</code></pre>
|
[
{
"answer_id": 225776,
"author": "Jarod Thornton",
"author_id": 44017,
"author_profile": "https://wordpress.stackexchange.com/users/44017",
"pm_score": 4,
"selected": true,
"text": "<p>I agree with @Mark Kaplun - what you're describing is an odd behavior though. Try this markup to override the <code>$ver</code> param. </p>\n\n<p><code>wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), null, true);</code></p>\n\n<p><a href=\"https://developer.wordpress.org/themes/basics/including-css-javascript/\" rel=\"noreferrer\">https://developer.wordpress.org/themes/basics/including-css-javascript/</a></p>\n\n<p>Alternatively, to work around the version cache try this markup which will generate a unique version with each page load.</p>\n\n<p><code>wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), rand(1, 100), true);</code></p>\n"
},
{
"answer_id": 225777,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You should always specify a version number for you scripts/css when you enqueue them, otherwise when you change them on the server they might not be changed for the user because some caching proxy in the middle cached it and keep serving it.</p>\n\n<p>If you don't specify one, wordpress will attach its own version number to the url as the <code>ver</code> parameter, but frankly IMO this behavior is more of a bug then a feature, since obviously wordpress upgrade almost never align with changes you are doing in your JS/CSS.</p>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225774",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54953/"
] |
I'm loading a custom script file using an enqueue and here's the output:
`<script type='text/javascript' src='.../wp-content/themes/enfold-child/js/custom_script.js?ver=4.5.1'></script>`
curious why it's appending that "?ver=4.5.1" at end. When I remove in console file loads fine, but when it's there blank file. Not sure if that's a caching thing or I should be loading some other way. Here's my enqueue code:
```
add_action('wp_enqueue_scripts','enqueue_our_required_stylesheets');
function my_scripts_method() {
wp_enqueue_script(
'custom-script',
get_stylesheet_directory_uri() . '/js/custom_script.js',
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
```
|
I agree with @Mark Kaplun - what you're describing is an odd behavior though. Try this markup to override the `$ver` param.
`wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), null, true);`
<https://developer.wordpress.org/themes/basics/including-css-javascript/>
Alternatively, to work around the version cache try this markup which will generate a unique version with each page load.
`wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), rand(1, 100), true);`
|
225,783 |
<p>On my site I have a number of post category archive pages. What I would like to do is set it up so that when links to specific posts are clicked on these pages the user is sent to the post only if they are logged in. Otherwise they would be sent to the login/sign up page.</p>
<p>I don't want the articles themselves to be restricted, meaning if somebody found a link outside my site to the post they would be able to view it without logging in. I only want access restricted when the user is coming directly from an internal archive page.</p>
<p>Thank you for your help.</p>
|
[
{
"answer_id": 225785,
"author": "LPH",
"author_id": 47326,
"author_profile": "https://wordpress.stackexchange.com/users/47326",
"pm_score": 2,
"selected": false,
"text": "<p>You might start by looking at the <code>is_user_logged_in()</code> pluggable function.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/is_user_logged_in/</a></p>\n\n<p>This is basically two lines:</p>\n\n<pre><code>$user = wp_get_current_user();\nreturn $user->exists();\n</code></pre>\n\n<p>In your case, wrap the links inside the curly braces of a conditional.</p>\n\n<pre><code>if ( is_user_logged_in() ) {\n\n // link\n}\n</code></pre>\n"
},
{
"answer_id": 225798,
"author": "figureout25",
"author_id": 93578,
"author_profile": "https://wordpress.stackexchange.com/users/93578",
"pm_score": 1,
"selected": false,
"text": "<p>I've worked it out with thanks to LPH for pointing me in the right direction.</p>\n\n<p>I added this to functions.php:</p>\n\n<pre><code>function login_page_url() {\n global $loginurl;\n $loginurl = \"login page url\";\n echo $loginurl;\n}\n</code></pre>\n\n<p>And this to category.php, where the link to the post goes:</p>\n\n<pre><code><a href=\"<?php if ( is_user_logged_in() ) { echo get_permalink(); } else { echo login_page_url(); } ?>\">\n</code></pre>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225783",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93578/"
] |
On my site I have a number of post category archive pages. What I would like to do is set it up so that when links to specific posts are clicked on these pages the user is sent to the post only if they are logged in. Otherwise they would be sent to the login/sign up page.
I don't want the articles themselves to be restricted, meaning if somebody found a link outside my site to the post they would be able to view it without logging in. I only want access restricted when the user is coming directly from an internal archive page.
Thank you for your help.
|
You might start by looking at the `is_user_logged_in()` pluggable function.
<https://developer.wordpress.org/reference/functions/is_user_logged_in/>
This is basically two lines:
```
$user = wp_get_current_user();
return $user->exists();
```
In your case, wrap the links inside the curly braces of a conditional.
```
if ( is_user_logged_in() ) {
// link
}
```
|
225,802 |
<p>I was making a plugin and I have a javascript file where I want to take some options saved in the database to show well the function.</p>
<p>So I have this:</p>
<pre><code>function wp_home(){
wp_enqueue_script( 'some-name-1', '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js', '1.0.0', true );
wp_enqueue_style( 'some-name-2', plugins_url( 'assets/jquery.something.css', __FILE__ ) );
wp_enqueue_script( 'some-name-3', plugins_url( 'assets/jquery.something.js', __FILE__ ), '1.0.0', true );
global $table_prefix;
$dbh = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
$table = $table_prefix.'options';
$qd = "SELECT option_value FROM $table WHERE option_name = 'description'";
$description = $dbh->get_results( $query_link );
$description = $description[0]->option_value;
//HERE I HAVE THE STRING OF $description AND I WANT TO PASS INSIDE TO CUSTOM-JS-PHP
wp_enqueue_script( 'custom-name-js', plugins_url( 'assets/custom-js.php', __FILE__ ), '1.0.0', true );
}
</code></pre>
<p>The file custom-js.php it's like this:</p>
<pre><code> <?php header("Content-type: text/javascript"); ?>
$(document).ready(function(){
$.showBox({
message: '<?php echo $description; ?>',
});
});
</code></pre>
<p>How I can take the $description? If I put the javascript inside wp_home() it doesn't work.</p>
<p>Thanks</p>
|
[
{
"answer_id": 225804,
"author": "Manu",
"author_id": 22963,
"author_profile": "https://wordpress.stackexchange.com/users/22963",
"pm_score": 2,
"selected": false,
"text": "<p>You can try this function: <code>wp_localize_script( $handle, $name, $data );</code></p>\n\n<p>See <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/wp_localize_script</a> for documentation.</p>\n\n<p>As the codex says: </p>\n\n<blockquote>\n <p>Though localization is the primary use, it can be used to make any data available to your script that you can normally only get from the server side of WordPress.</p>\n</blockquote>\n\n<p>I had to use it for translation / localization, but it looks like it can help you \"inject\" your dynamic value into the javascript.</p>\n"
},
{
"answer_id": 225805,
"author": "Andrew Bartel",
"author_id": 17879,
"author_profile": "https://wordpress.stackexchange.com/users/17879",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\">wp_localize_script()</a> to pass php variables to javascript. You create an array in php and then pass it to the function as the third parameter. It will come through as an object you name with the second parameter.</p>\n\n<p>First, register the script.</p>\n\n<p><code>wp_register_script( 'custom-name-js', plugins_url( 'assets/custom-js.php', __FILE__ ) );</code></p>\n\n<p>Second, build your array and run wp_localize.</p>\n\n<pre><code>$my_array = array( 'description' => $description[0]->option_value );\nwp_localize_script( 'custom-name-js', 'js_object_name', $my_array );\n</code></pre>\n\n<p>Finally, you enqueue your script.</p>\n\n<pre><code>wp_enqueue_script( 'custom-name-js' );\n</code></pre>\n\n<p>Then, in your js file, you will have a js object available named js_object_name (or whatever you pass as the second parameter to wp_localize_script) with a property of description.</p>\n\n<pre><code>js_object_name.description\n</code></pre>\n"
}
] |
2016/05/05
|
[
"https://wordpress.stackexchange.com/questions/225802",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81402/"
] |
I was making a plugin and I have a javascript file where I want to take some options saved in the database to show well the function.
So I have this:
```
function wp_home(){
wp_enqueue_script( 'some-name-1', '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js', '1.0.0', true );
wp_enqueue_style( 'some-name-2', plugins_url( 'assets/jquery.something.css', __FILE__ ) );
wp_enqueue_script( 'some-name-3', plugins_url( 'assets/jquery.something.js', __FILE__ ), '1.0.0', true );
global $table_prefix;
$dbh = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
$table = $table_prefix.'options';
$qd = "SELECT option_value FROM $table WHERE option_name = 'description'";
$description = $dbh->get_results( $query_link );
$description = $description[0]->option_value;
//HERE I HAVE THE STRING OF $description AND I WANT TO PASS INSIDE TO CUSTOM-JS-PHP
wp_enqueue_script( 'custom-name-js', plugins_url( 'assets/custom-js.php', __FILE__ ), '1.0.0', true );
}
```
The file custom-js.php it's like this:
```
<?php header("Content-type: text/javascript"); ?>
$(document).ready(function(){
$.showBox({
message: '<?php echo $description; ?>',
});
});
```
How I can take the $description? If I put the javascript inside wp\_home() it doesn't work.
Thanks
|
You can use [wp\_localize\_script()](https://codex.wordpress.org/Function_Reference/wp_localize_script) to pass php variables to javascript. You create an array in php and then pass it to the function as the third parameter. It will come through as an object you name with the second parameter.
First, register the script.
`wp_register_script( 'custom-name-js', plugins_url( 'assets/custom-js.php', __FILE__ ) );`
Second, build your array and run wp\_localize.
```
$my_array = array( 'description' => $description[0]->option_value );
wp_localize_script( 'custom-name-js', 'js_object_name', $my_array );
```
Finally, you enqueue your script.
```
wp_enqueue_script( 'custom-name-js' );
```
Then, in your js file, you will have a js object available named js\_object\_name (or whatever you pass as the second parameter to wp\_localize\_script) with a property of description.
```
js_object_name.description
```
|
225,867 |
<p>Hey so I am trying to create this conditional that auto creates a grid layout when widgets/sidebars are added and removed. The goal is let the user put in as many widgets as possible without worrying about the layout.
This is my code, let me know if you want me to further explain myself:</p>
<pre><code>if (function_exists('create_widget') && dynamic_sidebar('sidebar-1') && dynamic_sidebar('sidebar-2') && dynamic_sidebar('sidebar-3') ) {
$layout_classes = "col-md-4";
} elseif ( is_active_sidebar( 'sidebar-1' ) && is_active_sidebar( 'sidebar-2' ) ) {
$layout_classes = "col-md-6";
} else {
$layout_classes = "col-md-2";
}
<div class="row"
<div class="container">
<div class="col-md-12">
<div class="<?php echo $layout_classes ?>">
<?php dynamic_sidebar( 'sidebar-1'); ?>
<?php dynamic_sidebar( 'sidebar-2'); ?>
<?php dynamic_sidebar( 'sidebar-3'); ?>
</div>
</div>
</div>
</div><!--End Layout Class-->
</code></pre>
<p>P.S. Using Bootstrap 3.</p>
|
[
{
"answer_id": 225868,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>You haven't actually said what the problem is. But I can see one for starters - <code>dynamic_sidebar</code> in your <code>if</code> conditions will echo out the widgets immediately. If you want to <em>check</em> a sidebar has widgets, use <a href=\"https://developer.wordpress.org/reference/functions/is_active_sidebar/\" rel=\"nofollow\"><code>is_active_sidebar</code></a>:</p>\n\n<pre><code>is_active_sidebar( 'sidebar-1' ); // True/false\n</code></pre>\n"
},
{
"answer_id": 272265,
"author": "MikeiLL",
"author_id": 48604,
"author_profile": "https://wordpress.stackexchange.com/users/48604",
"pm_score": 0,
"selected": false,
"text": "<p>There is an answer <a href=\"https://wordpress.stackexchange.com/a/116112/48604\">here</a>, but it relies on <a href=\"https://developer.wordpress.org/reference/functions/wp_get_sidebars_widgets/\" rel=\"nofollow noreferrer\">wp_get_sidebars_widgets</a>, which is depreciated as well as private.</p>\n\n<p><a href=\"https://generatewp.com/snippet/2V0V0gy/\" rel=\"nofollow noreferrer\">This code</a> looks like a better and more robust solution:</p>\n\n<p>It's actually pretty simple. I used it to add classes to my widget's for <a href=\"https://purecss.io/\" rel=\"nofollow noreferrer\">PureCSS</a> framework.</p>\n\n<p>In this case we want the outer container to have the class <code>pure-g</code> for the \"grid\". And the inner items to have the class of <code>pure-u-1-*</code>, where the asterisk is the total number of columns, in this case the widget count. </p>\n\n<p>So registering the sidebar:</p>\n\n<pre><code>register_sidebar([\n 'name' => __('Footer Widget Area', 'pure-demo'),\n 'id' => 'sidebar-footer',\n 'class' => 'pure-g',\n // Next line has our callback\n 'before_widget' => '<section class=\"widget %2$s '. slbd_count_widgets( 'sidebar-footer' ) .'\">',\n 'after_widget' => '</section>',\n 'before_title' => '<h3>',\n 'after_title' => '</h3>'\n]);\n</code></pre>\n\n<p>And here's our callback function:</p>\n\n<pre><code> function slbd_count_widgets( $sidebar_id ) {\n // If loading from front page, consult $_wp_sidebars_widgets rather than options\n // to see if wp_convert_widget_settings() has made manipulations in memory.\n global $_wp_sidebars_widgets;\n if ( empty( $_wp_sidebars_widgets ) ) :\n $_wp_sidebars_widgets = get_option( 'sidebars_widgets', array() );\n endif;\n\n $sidebars_widgets_count = $_wp_sidebars_widgets;\n\n if ( isset( $sidebars_widgets_count[ $sidebar_id ] ) ) :\n $widget_count = count( $sidebars_widgets_count[ $sidebar_id ] );\n $widget_classes = '';\n $widget_classes .= 'pure-u-1 pure-u-sm-1-1';\n $widget_classes .= ' pure-u-md-1-' . ceil($widget_count / 2);\n $widget_classes .= ' pure-u-lg-1-' . $widget_count;\n return $widget_classes;\n endif;\n}\n</code></pre>\n\n<p>Then I display it like this:</p>\n\n<pre><code><footer class=\"content-info pure-g\">\n <?php if ( is_active_sidebar( 'sidebar-footer' ) ) : ?>\n <?php dynamic_sidebar( 'sidebar-footer' ); ?>\n <?php endif; ?>\n <div id=\"colophon\" class=\"site-footer\" role=\"contentinfo\">\n <?php\n if ( has_nav_menu( 'footer_links' ) ) :\n wp_nav_menu(['theme_location' => 'footer_links', 'container_class' => 'pure-menu', 'menu_class' => 'pure-menu-list']);\n endif;\n ?>\n </div>\n</footer>\n</code></pre>\n"
},
{
"answer_id": 351274,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 0,
"selected": false,
"text": "<p>This is an example of adding a custom class to the Widgets Text field:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'dynamic_sidebar_params', [ new Sidebar_Filterer, 'filter' ], 10, 1 );\n\nclass Sidebar_Filterer {\n\n /**\n * @filter dynamic_sidebar_params 10 1\n *\n * @param $param\n *\n * @return mixed\n */\n public function filter( $params ) {\n if ( ! is_array( $params ) || empty( $params ) ) {\n return $params;\n }\n\n foreach ( $params as &$param ) {\n if ( is_array( $param ) ) {\n $param = $this->filter_text_widget( $param );\n }\n }\n\n return $params;\n }\n\n private function filter_text_widget( array $param ): array {\n if ( ! array_key_exists( 'widget_name', $param ) ) {\n return $param;\n }\n\n if ( $param['widget_name'] != 'Text' ) {\n return $param;\n }\n\n if ( ! array_key_exists( 'before_widget', $param ) ) {\n return $param;\n }\n\n if ( strpos( $param['before_widget'], 'widget_text' ) === false ) {\n return $param;\n }\n\n $param['before_widget'] = str_replace( 'widget_text', 'widget_text some-other-class', $param['before_widget'] );\n\n return $param;\n }\n}\n</code></pre>\n"
}
] |
2016/05/06
|
[
"https://wordpress.stackexchange.com/questions/225867",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93640/"
] |
Hey so I am trying to create this conditional that auto creates a grid layout when widgets/sidebars are added and removed. The goal is let the user put in as many widgets as possible without worrying about the layout.
This is my code, let me know if you want me to further explain myself:
```
if (function_exists('create_widget') && dynamic_sidebar('sidebar-1') && dynamic_sidebar('sidebar-2') && dynamic_sidebar('sidebar-3') ) {
$layout_classes = "col-md-4";
} elseif ( is_active_sidebar( 'sidebar-1' ) && is_active_sidebar( 'sidebar-2' ) ) {
$layout_classes = "col-md-6";
} else {
$layout_classes = "col-md-2";
}
<div class="row"
<div class="container">
<div class="col-md-12">
<div class="<?php echo $layout_classes ?>">
<?php dynamic_sidebar( 'sidebar-1'); ?>
<?php dynamic_sidebar( 'sidebar-2'); ?>
<?php dynamic_sidebar( 'sidebar-3'); ?>
</div>
</div>
</div>
</div><!--End Layout Class-->
```
P.S. Using Bootstrap 3.
|
You haven't actually said what the problem is. But I can see one for starters - `dynamic_sidebar` in your `if` conditions will echo out the widgets immediately. If you want to *check* a sidebar has widgets, use [`is_active_sidebar`](https://developer.wordpress.org/reference/functions/is_active_sidebar/):
```
is_active_sidebar( 'sidebar-1' ); // True/false
```
|
225,893 |
<p>I am trying to use mathJax in my wordpress. According to the documentation at mathjax, the mathjax script url needs to mentioned in headers.php.
Which is exactly what I did. And right now this is what the head section in the headers.php looks like:</p>
<pre><code><head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<title><?php wp_title( '|', true, 'right' ); ?></title>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX", "output/HTML-CSS"],
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
processEscapes: true
},
"HTML-CSS": { availableFonts: ["TeX"] }
});
</script>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<script type="text/javascript"src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<![endif]-->
<?php wp_head(); ?>
</head>
</code></pre>
<p>This javascript is not loading on my website's <a href="http://quantum.wobblybit.com/" rel="nofollow">index.php</a> page, however its loading on a <a href="http://quantum.wobblybit.com/nielsenchuang/exercise-4-4/" rel="nofollow">single posts page</a>. What could be the problem. What am I missing here?</p>
|
[
{
"answer_id": 225894,
"author": "Anuroop Kuppam",
"author_id": 93655,
"author_profile": "https://wordpress.stackexchange.com/users/93655",
"pm_score": -1,
"selected": false,
"text": "<p>I could understand what the problem was. Firstly the statement<code><script type=\"text/javascript\"src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"></code> was inside an <strong>if</strong> for the browser IE. Even after removing that I faced the same problem because I had WP cache enabled and this was caching my webpages. So when you are testing your wp installation, I would recommend deactivating the cache.</p>\n"
},
{
"answer_id": 356904,
"author": "Tony Djukic",
"author_id": 60844,
"author_profile": "https://wordpress.stackexchange.com/users/60844",
"pm_score": 0,
"selected": false,
"text": "<p>The proper way to enqueue a script is as follows:</p>\n\n<pre><code>function mathJax_scripts() {\n wp_enqueue_script( 'mathjax-js', http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML', array(), '2.7.1', false );\n}\nadd_action( 'wp_enqueue_scripts', 'mathJax_scripts' );\n</code></pre>\n\n<p>I added the version number (2.7.1) and I flipped the final parameter to 'false' - that last parameter asks <em>'add script to footer?'</em>, <strong>true</strong> means yes, <strong>false</strong> means no. </p>\n\n<p>Then you'll want to add the inline code into the <code>wp_head()</code>:</p>\n\n<pre><code>function mathJax_inlineScript() {\n <script type=\"text/x-mathjax-config\">\n MathJax.Hub.Config({\n extensions: [\"tex2jax.js\"],\n jax: [\"input/TeX\", \"output/HTML-CSS\"],\n tex2jax: {\n inlineMath: [ ['$','$'], [\"\\\\(\",\"\\\\)\"] ],\n displayMath: [ ['$$','$$'], [\"\\\\[\",\"\\\\]\"] ],\n processEscapes: true\n },\n \"HTML-CSS\": { availableFonts: [\"TeX\"] }\n });\n </script>\n<?php }\nadd_action( 'wp_head', 'mathJax_inlineScript' , 999 );\n</code></pre>\n\n<p>In the add action I've set it to 999 - you can adjust and fine tune that to get the inline script to appear where you want it to in the <code>wp_head()</code>.</p>\n\n<p>Hope that helps.</p>\n"
}
] |
2016/05/07
|
[
"https://wordpress.stackexchange.com/questions/225893",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93655/"
] |
I am trying to use mathJax in my wordpress. According to the documentation at mathjax, the mathjax script url needs to mentioned in headers.php.
Which is exactly what I did. And right now this is what the head section in the headers.php looks like:
```
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<title><?php wp_title( '|', true, 'right' ); ?></title>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX", "output/HTML-CSS"],
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
processEscapes: true
},
"HTML-CSS": { availableFonts: ["TeX"] }
});
</script>
<link rel="profile" href="http://gmpg.org/xfn/11" />
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script>
<script type="text/javascript"src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<![endif]-->
<?php wp_head(); ?>
</head>
```
This javascript is not loading on my website's [index.php](http://quantum.wobblybit.com/) page, however its loading on a [single posts page](http://quantum.wobblybit.com/nielsenchuang/exercise-4-4/). What could be the problem. What am I missing here?
|
The proper way to enqueue a script is as follows:
```
function mathJax_scripts() {
wp_enqueue_script( 'mathjax-js', http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML', array(), '2.7.1', false );
}
add_action( 'wp_enqueue_scripts', 'mathJax_scripts' );
```
I added the version number (2.7.1) and I flipped the final parameter to 'false' - that last parameter asks *'add script to footer?'*, **true** means yes, **false** means no.
Then you'll want to add the inline code into the `wp_head()`:
```
function mathJax_inlineScript() {
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX", "output/HTML-CSS"],
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
processEscapes: true
},
"HTML-CSS": { availableFonts: ["TeX"] }
});
</script>
<?php }
add_action( 'wp_head', 'mathJax_inlineScript' , 999 );
```
In the add action I've set it to 999 - you can adjust and fine tune that to get the inline script to appear where you want it to in the `wp_head()`.
Hope that helps.
|
225,895 |
<p>I have updated WordPress to the newest version. But due to compatibility issues, I need your help.</p>
<p>How can I change the font size of each text? What I'm doing right now is using some kinds of buttons on the bar in the image.</p>
<p><a href="https://i.stack.imgur.com/dbFVq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dbFVq.jpg" alt="enter image description here"></a>.</p>
<p>This question could be a duplicate, but could someone please help me....</p>
<p>Thank you in advance.</p>
|
[
{
"answer_id": 225897,
"author": "Jared Caputo",
"author_id": 89128,
"author_profile": "https://wordpress.stackexchange.com/users/89128",
"pm_score": 0,
"selected": false,
"text": "<p>You can edit your theme's stylesheet (style.css) to change the font size for each of the headings and the paragraph element to your liking. Then you can select the heading that fits your needs in your text editor. To do this most easily, hover over the \"Appearance\" tab in your WordPress Admin, click \"Editor,\" select your \"Stylesheet\" (aka \"style.css\") from the right side of the screen, and make the adjustments there. You have 6 headers, and you can adjust each like this:</p>\n\n<pre><code>h6 { font-size: 14px;}\n</code></pre>\n\n<p>The number following the \"h\" specifies which heading, and the number preceding the \"px\" specifies the size in pixels.</p>\n\n<p>Then, as mentioned before, just select the heading that you wish to use, now having your updated font sizes. </p>\n\n<p>You should use a child theme if you update your theme and want to preserve your changes. More information about those is available here: <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow\">https://codex.wordpress.org/Child_Themes</a></p>\n"
},
{
"answer_id": 225905,
"author": "Vigneshwar",
"author_id": 90994,
"author_profile": "https://wordpress.stackexchange.com/users/90994",
"pm_score": 0,
"selected": false,
"text": "<p>You can change font size of header and paragraph text by editing/adding custom CSS to your stylesheet in Theme Root folder as <code>(wordpress/wp-content/themes/your-theme/style.css)</code>. </p>\n\n<pre><code>h1 { font-size: 24px;}\nh2 { font-size: 22px;}\nh3 { font-size: 18px;}\nh4 { font-size: 16px;}\nh5 { font-size: 12px;}\nh6 { font-size: 10px;}\n</code></pre>\n\n<p>Hope it helps you.</p>\n"
},
{
"answer_id": 225939,
"author": "Luis Sanz",
"author_id": 81084,
"author_profile": "https://wordpress.stackexchange.com/users/81084",
"pm_score": 2,
"selected": true,
"text": "<p>First of all, remember that html is for adding meaning and css appearance.</p>\n\n<p>If you want to change the text size for sematic reasons, like <em>\"this text is a subsection title\"</em> or <em>\"this sentence is very important\"</em>, I would advice you not to use <code><span style=\"font-size: xx\"></code>. It's a better practice for those cases to use <code><strong></code>, <code><em></code> or a proper heading tag and then change your theme's css to customize its appearance up to your likings. </p>\n\n<p>If it's not for semantic but for presentational reasons, you are ok with <code><span style=\"font-size: xx\"></code>.</p>\n\n<p>To make it easier, you can use the following code to add a new button to the text editor that will let you choose the font size without having to hardcode it each time.</p>\n\n<p><a href=\"https://i.stack.imgur.com/M6Fgj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/M6Fgj.png\" alt=\"enter image description here\"></a></p>\n\n<p>Just copy the code to a new file, save it as <code>show-font-size-button-in-editor.php</code> and install and activate it as a plugin. Alternatively you can copy the <code>function</code> and <code>add_filter</code> to your theme's <code>functions.php</code> file.</p>\n\n<pre><code><?php\n\n /*\n Plugin Name: Show font size button in editor\n Description: Adds a font size selector to the TinyMCE first tools row\n Version: 0.1\n Author: WPSE\n Author URI: http://wordpress.stackexchange.com/questions/225895/how-can-i-change-the-size-of-the-text-in-word-press\n */\n\n defined( 'ABSPATH' ) or die( 'Method not allowed.' );\n\n function wpse225895_show_font_size_button_in_editor( $buttons ) {\n\n array_unshift ( $buttons, 'fontsizeselect' );\n\n return $buttons;\n\n }\n\n add_filter( 'mce_buttons', 'wpse225895_show_font_size_button_in_editor', 10, 1 );\n\n?>\n</code></pre>\n"
}
] |
2016/05/07
|
[
"https://wordpress.stackexchange.com/questions/225895",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93656/"
] |
I have updated WordPress to the newest version. But due to compatibility issues, I need your help.
How can I change the font size of each text? What I'm doing right now is using some kinds of buttons on the bar in the image.
[](https://i.stack.imgur.com/dbFVq.jpg).
This question could be a duplicate, but could someone please help me....
Thank you in advance.
|
First of all, remember that html is for adding meaning and css appearance.
If you want to change the text size for sematic reasons, like *"this text is a subsection title"* or *"this sentence is very important"*, I would advice you not to use `<span style="font-size: xx">`. It's a better practice for those cases to use `<strong>`, `<em>` or a proper heading tag and then change your theme's css to customize its appearance up to your likings.
If it's not for semantic but for presentational reasons, you are ok with `<span style="font-size: xx">`.
To make it easier, you can use the following code to add a new button to the text editor that will let you choose the font size without having to hardcode it each time.
[](https://i.stack.imgur.com/M6Fgj.png)
Just copy the code to a new file, save it as `show-font-size-button-in-editor.php` and install and activate it as a plugin. Alternatively you can copy the `function` and `add_filter` to your theme's `functions.php` file.
```
<?php
/*
Plugin Name: Show font size button in editor
Description: Adds a font size selector to the TinyMCE first tools row
Version: 0.1
Author: WPSE
Author URI: http://wordpress.stackexchange.com/questions/225895/how-can-i-change-the-size-of-the-text-in-word-press
*/
defined( 'ABSPATH' ) or die( 'Method not allowed.' );
function wpse225895_show_font_size_button_in_editor( $buttons ) {
array_unshift ( $buttons, 'fontsizeselect' );
return $buttons;
}
add_filter( 'mce_buttons', 'wpse225895_show_font_size_button_in_editor', 10, 1 );
?>
```
|
225,899 |
<p>Would be potential problems if I delete <code>wordpress_logged_in_47d1523b...</code> cookie using javascript? Is there something additional that <code>wp_logout</code> does?</p>
|
[
{
"answer_id": 225902,
"author": "N00b",
"author_id": 80903,
"author_profile": "https://wordpress.stackexchange.com/users/80903",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Is there something additional that wp_logout does?</p>\n</blockquote>\n\n<p>As I said in my comment, WordPress runs two functions on <code>wp_logout</code>.</p>\n\n<ol>\n<li><code>wp_destroy_current_session()</code></li>\n<li><code>wp_clear_auth_cookie()</code></li>\n</ol>\n\n<hr>\n\n<p><code>wp_clear_auth_cookie()</code> removes all of the cookies associated with authentication. This is what you would like to do with JavaScript.</p>\n\n<p>However there's also <code>wp_destroy_current_session()</code>. This function remove the current session token from the database which brings us to the next question..</p>\n\n<blockquote>\n <p>Would be potential problems if I delete\n wordpress_logged_in_47d1523b... cookie using javascript?</p>\n</blockquote>\n\n<p>No, there could not be any problems because users can manually delete sessions and cookies but that doesn't break the web. As long as you delete the right session, everything works as you planned.</p>\n\n<p>Now you might be wondering: what about session token in database? That doesn't matter anymore because session is destroyed. It will be overwritten by new token as soon as user logs in again.</p>\n\n<hr>\n\n<p><strong>And now the bad news:</strong> How are you going to delete the session with only JavaScript? Session key and value are both generated, you have no way to target the right one only with JavaScript. Session key and value are different for every user and for every session. </p>\n"
},
{
"answer_id": 225917,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": true,
"text": "<p>You can log out the current user with <a href=\"https://codex.wordpress.org/Function_Reference/wp_logout\" rel=\"nofollow\"><code>wp_logout()</code> function</a>:</p>\n\n\n\n<p>I think it is much better approach. <code>wp_logout()</code> destroys current session, clears authorization cookie and call <code>wp_logout</code> action. Also, it is a pluggable function, which means can be redefined by plugins. You can miss important stuff, specially when working in combination with other plugins.</p>\n\n<p>If you want to log out from JavaScript, you can execute <code>wp_logout()</code> using ajax (code not tested, just writted here as basic example):</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'cyb_enqueue_scripts' );\nfunction cyb_enqueue_scripts() \n wp_enqueue_script( 'cyb-ajax-logout', 'url_to_js_script', array( 'jquery' ) );\n wp_localize_script( 'cyb-ajax-logout', 'ajax_logout_params',\n array(\n 'ajax_url' => admin_url( 'admin-ajax.php' ),\n 'logout_nonce' => wp_create_nonce( 'cyb-logout-nonce' ),\n )\n );\n}\n\nadd_action('wp_ajax_cyb_logout', 'cyb_ajax_logout');\nfunction cyb_ajax_logout(){\n if( check_ajax_referer( 'cyb-logout-nonce', 'logout_nonce', false ) ) {\n wp_logout();\n $reponse = array(\n 'message' => __( 'You have been logged out.', 'cyb-textdomain' )\n );\n wp_send_json_success( $reponse );\n } else {\n // Ajax referer is wrong\n $reponse = array(\n 'message' => __( \"Unknown referer. You couldn't been logged out.\", 'cyb-textdomain' )\n );\n wp_send_json_error( $reponse );\n }\n}\n</code></pre>\n\n<p>And the js:</p>\n\n<pre><code>jQuery(document).ready(function($){\n var data = {\n action: 'cyb_logout',\n logout_nonce: ajax_logout_params.logout_nonce\n };\n $.getJSON( ajax_logout_params.ajax_url, data, function( response ) {\n if( response.success ) {\n // User has been logged out\n }\n });\n});\n</code></pre>\n"
}
] |
2016/05/07
|
[
"https://wordpress.stackexchange.com/questions/225899",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47988/"
] |
Would be potential problems if I delete `wordpress_logged_in_47d1523b...` cookie using javascript? Is there something additional that `wp_logout` does?
|
You can log out the current user with [`wp_logout()` function](https://codex.wordpress.org/Function_Reference/wp_logout):
I think it is much better approach. `wp_logout()` destroys current session, clears authorization cookie and call `wp_logout` action. Also, it is a pluggable function, which means can be redefined by plugins. You can miss important stuff, specially when working in combination with other plugins.
If you want to log out from JavaScript, you can execute `wp_logout()` using ajax (code not tested, just writted here as basic example):
```
add_action( 'wp_enqueue_scripts', 'cyb_enqueue_scripts' );
function cyb_enqueue_scripts()
wp_enqueue_script( 'cyb-ajax-logout', 'url_to_js_script', array( 'jquery' ) );
wp_localize_script( 'cyb-ajax-logout', 'ajax_logout_params',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'logout_nonce' => wp_create_nonce( 'cyb-logout-nonce' ),
)
);
}
add_action('wp_ajax_cyb_logout', 'cyb_ajax_logout');
function cyb_ajax_logout(){
if( check_ajax_referer( 'cyb-logout-nonce', 'logout_nonce', false ) ) {
wp_logout();
$reponse = array(
'message' => __( 'You have been logged out.', 'cyb-textdomain' )
);
wp_send_json_success( $reponse );
} else {
// Ajax referer is wrong
$reponse = array(
'message' => __( "Unknown referer. You couldn't been logged out.", 'cyb-textdomain' )
);
wp_send_json_error( $reponse );
}
}
```
And the js:
```
jQuery(document).ready(function($){
var data = {
action: 'cyb_logout',
logout_nonce: ajax_logout_params.logout_nonce
};
$.getJSON( ajax_logout_params.ajax_url, data, function( response ) {
if( response.success ) {
// User has been logged out
}
});
});
```
|
225,901 |
<p>I have this code in my functions.php file:</p>
<pre><code>function user_content_replace($content) {
// it's not a URL, let's apply the replacement
if (!filter_var($string, FILTER_VALIDATE_URL)) {
$replacement = '$1.</p><p>$2';
return preg_replace("/([^\\.]*\\.[^\\.]*\\.[^\\.]*){1}\\.([^\\.]*)/s", $replacement, $content);
} else { // it's a URL, just return the string
return $content;
}
}
add_filter('the_content','user_content_replace', 99);
</code></pre>
<p>This code replaces every third dot in content with dot+closed+open paragraph. This because it is the best way in this moment to format non-formatted great amount of texts and posts.</p>
<p>But: this code also changes <strong>Images URLs</strong> so all my images does not contain dot before extension but <code>**imagename.</p><p>jpg**</code>instead of <strong>imagename.jpg</strong></p>
<p>Even if I put URL validation - same problem. Any advice please?</p>
|
[
{
"answer_id": 226012,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 1,
"selected": true,
"text": "<pre><code><?php\n$string = 'Sentence 1. Sentence 2? Sentence 3! Sentence 4... Sentence 5β¦ Sentence 6! Sentence 7. Sentence 8. Sentence 9β¦ Sentence 10... Sentence 11. ';\n\n$sentences_per_paragraph = 3; // settings\n\n$pattern = '~(?<=[.?!β¦])\\s+~'; // some punctuation and trailing space(s)\n\n$sentences_array = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY); // get sentences into array\n\n$sentences_count = count($sentences_array); // count sentences\n\n$output = ''; // new content init\n\n// see PHP modulus\nfor($i = 0; $i < $sentences_count; $i++) {\n if($i%$sentences_per_paragraph == 0 && $i == 0) { //divisible by settings and is first\n $output .= \"<p>\" . $sentences_array[$i] . ' '; // add paragraph and the first sentence\n } elseif($i%$sentences_per_paragraph == 0 && $i > 0) { //divisible by settings and not first\n $output .= \"</p><p>\" . $sentences_array[$i] . ' '; // close and open paragraph, add the first sentence\n } else {\n $output .= $sentences_array[$i] . ' '; // concatenate other sentences\n }\n}\n\n$output .= \"</p>\"; // close the last paragraph\n\necho $output;\n</code></pre>\n\n<p><strong>Note</strong>: It's a very rough code that does not check the deeper problems. </p>\n\n<p>For more info:</p>\n\n<ul>\n<li><a href=\"https://secure.php.net/manual/en/language.operators.arithmetic.php\" rel=\"nofollow\">PHP modulus</a></li>\n<li><a href=\"https://secure.php.net/manual/en/function.preg-split.php\" rel=\"nofollow\">preg_split()</a></li>\n</ul>\n"
},
{
"answer_id": 226027,
"author": "Eager2Learn",
"author_id": 31498,
"author_profile": "https://wordpress.stackexchange.com/users/31498",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks to @Max Yudin this is an answer to my problem:</p>\n\n<pre><code>function user_content_replace($content) {\n\n$sentences_per_paragraph = 3; // settings\n\n$pattern = '~(?<=[.?!β¦])\\s+~'; // some punctuation and trailing space(s)\n\n$sentences_array = preg_split($pattern, $content, -1, PREG_SPLIT_NO_EMPTY); // get sentences into array\n\n$sentences_count = count($sentences_array); // count sentences\n\n$output = ''; // new content init\n\n// see PHP modulus\nfor($i = 0; $i < $sentences_count; $i++) {\n if($i%$sentences_per_paragraph == 0 && $i == 0) { //divisible by settings and is first\n $output .= \"<p>\" . $sentences_array[$i] . ' '; // add paragraph and the first sentence\n } elseif($i%$sentences_per_paragraph == 0 && $i > 0) { //divisible by settings and not first\n $output .= \"</p><p>\" . $sentences_array[$i] . ' '; // close and open paragraph, add the first sentence\n } else {\n $output .= $sentences_array[$i] . ' '; // concatenate other sentences\n }\n}\n\n$output .= \"</p>\"; // close the last paragraph\n\necho $output;\n}\nadd_filter('the_content','user_content_replace', 99);\n</code></pre>\n"
}
] |
2016/05/07
|
[
"https://wordpress.stackexchange.com/questions/225901",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31498/"
] |
I have this code in my functions.php file:
```
function user_content_replace($content) {
// it's not a URL, let's apply the replacement
if (!filter_var($string, FILTER_VALIDATE_URL)) {
$replacement = '$1.</p><p>$2';
return preg_replace("/([^\\.]*\\.[^\\.]*\\.[^\\.]*){1}\\.([^\\.]*)/s", $replacement, $content);
} else { // it's a URL, just return the string
return $content;
}
}
add_filter('the_content','user_content_replace', 99);
```
This code replaces every third dot in content with dot+closed+open paragraph. This because it is the best way in this moment to format non-formatted great amount of texts and posts.
But: this code also changes **Images URLs** so all my images does not contain dot before extension but `**imagename.</p><p>jpg**`instead of **imagename.jpg**
Even if I put URL validation - same problem. Any advice please?
|
```
<?php
$string = 'Sentence 1. Sentence 2? Sentence 3! Sentence 4... Sentence 5β¦ Sentence 6! Sentence 7. Sentence 8. Sentence 9β¦ Sentence 10... Sentence 11. ';
$sentences_per_paragraph = 3; // settings
$pattern = '~(?<=[.?!β¦])\s+~'; // some punctuation and trailing space(s)
$sentences_array = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY); // get sentences into array
$sentences_count = count($sentences_array); // count sentences
$output = ''; // new content init
// see PHP modulus
for($i = 0; $i < $sentences_count; $i++) {
if($i%$sentences_per_paragraph == 0 && $i == 0) { //divisible by settings and is first
$output .= "<p>" . $sentences_array[$i] . ' '; // add paragraph and the first sentence
} elseif($i%$sentences_per_paragraph == 0 && $i > 0) { //divisible by settings and not first
$output .= "</p><p>" . $sentences_array[$i] . ' '; // close and open paragraph, add the first sentence
} else {
$output .= $sentences_array[$i] . ' '; // concatenate other sentences
}
}
$output .= "</p>"; // close the last paragraph
echo $output;
```
**Note**: It's a very rough code that does not check the deeper problems.
For more info:
* [PHP modulus](https://secure.php.net/manual/en/language.operators.arithmetic.php)
* [preg\_split()](https://secure.php.net/manual/en/function.preg-split.php)
|
225,926 |
<p>I have a server elastic-search instance running, as well as an off-site firebase data account. What I am trying to do is basically fire a curl request to create certain user fields with data once the user creates an account. The site automatically checks for these values once the user logs in (I did this by automatically firing the command once a certain page loads which every user is redirected to when they log-in). I am also running angularjs so I have that option as well. It's just that I really have no idea what php function to use or anything that fires once a user is created.. Any ideas on how to get this done?</p>
|
[
{
"answer_id": 225931,
"author": "Douglas.Sesar",
"author_id": 19945,
"author_profile": "https://wordpress.stackexchange.com/users/19945",
"pm_score": 2,
"selected": false,
"text": "<pre><code>//This action hook allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument.\n do_action( 'user_register', $user_id );\n</code></pre>\n\n<p>so you could: </p>\n\n<pre><code>add_action('user_register','my_user_register_function');\n\nfunction my_user_register_function($user_id)\n{\n$user = get_user_by( 'ID', $user_id );\n//your CURL stuff\n}\n</code></pre>\n"
},
{
"answer_id": 225943,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to wait until the user is activated by BuddyPress. </p>\n\n<p>Try using this hook:</p>\n\n<pre><code>do_action( 'bp_core_activated_user', $user_id, $key, $user ); \n</code></pre>\n\n<p>Located in: <code>buddypress\\bp-members\\bp-members-functions.php</code> in <code>function bp_core_activate_signup</code></p>\n"
}
] |
2016/05/07
|
[
"https://wordpress.stackexchange.com/questions/225926",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93670/"
] |
I have a server elastic-search instance running, as well as an off-site firebase data account. What I am trying to do is basically fire a curl request to create certain user fields with data once the user creates an account. The site automatically checks for these values once the user logs in (I did this by automatically firing the command once a certain page loads which every user is redirected to when they log-in). I am also running angularjs so I have that option as well. It's just that I really have no idea what php function to use or anything that fires once a user is created.. Any ideas on how to get this done?
|
```
//This action hook allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument.
do_action( 'user_register', $user_id );
```
so you could:
```
add_action('user_register','my_user_register_function');
function my_user_register_function($user_id)
{
$user = get_user_by( 'ID', $user_id );
//your CURL stuff
}
```
|
225,933 |
<p>I am creating theme for WordPress which I hope to maintain. The current method of updating a non-WordPress hosted theme is to either replace the old theme with the new theme through FTP or switch to say WP2016 then delete the old theme and install the new one. Neither of these are really user friendly methods.</p>
<p>Would there be any problems (e.g. using numbers in theme name) if I start with say MyTheme_1_0 then when I have updated it call it MyTheme_1_1. This way the theme can be installed and switched to directly from the Theme page, without the need of a FTP or switching to a default theme, and the user can roll back to the old theme if need be.</p>
|
[
{
"answer_id": 225931,
"author": "Douglas.Sesar",
"author_id": 19945,
"author_profile": "https://wordpress.stackexchange.com/users/19945",
"pm_score": 2,
"selected": false,
"text": "<pre><code>//This action hook allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument.\n do_action( 'user_register', $user_id );\n</code></pre>\n\n<p>so you could: </p>\n\n<pre><code>add_action('user_register','my_user_register_function');\n\nfunction my_user_register_function($user_id)\n{\n$user = get_user_by( 'ID', $user_id );\n//your CURL stuff\n}\n</code></pre>\n"
},
{
"answer_id": 225943,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to wait until the user is activated by BuddyPress. </p>\n\n<p>Try using this hook:</p>\n\n<pre><code>do_action( 'bp_core_activated_user', $user_id, $key, $user ); \n</code></pre>\n\n<p>Located in: <code>buddypress\\bp-members\\bp-members-functions.php</code> in <code>function bp_core_activate_signup</code></p>\n"
}
] |
2016/05/07
|
[
"https://wordpress.stackexchange.com/questions/225933",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36773/"
] |
I am creating theme for WordPress which I hope to maintain. The current method of updating a non-WordPress hosted theme is to either replace the old theme with the new theme through FTP or switch to say WP2016 then delete the old theme and install the new one. Neither of these are really user friendly methods.
Would there be any problems (e.g. using numbers in theme name) if I start with say MyTheme\_1\_0 then when I have updated it call it MyTheme\_1\_1. This way the theme can be installed and switched to directly from the Theme page, without the need of a FTP or switching to a default theme, and the user can roll back to the old theme if need be.
|
```
//This action hook allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument.
do_action( 'user_register', $user_id );
```
so you could:
```
add_action('user_register','my_user_register_function');
function my_user_register_function($user_id)
{
$user = get_user_by( 'ID', $user_id );
//your CURL stuff
}
```
|
225,941 |
<p>I have a custom post type called "products". My goal is to make my custom query that I have on homepage and also the search query show first the posts that have a custom field called "id_number" not empty and then the other posts that have the "id_number" empty. All should be ordered by title.</p>
<p>This is my code so far only for my custom query. I also need it for search page query but I didn't get that far.</p>
<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$wp_query = new WP_Query( array(
'post_type' => 'products',
'posts_per_page' => 20,
'post_status' => 'publish',
'pagination' => true,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'id_number',
'compare' => 'EXISTS',
),
array(
'key' => 'id_number',
'compare' => 'NOT EXISTS'
)
),
'meta_key' => 'id_number',
'orderby' => 'title',
'paged'=>$paged
) );
</code></pre>
<p>Any help will be appreciated. Thank you!</p>
|
[
{
"answer_id": 225931,
"author": "Douglas.Sesar",
"author_id": 19945,
"author_profile": "https://wordpress.stackexchange.com/users/19945",
"pm_score": 2,
"selected": false,
"text": "<pre><code>//This action hook allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument.\n do_action( 'user_register', $user_id );\n</code></pre>\n\n<p>so you could: </p>\n\n<pre><code>add_action('user_register','my_user_register_function');\n\nfunction my_user_register_function($user_id)\n{\n$user = get_user_by( 'ID', $user_id );\n//your CURL stuff\n}\n</code></pre>\n"
},
{
"answer_id": 225943,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to wait until the user is activated by BuddyPress. </p>\n\n<p>Try using this hook:</p>\n\n<pre><code>do_action( 'bp_core_activated_user', $user_id, $key, $user ); \n</code></pre>\n\n<p>Located in: <code>buddypress\\bp-members\\bp-members-functions.php</code> in <code>function bp_core_activate_signup</code></p>\n"
}
] |
2016/05/07
|
[
"https://wordpress.stackexchange.com/questions/225941",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69589/"
] |
I have a custom post type called "products". My goal is to make my custom query that I have on homepage and also the search query show first the posts that have a custom field called "id\_number" not empty and then the other posts that have the "id\_number" empty. All should be ordered by title.
This is my code so far only for my custom query. I also need it for search page query but I didn't get that far.
```
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$wp_query = new WP_Query( array(
'post_type' => 'products',
'posts_per_page' => 20,
'post_status' => 'publish',
'pagination' => true,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'id_number',
'compare' => 'EXISTS',
),
array(
'key' => 'id_number',
'compare' => 'NOT EXISTS'
)
),
'meta_key' => 'id_number',
'orderby' => 'title',
'paged'=>$paged
) );
```
Any help will be appreciated. Thank you!
|
```
//This action hook allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument.
do_action( 'user_register', $user_id );
```
so you could:
```
add_action('user_register','my_user_register_function');
function my_user_register_function($user_id)
{
$user = get_user_by( 'ID', $user_id );
//your CURL stuff
}
```
|
225,963 |
<p>In the phase of developing a new wordpress-based site, I'm evaluating also future pitfalls such as upgrades. Unfortunately, there's no guarantee that a third party plugin will not be discontinued. But that's how it works!
There are two possible options:</p>
<p>1) Develop a tight robust site, with no future updates, and cross your fingers (hackers)</p>
<p>2) struggle to keep updated the site, and cross your fingers (what if plugin support is dropped?)</p>
<p>Is there a third option?</p>
|
[
{
"answer_id": 225931,
"author": "Douglas.Sesar",
"author_id": 19945,
"author_profile": "https://wordpress.stackexchange.com/users/19945",
"pm_score": 2,
"selected": false,
"text": "<pre><code>//This action hook allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument.\n do_action( 'user_register', $user_id );\n</code></pre>\n\n<p>so you could: </p>\n\n<pre><code>add_action('user_register','my_user_register_function');\n\nfunction my_user_register_function($user_id)\n{\n$user = get_user_by( 'ID', $user_id );\n//your CURL stuff\n}\n</code></pre>\n"
},
{
"answer_id": 225943,
"author": "shanebp",
"author_id": 16575,
"author_profile": "https://wordpress.stackexchange.com/users/16575",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to wait until the user is activated by BuddyPress. </p>\n\n<p>Try using this hook:</p>\n\n<pre><code>do_action( 'bp_core_activated_user', $user_id, $key, $user ); \n</code></pre>\n\n<p>Located in: <code>buddypress\\bp-members\\bp-members-functions.php</code> in <code>function bp_core_activate_signup</code></p>\n"
}
] |
2016/05/07
|
[
"https://wordpress.stackexchange.com/questions/225963",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1210/"
] |
In the phase of developing a new wordpress-based site, I'm evaluating also future pitfalls such as upgrades. Unfortunately, there's no guarantee that a third party plugin will not be discontinued. But that's how it works!
There are two possible options:
1) Develop a tight robust site, with no future updates, and cross your fingers (hackers)
2) struggle to keep updated the site, and cross your fingers (what if plugin support is dropped?)
Is there a third option?
|
```
//This action hook allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument.
do_action( 'user_register', $user_id );
```
so you could:
```
add_action('user_register','my_user_register_function');
function my_user_register_function($user_id)
{
$user = get_user_by( 'ID', $user_id );
//your CURL stuff
}
```
|
226,029 |
<p>The 40,000 urls have the same structure between them.</p>
<p>How can we redirect 40,000 urls in bulk instead of inputting each url 1 by 1?</p>
<p>Here's a sample format of the url structure:</p>
<p>www.website.com/School-A-Cost to www.website.com/School-A/Cost</p>
<p>www.website.com/School-B-Cost to www.website.com/School-B/Cost</p>
|
[
{
"answer_id": 226030,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": false,
"text": "<p>That can be solved without WordPress per .htaccess (or whatever config file your webserver is using).</p>\n\n<p>Example for .htaccess:</p>\n\n<pre><code>RedirectMatch Permanent /School-(.*)-Cost /School-$1/Cost\n</code></pre>\n"
},
{
"answer_id": 226034,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this in WP but there isn't much specific to WordPress here besides <a href=\"https://codex.wordpress.org/Function_Reference/wp_redirect\" rel=\"nofollow\">wp_redirect</a>. </p>\n\n<p>This chunk of code could go in a plugin to speed up the check or just dropped into your functions.php. Essentially you want to run this as soon as possible before WP has to think too hard.</p>\n\n<pre><code>if ( ! function_exists( 'wpse_20160508_check_redirects' ) ) {\n function wpse_20160508_check_redirects() {\n\n $request = $_SERVER[ 'REQUEST_URI' ];\n $redirect = '';\n\n /**\n * http://example.com/School-A-Cost/ -> http://example.com/School-A/Cost/\n */\n\n if ( preg_match( \"/(School-(.*))-(Cost)(\\/.*)?/\", $request, $matches ) && count( $matches ) >= 3 ) {\n\n $path = $matches[ 1 ] . '/' . $matches[ 3 ];\n\n if ( isset( $matches[ 4 ] ) ) {\n $path .= $matches[ 4 ];\n }\n\n $redirect = site_url( $path );\n }\n\n if ( ! empty ( $redirect ) ) {\n wp_redirect( $redirect, 301 );\n exit();\n }\n }\n}\n\n// Run as soon as possible\nwpse_20160508_check_redirects();\n</code></pre>\n\n<p>As you can see it'll take a URL like <code>/School-A-Cost/this-is-extra?foo=bar</code> and checks for matches to the regular expression.</p>\n\n<pre><code>Array\n(\n [0] => School-A-Cost/this-is-extra?foo=bar\n [1] => School-A\n [2] => A\n [3] => Cost\n [4] => /this-is-extra?foo=bar\n)\n</code></pre>\n\n<p>From there you can put those parts together to form a new location <code>/School-A/Cost/this-is-extra?foo=bar</code> which you'll redirect to.</p>\n"
}
] |
2016/05/09
|
[
"https://wordpress.stackexchange.com/questions/226029",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86907/"
] |
The 40,000 urls have the same structure between them.
How can we redirect 40,000 urls in bulk instead of inputting each url 1 by 1?
Here's a sample format of the url structure:
www.website.com/School-A-Cost to www.website.com/School-A/Cost
www.website.com/School-B-Cost to www.website.com/School-B/Cost
|
That can be solved without WordPress per .htaccess (or whatever config file your webserver is using).
Example for .htaccess:
```
RedirectMatch Permanent /School-(.*)-Cost /School-$1/Cost
```
|
226,044 |
<p>I've added meta box: checkbox on admin edit screen</p>
<pre><code><input type="checkbox" name="changeposition" />
</code></pre>
<p>So how could we sanitize the input came from the checkbox as we do for input type text by <code>sanitize_text_field()</code>. Is there any function like this for checkbox sanitization or should we create custom method for it?</p>
|
[
{
"answer_id": 226045,
"author": "550",
"author_id": 92492,
"author_profile": "https://wordpress.stackexchange.com/users/92492",
"pm_score": 0,
"selected": false,
"text": "<p>I would suggest the <a href=\"http://php.net/manual/en/function.filter-var.php\" rel=\"nofollow\"><code>filter_var()</code></a> function in PHP. \nIt has some predefined filters thats you can use.</p>\n\n<p>To sanitize a number:</p>\n\n<pre><code>$sanitizedCheckbox = filter_var( $yourVar, FILTER_SANITIZE_NUMBER_INT );\n</code></pre>\n\n<p>For a string you would just change <code>_NUM_INT</code> to <code>_STRING</code>.</p>\n"
},
{
"answer_id": 285280,
"author": "jaswrks",
"author_id": 81760,
"author_profile": "https://wordpress.stackexchange.com/users/81760",
"pm_score": 2,
"selected": false,
"text": "<p>Be sure to set the value in your markup. You should have.</p>\n\n<pre><code><input type=\"checkbox\" name=\"changeposition\" value=\"yes\" />\n</code></pre>\n\n<p>Then, I'd suggest using <a href=\"https://developer.wordpress.org/reference/functions/sanitize_key/\" rel=\"nofollow noreferrer\"><code>sanitize_key()</code></a> to sanitize.</p>\n\n<blockquote>\n <p>Keys are used as internal identifiers. Lowercase alphanumeric\n characters, dashes and underscores are allowed.</p>\n</blockquote>\n\n<p><em>Think of the word <code>yes</code>, as a key. That's what you're expecting is a lowercase alphanumeric value.</em></p>\n\n<hr>\n\n<p>See also: <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox</a></p>\n\n<blockquote>\n <p>If the value attribute was omitted, the submitted data would be given a default value of on, so the submitted data in that case would be subscribe=on.</p>\n</blockquote>\n"
}
] |
2016/05/09
|
[
"https://wordpress.stackexchange.com/questions/226044",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75767/"
] |
I've added meta box: checkbox on admin edit screen
```
<input type="checkbox" name="changeposition" />
```
So how could we sanitize the input came from the checkbox as we do for input type text by `sanitize_text_field()`. Is there any function like this for checkbox sanitization or should we create custom method for it?
|
Be sure to set the value in your markup. You should have.
```
<input type="checkbox" name="changeposition" value="yes" />
```
Then, I'd suggest using [`sanitize_key()`](https://developer.wordpress.org/reference/functions/sanitize_key/) to sanitize.
>
> Keys are used as internal identifiers. Lowercase alphanumeric
> characters, dashes and underscores are allowed.
>
>
>
*Think of the word `yes`, as a key. That's what you're expecting is a lowercase alphanumeric value.*
---
See also: <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox>
>
> If the value attribute was omitted, the submitted data would be given a default value of on, so the submitted data in that case would be subscribe=on.
>
>
>
|
226,065 |
<p>I have a homepage displaying the <code>home.php</code> template, containing 2 sidebars with widgets in them.</p>
<p>The main query still pulls in the standard 10 posts, but since I'm not displaying these, I'd like to eliminate the query being made to the database entirely. If needs be, an empty post loop will do as I am not using the main loop in my <code>home.php</code> template.</p>
<p>How would I do this? I could use <code>pre_get_posts</code> to minimise and reduce the query, but that still leaves me with a very fast query, how do I eliminate it entirely?</p>
|
[
{
"answer_id": 226070,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a neat trick I learned from @birgire, we can halt the main query by appending <code>AND where 0=1</code> to the <code>WHERE</code> clause of the SQL query. This might still result in one db query, but it will surely stop the main query from querying posts</p>\n\n<pre><code>add_filter( 'posts_where', function ( $where, \\WP_Query $q )\n{\n if ( $q->is_home()\n && $q->is_main_query()\n ) {\n $where .= ' AND where 0 = 1';\n }\n\n return $where;\n}, 10, 2 ); \n</code></pre>\n\n<p>You can also just try to replace the <code>WHERE</code> clause with <code>where 0 = 1</code></p>\n\n<pre><code>$where = ' where 0 = 1';\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>$where .= ' AND where 0 = 1';\n</code></pre>\n\n<p>Unfortunately, I do not have time to test anything, but this should be a nice starting point</p>\n"
},
{
"answer_id": 226074,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<h2>The <code>posts_request</code> filter</h2>\n\n<p>Skimming through the <code>WP_Query</code> we find this part of interest:</p>\n\n<pre><code>if ( !$q['suppress_filters'] ) {\n /**\n * Filter the completed SQL query before sending.\n *\n * @since 2.0.0\n *\n * @param array $request The complete SQL query.\n * @param WP_Query &$this The WP_Query instance (passed by reference).\n */\n $this->request = apply_filters_ref_array( 'posts_request', \n array( $this->request, &$this ) );\n }\n\n if ( 'ids' == $q['fields'] ) {\n $this->posts = $wpdb->get_col( $this->request );\n $this->posts = array_map( 'intval', $this->posts );\n $this->post_count = count( $this->posts );\n $this->set_found_posts( $q, $limits );\n return $this->posts;\n }\n</code></pre>\n\n<p>We might try to eliminate the main home request through the <code>posts_request</code> filter. Here's an example:</p>\n\n<pre><code>add_filter( 'posts_request', function( $request, \\WP_Query $q )\n{\n // Target main home query\n if ( $q->is_home() && $q->is_main_query() )\n {\n // Our early exit\n $q->set( 'fields', 'ids' );\n\n // No request\n $request = '';\n }\n\n return $request; \n\n}, PHP_INT_MAX, 2 );\n</code></pre>\n\n<p>where we force the <code>'fields' => 'ids'</code> for early exit.</p>\n\n<h2>The <code>posts_pre_query</code> filter (WP 4.6+)</h2>\n\n<p>We could also use the new <code>posts_pre_query</code><sup><a href=\"https://github.com/WordPress/WordPress/blob/b8b7a008892718f135524dd635274f21a4da6c5b/wp-includes/query.php#L35593575\" rel=\"nofollow\">src</a></sup> filter available in WordPress 4.6+</p>\n\n<pre><code>add_filter( 'posts_pre_query', function( $posts, \\WP_Query $q )\n{\n if( $q->is_home() && $q->is_main_query() )\n {\n $posts = [];\n $q->found_posts = 0;\n }\n return $posts;\n}, 10, 2 );\n</code></pre>\n\n<p>This filter makes it possible to skip the usual database queries to implement a custom posts injection instead.</p>\n\n<p>I just tested this and noticed that this will not prevent sticky posts, opposite to the <code>posts_request</code> approach.</p>\n\n<p>Check out the ticket <a href=\"https://core.trac.wordpress.org/ticket/36687\" rel=\"nofollow\">#36687</a> for more info and the <a href=\"https://core.trac.wordpress.org/ticket/36687#comment:8\" rel=\"nofollow\">example there</a> by @boonebgorges.</p>\n"
},
{
"answer_id": 226075,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>For reference, before: 45q, after: 42q</p>\n\n<p>The code is very similar to the code used by @birgire</p>\n\n<pre><code>function _tomjn_home_cancel_query( $query, \\WP_Query $q ) {\n if ( !$q->is_admin() && !$q->is_feed() && $q->is_home() && $q->is_main_query() ) {\n $query = false;\n $q->set( 'fields', 'ids' );\n }\n return $query;\n}\nadd_filter( 'posts_request', '_tomjn_home_cancel_query', 100, 2 );\n</code></pre>\n"
}
] |
2016/05/09
|
[
"https://wordpress.stackexchange.com/questions/226065",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/736/"
] |
I have a homepage displaying the `home.php` template, containing 2 sidebars with widgets in them.
The main query still pulls in the standard 10 posts, but since I'm not displaying these, I'd like to eliminate the query being made to the database entirely. If needs be, an empty post loop will do as I am not using the main loop in my `home.php` template.
How would I do this? I could use `pre_get_posts` to minimise and reduce the query, but that still leaves me with a very fast query, how do I eliminate it entirely?
|
The `posts_request` filter
--------------------------
Skimming through the `WP_Query` we find this part of interest:
```
if ( !$q['suppress_filters'] ) {
/**
* Filter the completed SQL query before sending.
*
* @since 2.0.0
*
* @param array $request The complete SQL query.
* @param WP_Query &$this The WP_Query instance (passed by reference).
*/
$this->request = apply_filters_ref_array( 'posts_request',
array( $this->request, &$this ) );
}
if ( 'ids' == $q['fields'] ) {
$this->posts = $wpdb->get_col( $this->request );
$this->posts = array_map( 'intval', $this->posts );
$this->post_count = count( $this->posts );
$this->set_found_posts( $q, $limits );
return $this->posts;
}
```
We might try to eliminate the main home request through the `posts_request` filter. Here's an example:
```
add_filter( 'posts_request', function( $request, \WP_Query $q )
{
// Target main home query
if ( $q->is_home() && $q->is_main_query() )
{
// Our early exit
$q->set( 'fields', 'ids' );
// No request
$request = '';
}
return $request;
}, PHP_INT_MAX, 2 );
```
where we force the `'fields' => 'ids'` for early exit.
The `posts_pre_query` filter (WP 4.6+)
--------------------------------------
We could also use the new `posts_pre_query`[src](https://github.com/WordPress/WordPress/blob/b8b7a008892718f135524dd635274f21a4da6c5b/wp-includes/query.php#L35593575) filter available in WordPress 4.6+
```
add_filter( 'posts_pre_query', function( $posts, \WP_Query $q )
{
if( $q->is_home() && $q->is_main_query() )
{
$posts = [];
$q->found_posts = 0;
}
return $posts;
}, 10, 2 );
```
This filter makes it possible to skip the usual database queries to implement a custom posts injection instead.
I just tested this and noticed that this will not prevent sticky posts, opposite to the `posts_request` approach.
Check out the ticket [#36687](https://core.trac.wordpress.org/ticket/36687) for more info and the [example there](https://core.trac.wordpress.org/ticket/36687#comment:8) by @boonebgorges.
|
226,099 |
<p>I'm trying to stop the WordPress from automatically wrapping <code><img></code>s with <code><p></code> tags. I've tried this recommended snippet in my <code>functions.php</code>:</p>
<pre><code>function filter_ptags_on_images($content){ // Remove p tags from around images
return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}
add_filter('the_content', 'filter_ptags_on_images');
</code></pre>
<p>This doesn't works if an image is the <strong>first</strong> element in a post or page. When an image comes before any text, the image gets wrapped with <code><p></code> tags once again. Any ideas?</p>
|
[
{
"answer_id": 269399,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to <em>remove</em> <code><p></code> from entire content (not only from the images), this can help you</p>\n\n<pre><code>add_filter( 'the_content', 'wpse_226099_remove_p' );\nfunction wpse_226099_remove_p( $content ) {\n global $post;\n return $post->post_content;\n}\n</code></pre>\n\n<p>or maybe with this-</p>\n\n<pre><code>remove_filter('the_content', 'wpautop')\n</code></pre>\n"
},
{
"answer_id": 269440,
"author": "honk31",
"author_id": 10994,
"author_profile": "https://wordpress.stackexchange.com/users/10994",
"pm_score": 1,
"selected": false,
"text": "<p>this is a function, that unwraps images from p tags inside the_content</p>\n\n<pre><code>/**\n * WP: Unwrap images from <p> tag\n * @param $content\n * @return mixed\n */\nfunction so226099_filter_p_tags_on_images( $content ) {\n $content = preg_replace('/<p>\\\\s*?(<a .*?><img.*?><\\\\/a>|<img.*?>)?\\\\s*<\\\\/p>/s', '\\1', $content);\n\n return $content;\n}\nadd_filter('the_content', 'so226099_filter_p_tags_on_images');\n</code></pre>\n"
}
] |
2016/05/09
|
[
"https://wordpress.stackexchange.com/questions/226099",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93768/"
] |
I'm trying to stop the WordPress from automatically wrapping `<img>`s with `<p>` tags. I've tried this recommended snippet in my `functions.php`:
```
function filter_ptags_on_images($content){ // Remove p tags from around images
return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}
add_filter('the_content', 'filter_ptags_on_images');
```
This doesn't works if an image is the **first** element in a post or page. When an image comes before any text, the image gets wrapped with `<p>` tags once again. Any ideas?
|
this is a function, that unwraps images from p tags inside the\_content
```
/**
* WP: Unwrap images from <p> tag
* @param $content
* @return mixed
*/
function so226099_filter_p_tags_on_images( $content ) {
$content = preg_replace('/<p>\\s*?(<a .*?><img.*?><\\/a>|<img.*?>)?\\s*<\\/p>/s', '\1', $content);
return $content;
}
add_filter('the_content', 'so226099_filter_p_tags_on_images');
```
|
226,112 |
<p>I have this code that generates a link to a random post in my blog:</p>
<pre><code><?php
$posts = get_posts('orderby=rand&numberposts=1');
foreach($posts as $post): ?>
<a href="<?php the_permalink(); ?>" title="Random Post from Our Blog" style="float:right;" class="random-widget">
<span class="fa-random" style="font-family:FontAwesome;float:right;"></span>
</a>
<?php endforeach;
wp_reset_postdata(); ?>
</code></pre>
<p>I replaced <code>wp_reset_query()</code> with <code>wp_reset_postdata()</code> after reading <a href="https://wordpress.stackexchange.com/questions/44522/random-post-page-inside-post-loop-problem" title="this post">this question</a> but it's not working for me. All of my pages are displaying random post content instead of the page content. This is called in my action bar, above the menu.</p>
<h2>Update</h2>
<p>After several iterations, my code now closely resembles that found <a href="https://codex.wordpress.org/Template_Tags/get_posts#Reset_after_Postlists_with_offset" rel="nofollow noreferrer" title="here">in the Codex </a> and I'm still experiencing the same problem. Here's what I've got so far:</p>
<pre><code><?php
global $post;
$args = array('orderby'=>'rand','numberposts'=>'1','offset'=>'0');
$posts = get_posts($args);
foreach($posts as $post): setup_postdata($post); ?>
<a href="<?php the_permalink(); ?>" title="Random Post from Our Blog" style="float:right;" class="random-widget">
<span class="fa-random" style="font-family:FontAwesome;float:right;"></span>
</a>
<?php endforeach;
wp_reset_postdata(); ?>
</code></pre>
|
[
{
"answer_id": 226113,
"author": "The Maniac",
"author_id": 10966,
"author_profile": "https://wordpress.stackexchange.com/users/10966",
"pm_score": 0,
"selected": false,
"text": "<p>I think you just need to add a call to <code>setup_postdata</code>. Otherwise your code looks like it should work as intended:\n </p>\n\n<pre><code><?php foreach($posts as $post): setup_postdata($post); ?>\n <a href=\"<?php the_permalink(); ?>\" title=\"Random Post from Our Blog\" style=\"float:right;\" class=\"random-widget\"><span class=\"fa-random\" style=\"font-family:FontAwesome;float:right;\"></span></a>\n<?php endforeach; wp_reset_postdata(); ?>\n</code></pre>\n\n<p>(Note: I used colons instead of brackets, its easier to follow in my opinion but completely unnecessary)</p>\n"
},
{
"answer_id": 226114,
"author": "KingRichard",
"author_id": 43473,
"author_profile": "https://wordpress.stackexchange.com/users/43473",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, thanks to The Maniac for all the help troublshooting.</p>\n\n<p>Looks like I had to take this completely outside the loop and call the WP_Query class on a new variable to make it happen.</p>\n\n<p>Here's what worked:</p>\n\n<pre><code><?php\n$query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1' ) );\n\nwhile ( $query->have_posts() ) : $query->the_post(); ?>\n\n <a href=\"<?php the_permalink(); ?>\" title=\"Random Post from Our Blog\" style=\"float:right;\" class=\"random-widget\">\n <span class=\"fa-random\" style=\"font-family:FontAwesome;float:right;\"></span>\n </a>\n\n<?php endwhile;\nwp_reset_postdata(); ?>\n</code></pre>\n"
}
] |
2016/05/09
|
[
"https://wordpress.stackexchange.com/questions/226112",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43473/"
] |
I have this code that generates a link to a random post in my blog:
```
<?php
$posts = get_posts('orderby=rand&numberposts=1');
foreach($posts as $post): ?>
<a href="<?php the_permalink(); ?>" title="Random Post from Our Blog" style="float:right;" class="random-widget">
<span class="fa-random" style="font-family:FontAwesome;float:right;"></span>
</a>
<?php endforeach;
wp_reset_postdata(); ?>
```
I replaced `wp_reset_query()` with `wp_reset_postdata()` after reading [this question](https://wordpress.stackexchange.com/questions/44522/random-post-page-inside-post-loop-problem "this post") but it's not working for me. All of my pages are displaying random post content instead of the page content. This is called in my action bar, above the menu.
Update
------
After several iterations, my code now closely resembles that found [in the Codex](https://codex.wordpress.org/Template_Tags/get_posts#Reset_after_Postlists_with_offset "here") and I'm still experiencing the same problem. Here's what I've got so far:
```
<?php
global $post;
$args = array('orderby'=>'rand','numberposts'=>'1','offset'=>'0');
$posts = get_posts($args);
foreach($posts as $post): setup_postdata($post); ?>
<a href="<?php the_permalink(); ?>" title="Random Post from Our Blog" style="float:right;" class="random-widget">
<span class="fa-random" style="font-family:FontAwesome;float:right;"></span>
</a>
<?php endforeach;
wp_reset_postdata(); ?>
```
|
Ok, thanks to The Maniac for all the help troublshooting.
Looks like I had to take this completely outside the loop and call the WP\_Query class on a new variable to make it happen.
Here's what worked:
```
<?php
$query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1' ) );
while ( $query->have_posts() ) : $query->the_post(); ?>
<a href="<?php the_permalink(); ?>" title="Random Post from Our Blog" style="float:right;" class="random-widget">
<span class="fa-random" style="font-family:FontAwesome;float:right;"></span>
</a>
<?php endwhile;
wp_reset_postdata(); ?>
```
|
226,117 |
<p>I'm new to WordPress and I'm hoping to display post formats differently on the home page; sort of like this image:</p>
<p><img src="https://i.stack.imgur.com/ZsJNe.jpg" alt="homepage"></p>
<p>The problem is that the theme I'm using is very different than other themes I've seen, <strong>the loop is in a function</strong>. </p>
<p>In my <code>index.php</code>, I have</p>
<pre><code><?php
if(have_posts()) :
while(have_posts()) : the_post();
echo cool_post_article_normal_block();
endwhile;
endif;
?>
</code></pre>
<p>In the function it says:</p>
<pre><code>function cool_post_article_normal_block ($usecategory = false)
{
add_filter( 'excerpt_length', 'cool_article_excerpt_latest_length', 999 );
add_filter('excerpt_more', 'cool_article_excerpt_latest_more');
$timeformat = "<time class='post-date' datetime='" . get_the_time("Y-m-d H:i:s") . "'>" . get_the_time("F j, Y ") . "</time>";
$categoryarray = get_the_category();
$categorytext = '';
if(!empty($categoryarray))
$categorytext = "<span class='post-category'><a href='" . get_category_link($categoryarray[0]->term_id) . "' rel='category'>" . $categoryarray[0]->name . "</a></span>";
$authorurl = get_author_posts_url(get_the_author_meta('ID'));
$authorname = apply_filters('cool_get_author_name', null);
$authortext = '<span class="post-author">'. __('By', 'cool_textdomain') . ' <a href="' . $authorurl .'" rel="author">' . $authorname .'</a></span>';
$firsttext = $authortext;
if($usecategory) {
$firsttext = $categorytext;
}
$post_class = get_post_class(array('review-list', 'clearfix'), get_the_ID());
if(is_sticky()) {
$htmlcontent =
'<article class="'. implode(' ', $post_class) .'">
<div class="col-md-6">
' . apply_filters('cool_featured_figure_lazy', null, 'half-post-featured') . '
</div>
<div class="col-md-6">
<div class="">
<header class="content">
<h2 class="post-title"><a href="'. get_permalink(get_the_ID()) .'">'. get_the_title() .'</a></h2>
</header>
<div class="post-meta">
' . $firsttext . '
' . $timeformat . '
</div>
<div class="post-excerpt">
<p>'. get_the_excerpt() .'</p>
</div>
</div>
</div>
</article>';
} else {
$htmlcontent =
'<article class="'. implode(' ', $post_class) .'">
<div class="col-md-5">
' . apply_filters('cool_featured_figure_lazy', null, 'half-post-featured') . '
</div>
<div class="col-md-7">
<div class="">
<header class="content">
<h2 class="post-title"><a href="'. get_permalink(get_the_ID()) .'">'. get_the_title() .'</a></h2>
</header>
<div class="post-meta">
' . $firsttext . '
' . $timeformat . '
</div>
<div class="post-excerpt">
<p>'. get_the_excerpt() .'</p>
</div>
</div>
</div>
</article>';
}
remove_filter( 'excerpt_length', 'cool_article_excerpt_latest_length');
remove_filter( 'excerpt_more', 'cool_article_excerpt_latest_more');
return $htmlcontent;
}
</code></pre>
<p>What I understand is that I'm supposed to modify between <code><article></article></code> but what I don't know how to do is <strong>get the post format</strong> conditionally; especially since there is already a sticky conditional-- and I don't know PHP well :( </p>
<p>I'm very new to PHP so I'm unsure how to do this. I have several post formats activated: <code>quote</code>, <code>video</code>, <code>gallery</code>, <code>audio</code> and <code>image</code>. </p>
<p>I'd like the loop to go something like:</p>
<pre><code>if (sticky) {
if (quote)
show title only
} elseif (video, audio, gallery) {
show title
show excerpt
} elseif(image){
show title
show featured image
} else {
if (quote) {
show title only
}elseif (video, audio, gallery){
show title
show excerpt
} elseif (image) {
show title
show featured image
}
</code></pre>
|
[
{
"answer_id": 226124,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>Looking at your list, you are really only changing the default result for excerpts for the image and quote formats (at the moment), you can remove those using <code>the_excerpt</code> filter...</p>\n\n<pre><code>add_filter('the_excerpt','custom_post_format_excerpt',99);\nfunction custom_post_format_excerpt() {\n $noexcerptformats = array('quote','image');\n if (has_post_format($noexcerptformats)) {$excerpt = '';}\n return $excerpt;\n}\n</code></pre>\n\n<p>It looks like your theme has a custom filter for the thumbnail called <code>cool_featured_figure_lazy</code> with two arguments... you might try something like this to remove the featured image for anything but image post formats (and standard posts):</p>\n\n<pre><code>add_filter('cool_featured_figure_lazy','custom_post_format_thumbnail',99,2);\nfunction custom_post_format_thumbnail($thumbnail,$class) {\n $nothumbnailformats = array('quote','video','audio','gallery');\n if (has_post_format($nothumbnailformats)) {$thumbnail = '';}\n return $thumbnail;\n}\n</code></pre>\n\n<p>If you need to you can change the title similarly, you can use the <code>the_title</code> filter for that... eg.</p>\n\n<pre><code>add_filter('the_title','custom_post_format_title',99);\nfunction custom_post_format_title($title) {\n if (is_sticky()) {$title = 'Featured: '.$title;}\n return $title;\n}\n</code></pre>\n"
},
{
"answer_id": 226157,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": true,
"text": "<p>The best way to do this is get the post format and then use the switch statement, like this:</p>\n\n<pre><code>$my_format = get_post_format ();\nswitch ($my_format) {\n case 'quote': $htmlcontent = ... ; break;\n case 'aside': $htmlcontent = ... ; break;\n and so on\n }\n</code></pre>\n\n<p>The function that builds up $htmlcontent starts with declaring some building blocks that are used later on (from $timeformat to $firsttext). You can improve on this by setting up larger blocks. The code as it is now, for instance, would already be better if it had blocks like this:</p>\n\n<pre><code>$post-title = '<header class=\"content\">\n <h2 class=\"post-title\"><a href=\"'. get_permalink(get_the_ID()) .'\">'. get_the_title() .'</a></h2>\n </header>';\n</code></pre>\n\n<p>This code is now duplicated, which is never a good idea.</p>\n"
}
] |
2016/05/09
|
[
"https://wordpress.stackexchange.com/questions/226117",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93779/"
] |
I'm new to WordPress and I'm hoping to display post formats differently on the home page; sort of like this image:

The problem is that the theme I'm using is very different than other themes I've seen, **the loop is in a function**.
In my `index.php`, I have
```
<?php
if(have_posts()) :
while(have_posts()) : the_post();
echo cool_post_article_normal_block();
endwhile;
endif;
?>
```
In the function it says:
```
function cool_post_article_normal_block ($usecategory = false)
{
add_filter( 'excerpt_length', 'cool_article_excerpt_latest_length', 999 );
add_filter('excerpt_more', 'cool_article_excerpt_latest_more');
$timeformat = "<time class='post-date' datetime='" . get_the_time("Y-m-d H:i:s") . "'>" . get_the_time("F j, Y ") . "</time>";
$categoryarray = get_the_category();
$categorytext = '';
if(!empty($categoryarray))
$categorytext = "<span class='post-category'><a href='" . get_category_link($categoryarray[0]->term_id) . "' rel='category'>" . $categoryarray[0]->name . "</a></span>";
$authorurl = get_author_posts_url(get_the_author_meta('ID'));
$authorname = apply_filters('cool_get_author_name', null);
$authortext = '<span class="post-author">'. __('By', 'cool_textdomain') . ' <a href="' . $authorurl .'" rel="author">' . $authorname .'</a></span>';
$firsttext = $authortext;
if($usecategory) {
$firsttext = $categorytext;
}
$post_class = get_post_class(array('review-list', 'clearfix'), get_the_ID());
if(is_sticky()) {
$htmlcontent =
'<article class="'. implode(' ', $post_class) .'">
<div class="col-md-6">
' . apply_filters('cool_featured_figure_lazy', null, 'half-post-featured') . '
</div>
<div class="col-md-6">
<div class="">
<header class="content">
<h2 class="post-title"><a href="'. get_permalink(get_the_ID()) .'">'. get_the_title() .'</a></h2>
</header>
<div class="post-meta">
' . $firsttext . '
' . $timeformat . '
</div>
<div class="post-excerpt">
<p>'. get_the_excerpt() .'</p>
</div>
</div>
</div>
</article>';
} else {
$htmlcontent =
'<article class="'. implode(' ', $post_class) .'">
<div class="col-md-5">
' . apply_filters('cool_featured_figure_lazy', null, 'half-post-featured') . '
</div>
<div class="col-md-7">
<div class="">
<header class="content">
<h2 class="post-title"><a href="'. get_permalink(get_the_ID()) .'">'. get_the_title() .'</a></h2>
</header>
<div class="post-meta">
' . $firsttext . '
' . $timeformat . '
</div>
<div class="post-excerpt">
<p>'. get_the_excerpt() .'</p>
</div>
</div>
</div>
</article>';
}
remove_filter( 'excerpt_length', 'cool_article_excerpt_latest_length');
remove_filter( 'excerpt_more', 'cool_article_excerpt_latest_more');
return $htmlcontent;
}
```
What I understand is that I'm supposed to modify between `<article></article>` but what I don't know how to do is **get the post format** conditionally; especially since there is already a sticky conditional-- and I don't know PHP well :(
I'm very new to PHP so I'm unsure how to do this. I have several post formats activated: `quote`, `video`, `gallery`, `audio` and `image`.
I'd like the loop to go something like:
```
if (sticky) {
if (quote)
show title only
} elseif (video, audio, gallery) {
show title
show excerpt
} elseif(image){
show title
show featured image
} else {
if (quote) {
show title only
}elseif (video, audio, gallery){
show title
show excerpt
} elseif (image) {
show title
show featured image
}
```
|
The best way to do this is get the post format and then use the switch statement, like this:
```
$my_format = get_post_format ();
switch ($my_format) {
case 'quote': $htmlcontent = ... ; break;
case 'aside': $htmlcontent = ... ; break;
and so on
}
```
The function that builds up $htmlcontent starts with declaring some building blocks that are used later on (from $timeformat to $firsttext). You can improve on this by setting up larger blocks. The code as it is now, for instance, would already be better if it had blocks like this:
```
$post-title = '<header class="content">
<h2 class="post-title"><a href="'. get_permalink(get_the_ID()) .'">'. get_the_title() .'</a></h2>
</header>';
```
This code is now duplicated, which is never a good idea.
|
226,167 |
<p>I am writing a function to query some information from a custom table in the database. It seems that I am unable to query the database on the field I need.</p>
<pre><code>function ch_details_from_id($id) {
global $wpdb;
$details = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "ch_guests WHERE key = '" . $id . "'", ARRAY_A);
return $details;
}
</code></pre>
<p>$id is currently '001'. If I search on any other field in the table, I get the expected results, but on this field nothing is returned.</p>
<p>If I run exactly the same query in phpMyAdmin, it works fine.</p>
|
[
{
"answer_id": 226168,
"author": "Badger",
"author_id": 66660,
"author_profile": "https://wordpress.stackexchange.com/users/66660",
"pm_score": -1,
"selected": false,
"text": "<p>The field name is a reserved name. Changing from <code>key</code> to <code>id</code> has solved the issue.</p>\n"
},
{
"answer_id": 226169,
"author": "fischi",
"author_id": 15680,
"author_profile": "https://wordpress.stackexchange.com/users/15680",
"pm_score": 2,
"selected": false,
"text": "<p>You should use <code>$wpdb->prepare</code> for queries, as it does all the sanitizing and escaping for you. Also, <code>key</code> is reserved as a field name in MySQL:</p>\n\n<pre><code>function ch_details_from_id($id) {\n\n global $wpdb;\n // or try using \" . $wpdb->prefix . \"ch_guests\n $query = \"SELECT * FROM $wpdb->ch_guests WHERE guest = %d\";\n $details = $wpdb->get_results( $wpdb->prepare( $query, $id ) );\n\n return $details;\n\n}\n</code></pre>\n\n<p>To debug, you can output the last query <code>$wpdb</code> has done.</p>\n"
},
{
"answer_id": 226172,
"author": "Arpita Hunka",
"author_id": 86864,
"author_profile": "https://wordpress.stackexchange.com/users/86864",
"pm_score": 2,
"selected": true,
"text": "<p>Here issue with the column name. You are using column <strong>key</strong> in the query which is the default keyword/index in mysql. </p>\n\n<p>For resolving this kind of issue just use the \"Grave accent(`)' symbol in the query for the column name, No need to change the column name. So in your case the right query is </p>\n\n<pre><code>$details = $wpdb->get_results(\"SELECT * FROM \" . $wpdb->prefix . \"ch_guests WHERE `key` = '\" . $id . \"'\", ARRAY_A);\n</code></pre>\n\n<p>Run the above query, This is working for me, so i believe will work for you as well.</p>\n"
}
] |
2016/05/10
|
[
"https://wordpress.stackexchange.com/questions/226167",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66660/"
] |
I am writing a function to query some information from a custom table in the database. It seems that I am unable to query the database on the field I need.
```
function ch_details_from_id($id) {
global $wpdb;
$details = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "ch_guests WHERE key = '" . $id . "'", ARRAY_A);
return $details;
}
```
$id is currently '001'. If I search on any other field in the table, I get the expected results, but on this field nothing is returned.
If I run exactly the same query in phpMyAdmin, it works fine.
|
Here issue with the column name. You are using column **key** in the query which is the default keyword/index in mysql.
For resolving this kind of issue just use the "Grave accent(`)' symbol in the query for the column name, No need to change the column name. So in your case the right query is
```
$details = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "ch_guests WHERE `key` = '" . $id . "'", ARRAY_A);
```
Run the above query, This is working for me, so i believe will work for you as well.
|
226,187 |
<p>I want to remove the coupon drop down feature and just have the input field and 'add coupon' button on the checkout page. Does anyone know how I can get rid of the dropdown feature?
Thank you in advance!</p>
<p>HTML:</p>
<pre><code>if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
if ( ! wc_coupons_enabled() ) {
return;
}
if ( ! WC()->cart->applied_coupons ) {
$info_message = apply_filters( 'woocommerce_checkout_coupon_message', __( 'Promo code?', 'woocommerce' ) . ' <a href="#" class="showcoupon">' . __( 'Click here to enter your code', 'woocommerce' ) . '</a>' );
wc_print_notice( $info_message, 'notice' );
}
?>
<form class="checkout_coupon" method="post" style="display:none">
<p class="form-row form-row-first">
<input type="text" name="coupon_code" class="input-text" placeholder="<?php esc_attr_e( 'Promo Code', 'woocommerce' ); ?>" id="coupon_code" value="" />
</p>
<p class="form-row form-row-last">
<input type="submit" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply', 'woocommerce' ); ?>" />
</p>
<div class="clear"></div>
</form>
</code></pre>
|
[
{
"answer_id": 226224,
"author": "Steven",
"author_id": 13118,
"author_profile": "https://wordpress.stackexchange.com/users/13118",
"pm_score": 0,
"selected": false,
"text": "<p>You can do that with css - the form is hidden by default, but can be targeted like this:</p>\n\n<pre><code>.woocommerce-checkout form.checkout_coupon{\n display:block\n}\n</code></pre>\n\n<p>(put that in style.css)</p>\n"
},
{
"answer_id": 355844,
"author": "Dip Patel",
"author_id": 172710,
"author_profile": "https://wordpress.stackexchange.com/users/172710",
"pm_score": 1,
"selected": false,
"text": "<p>You can try this action.\nPut this line into your active theme <strong>functions.php</strong> file</p>\n\n<pre><code>remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );\n</code></pre>\n"
},
{
"answer_id": 377105,
"author": "HK89",
"author_id": 179278,
"author_profile": "https://wordpress.stackexchange.com/users/179278",
"pm_score": 1,
"selected": false,
"text": "<p>Removing the Coupon Field Using Option</p>\n<p>If you are really fed up with the coupons, you can easily remove the coupon field altogether. To do that, go to the WooCommerce > Settings page, click on the βCheckoutβ tab. Uncheck the βEnable the use of couponsβ and click βSave Changesβ button. At this point, you no longer have the coupon field anywhere in your store.</p>\n<p><a href=\"https://i.stack.imgur.com/b0tjR.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/b0tjR.jpg\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 380961,
"author": "James Revillini",
"author_id": 133859,
"author_profile": "https://wordpress.stackexchange.com/users/133859",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://wordpress.stackexchange.com/a/226224/133859\">Steven</a> is correct, but new WooCommerce styles apply styles to that form differently now so the style code should be</p>\n<p><code>.woocommerce form.checkout_coupon { display:block !important; }</code></p>\n"
}
] |
2016/05/10
|
[
"https://wordpress.stackexchange.com/questions/226187",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93762/"
] |
I want to remove the coupon drop down feature and just have the input field and 'add coupon' button on the checkout page. Does anyone know how I can get rid of the dropdown feature?
Thank you in advance!
HTML:
```
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
if ( ! wc_coupons_enabled() ) {
return;
}
if ( ! WC()->cart->applied_coupons ) {
$info_message = apply_filters( 'woocommerce_checkout_coupon_message', __( 'Promo code?', 'woocommerce' ) . ' <a href="#" class="showcoupon">' . __( 'Click here to enter your code', 'woocommerce' ) . '</a>' );
wc_print_notice( $info_message, 'notice' );
}
?>
<form class="checkout_coupon" method="post" style="display:none">
<p class="form-row form-row-first">
<input type="text" name="coupon_code" class="input-text" placeholder="<?php esc_attr_e( 'Promo Code', 'woocommerce' ); ?>" id="coupon_code" value="" />
</p>
<p class="form-row form-row-last">
<input type="submit" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply', 'woocommerce' ); ?>" />
</p>
<div class="clear"></div>
</form>
```
|
You can try this action.
Put this line into your active theme **functions.php** file
```
remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );
```
|
226,211 |
<p>I am using a child theme but it does not display any images. I am reading a book which suggests the following: "There is a difference in calling images from parent themes and child themes: </p>
<p>for parent Theme:</p>
<pre><code> <?php echo get template_directory_uri(); ?>
</code></pre>
<p>for child Theme:</p>
<pre><code> <?php bloginfo('stylesheet_directory'); ?>
</code></pre>
<p>Unfortunately the book doesn't say where the relevant code should be inserted.<br>
Any ideas please.</p>
|
[
{
"answer_id": 226287,
"author": "Pim Schaaf",
"author_id": 25886,
"author_profile": "https://wordpress.stackexchange.com/users/25886",
"pm_score": 0,
"selected": false,
"text": "<p>Images that are uploaded through WordPress are saved to <code>/wp-content/uploads/</code> <em>independent</em> of your theme or child theme, and commonly accessed through helper functions (e.g. <code>the_post_thumbnail()</code>) that will output HTML, including the image path(s). Therefore I'm ruling out that this is what you are trying to do.</p>\n\n<p>Instead I'm assuming you are trying to load (static) assets from e.g. <code>/wp-content/(child-)theme/assets/images/</code>. This can be done anywhere in your theme, e.g. in a template; let's say <code>home.php</code>. I found the description on <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri</a> most helpful.</p>\n\n<p>In a template, you can do the following:</p>\n\n<p>Child theme syntax:</p>\n\n<pre><code><body>\n <img src=\"<?php echo get_stylesheet_directory_uri(); ?>/assets/images/image.png\" />\n</body>\n</code></pre>\n\n<blockquote>\n <p>In the event a child theme is being used, this function will return the child's theme directory URI. Use <code>get_template_directory_uri()</code> to avoid being overridden by a child theme.</p>\n</blockquote>\n\n<p>for a parent theme, the syntax would be:</p>\n\n<pre><code><body>\n <img src=\"<?php echo get_template_directory_uri(); ?>/assets/images/image.png\" />\n</body>\n</code></pre>\n\n<p>Similar references are often made when enqueuing scripts or stylesheets in <code>functions.php</code>:</p>\n\n<pre><code>/*\n * Enqueue a script with the correct path.\n */\nfunction wpdocs_scripts_method() {\n wp_enqueue_script(\n 'custom_script',\n get_template_directory_uri() . '/js/custom_script.js',\n array('jquery')\n );\n}\n</code></pre>\n\n<p>Last code example was contributed by bhlarsen on <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/get_template_directory_uri/</a></p>\n"
},
{
"answer_id": 284115,
"author": "klewis",
"author_id": 98671,
"author_profile": "https://wordpress.stackexchange.com/users/98671",
"pm_score": 2,
"selected": false,
"text": "<p>You could try the following if you have a child theme and trying to reference your images from that file location, onto your custom .php files...</p>\n\n<pre><code><img src=\"<?php echo get_stylesheet_directory_uri(); ?>/assets/images/your-custom-image.jpg\" />\n</code></pre>\n\n<p>Just make sure in your child theme location, you really have a child folder structure of...</p>\n\n<p>assets -> images</p>\n"
}
] |
2016/05/10
|
[
"https://wordpress.stackexchange.com/questions/226211",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93829/"
] |
I am using a child theme but it does not display any images. I am reading a book which suggests the following: "There is a difference in calling images from parent themes and child themes:
for parent Theme:
```
<?php echo get template_directory_uri(); ?>
```
for child Theme:
```
<?php bloginfo('stylesheet_directory'); ?>
```
Unfortunately the book doesn't say where the relevant code should be inserted.
Any ideas please.
|
You could try the following if you have a child theme and trying to reference your images from that file location, onto your custom .php files...
```
<img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/images/your-custom-image.jpg" />
```
Just make sure in your child theme location, you really have a child folder structure of...
assets -> images
|
226,216 |
<p>I'm learning how to build a WordPress plugin. In the sample plugin code, I have this PHP/HTML:</p>
<pre><code>ob_start();
// other plugin code
<?php function plugin_rvce_options_page() { ?>
<div>
<form action="options.php" method="post">
<?php settings_fields('plugin_options'); ?>
<?php do_settings_sections('plugin'); ?>
<input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
</form>
</div>
<?php } ?>
</code></pre>
<p>Initially, this was causing the warning "Headers already sent" before I found ob_start. After implementing ob_start I don't get the warnings.. but am I using it correctly by just adding ob_start at the top of my plugin file?</p>
|
[
{
"answer_id": 226218,
"author": "Steven",
"author_id": 13118,
"author_profile": "https://wordpress.stackexchange.com/users/13118",
"pm_score": 2,
"selected": false,
"text": "<p>No, this is not a correct use for <code>ob_start()</code>. You're getting the warning because your script is outputting code before the page headers are sent - meaning you're printing output before the html page.</p>\n\n<p>Without knowing what's going on in your <code>// other plugin code</code> it's difficult to say what's happening exactly. I would guess you're calling <code>plugin_rvce_options_page()</code> somewhere in the root of the functions.php file instead of in a function that outputs to an admin page. In any case, try and fix the issue and don't use <code>ob_start()</code> as a work-around.</p>\n"
},
{
"answer_id": 226319,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>You definitely shouldn't be using <code>ob_start()</code> to prevent premature outputting of html. Rather you should use <code>add_action()</code> at the top of the plugin to start outputting your code in the right place.</p>\n\n<p>For backend the usual hook is <code>add_action ('admin_init','your_main_function');</code></p>\n\n<p>For frontend the usual hook is <code>add_action ('wp_head','your_main_function');</code></p>\n\n<p>Here's a list of all available hooks: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference</a></p>\n"
},
{
"answer_id": 349719,
"author": "Eliut Islas",
"author_id": 171699,
"author_profile": "https://wordpress.stackexchange.com/users/171699",
"pm_score": 1,
"selected": false,
"text": "<p>The output is happening when you call the function plugin_rvce_options_page, not when you declare it.\nTry this:</p>\n\n<pre><code>// other plugin code\n\n<?php function plugin_rvce_options_page() { \nob_start();\n?>\n\n<div>\n\n <form action=\"options.php\" method=\"post\">\n\n <?php settings_fields('plugin_options'); ?>\n <?php do_settings_sections('plugin'); ?>\n\n <input name=\"Submit\" type=\"submit\" value=\"<?php esc_attr_e('Save Changes'); ?>\" />\n\n </form>\n\n</div>\n\n<?php \nreturn ob_get_clean();\n }\n ?>\n</code></pre>\n"
}
] |
2016/05/10
|
[
"https://wordpress.stackexchange.com/questions/226216",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93195/"
] |
I'm learning how to build a WordPress plugin. In the sample plugin code, I have this PHP/HTML:
```
ob_start();
// other plugin code
<?php function plugin_rvce_options_page() { ?>
<div>
<form action="options.php" method="post">
<?php settings_fields('plugin_options'); ?>
<?php do_settings_sections('plugin'); ?>
<input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
</form>
</div>
<?php } ?>
```
Initially, this was causing the warning "Headers already sent" before I found ob\_start. After implementing ob\_start I don't get the warnings.. but am I using it correctly by just adding ob\_start at the top of my plugin file?
|
No, this is not a correct use for `ob_start()`. You're getting the warning because your script is outputting code before the page headers are sent - meaning you're printing output before the html page.
Without knowing what's going on in your `// other plugin code` it's difficult to say what's happening exactly. I would guess you're calling `plugin_rvce_options_page()` somewhere in the root of the functions.php file instead of in a function that outputs to an admin page. In any case, try and fix the issue and don't use `ob_start()` as a work-around.
|
226,229 |
<p>I have a working query which returns a set of custom posts which are ordered by their package ID (ASC). For a query with 9 results this may return for example:</p>
<blockquote>
<p>4 posts (Post ID's 1,2,3,4) with Package ID 1</p>
<p>3 posts (Post ID's 5,6,7) with Package ID 2</p>
<p>2 posts (Post ID's 8,9) with Package ID 3</p>
</blockquote>
<p>When these posts are displayed they are always in the same order. In other words, they are displayed in order from Post ID 1 to Post ID 9.</p>
<p>What I am trying to achieve is to sort the results of each subset (defined by Package ID) randomly. In this way the posts would be displayed as such:</p>
<blockquote>
<p>Random display of Post ID's 1 through to 4 (eg 2,1,4,3)</p>
<p>Random display of Post ID's 5 through to 7 (eg 6,5,7)</p>
<p>Random display of Post ID's 8 through to 9 (eg 8,9)</p>
</blockquote>
<p>So the posts are still grouped by the Package ID but the posts within each package are displayed randomly.</p>
<p>This is how my current query looks:</p>
<pre><code>$args = array(
'post_type' => 'custom_post_type',
'post_status' => 'publish',
'posts_per_page' => 9,
'meta_key' => 'pkg_id',
'orderby' => 'pkg_id',
'order' => 'ASC'
);
</code></pre>
<p>What I thought 'might' work but doesn't:</p>
<pre><code>$args = array(
'post_type' => 'custom_post_type',
'post_status' => 'publish',
'posts_per_page' => 9,
'meta_key' => 'pkg_id',
'orderby' => array( 'pkg_id' => 'ASC', 'rand' )
);
</code></pre>
<p>Any suggestions as I am completely stumped!</p>
|
[
{
"answer_id": 226230,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 1,
"selected": false,
"text": "<p>Not possible with a single query you would have to do 3 seperate query each one targeting the different \"Package ID's\" and ordering those queries as rand.</p>\n\n<pre><code>$args1 = array(\n 'post_type' => 'custom_post_type',\n 'orderby' => 'rand',\n 'meta_query' => array(\n array(\n 'key' => 'pkg_id',\n 'value' => 1, // you will have to check if this is correct\n )\n )\n);\n\n$args2 = array(\n 'post_type' => 'custom_post_type',\n 'orderby' => 'rand',\n 'meta_query' => array(\n array(\n 'key' => 'pkg_id',\n 'value' => 2, // you will have to check if this is correct\n )\n )\n);\n\n$args3 = array(\n 'post_type' => 'custom_post_type',\n 'orderby' => 'rand',\n 'meta_query' => array(\n array(\n 'key' => 'pkg_id',\n 'value' => 3, // you will have to check if this is correct\n )\n )\n);\n</code></pre>\n\n<p>This will seperate your posts into their \"Package ID's\" and order each set as Random</p>\n"
},
{
"answer_id": 226250,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>There is no need to do an overrated amount of queries to accomplish this. you can still use <strong>only</strong> one query, <code>the_posts</code> filter and some PHP to sort your code as needed. </p>\n\n<p>I take that this is a custom query from what I read in your question, so we can do the following:</p>\n\n<ul>\n<li><p>First, we want to introduce a custom <code>WP_Query</code> parameter so that we can use that parameter as a trigger for our <code>the_posts</code> filter. We will call this parameter n <code>wpse_custom_sort</code> and it will take a value of <code>true</code> in order to trigger the filter</p></li>\n<li><p>Next, we will use the <code>the_posts</code> filter to sort the posts according to custom field, then sort those posts randomly per custom field and finally return the sorted posts</p></li>\n</ul>\n\n<h2>THE CODE</h2>\n\n<p>Just a few notes though</p>\n\n<ul>\n<li><p>The code is untested and needs at least PHP 5.4</p></li>\n<li><p>I have used <code>get_post_meta()</code> to return the custom field values per post, as you are using ACF, you might need to adjust this to use <code>get_field()</code>. I'm not familiar with ACF, so you will need to sort that part. The logic would still remain the same though</p></li>\n<li><p>Just remember, querying custom fields does not result in extra queries as they are cached, so this is a very lean, optimized way to accomplish your end goal</p></li>\n</ul>\n\n<p>Here is the code for the custom query. All you basically need to do is to add the extra parameter to your query args in your custom page template</p>\n\n<pre><code>// Run your query normally\n$args = [\n 'wpse_custom_sort' => true, // This parameter will trigger or the_posts filter\n // Your query args here\n];\n$q = new WP_Query( $args );\n\n// Your loop as normal\n</code></pre>\n\n<p>Now, we will run our filter (<em>this goes into <code>functions.php</code> or preferably into a custom plugin</em>)</p>\n\n<pre><code>/**\n * Function to flatten a multidimentional array (for later use)\n * \n * Credit to zdenko\n * @link https://gist.github.com/kohnmd/11197713\n */\nfunction flatten_array( $arg ) \n{\n return is_array( $arg ) \n ? \n array_reduce( $arg, function ( $c, $a ) \n { \n return array_merge( $c, flatten_array( $a ) ); \n }, [] ) \n : \n [$arg];\n}\n\n// The the_posts filter\nadd_filter( 'the_posts', function ( $posts, $q )\n{\n // First we need remove our filter\n remove_filter( current_filter(), __FUNCTION__ );\n\n // Check if our custom parameter is set and is true, if not, bail early\n if ( true !== $q->get( 'wpse_custom_sort' ) )\n return $posts; \n\n // Before we do any work, and to avoid WSOD, make sure that the flatten_array function exists\n if ( !function_exists( 'flatten_array' ) )\n return $posts;\n\n // Our custom parameter is available and true, lets continue\n // Loop through the posts\n $major_array = [];\n foreach ( $posts as $p ) {\n $meta = get_post_meta(\n $p->ID,\n 'pkg_id',\n true\n );\n\n // Bail if we do not have a $meta value, just to be safe\n if ( !$meta )\n continue;\n\n // Sanitize the value\n $meta = filter_var( $meta, FILTER_SANITIZE_STRING );\n\n // Lets build our array\n $major_array[$meta][] = $p;\n }\n\n // Make sure we have a value for $major_array, if not, bail\n if ( !$major_array )\n return $posts;\n\n // Lets randomize the posts under each custom field\n $sorted = [];\n foreach ( $major_array as $field ) \n $sorted[] = shuffle( $field );\n\n // Lets flatten and return the array of posts\n $posts = flatten_array( $sorted );\n\n return array_values( $posts );\n}, 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 226258,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>If we use:</p>\n\n<pre><code>$args = array( \n 'post_type' => 'custom_post_type',\n 'post_status' => 'publish',\n 'posts_per_page' => 9,\n 'meta_key' => 'pkg_id',\n 'orderby' => array( 'pkg_id' => 'ASC', 'rand' => 'DESC' )\n);\n</code></pre>\n\n<p>then we get the order part as:</p>\n\n<pre><code>ORDER BY wp_postmeta.meta_value ASC, RAND() DESC\n</code></pre>\n\n<p>This seems to work, but the DESC is not needed.</p>\n\n<p>But note that ordering by <code>RAND()</code> doesn't scale well. The method by @PieterGoosen might be better suited for you in that case.</p>\n"
},
{
"answer_id": 328820,
"author": "chrwald",
"author_id": 161312,
"author_profile": "https://wordpress.stackexchange.com/users/161312",
"pm_score": 0,
"selected": false,
"text": "<p>One addition to Pieter Goosen answer.</p>\n\n<p>I had to change his code at the end since shuffle($field) returns a boolen, not the shuffled array itself. So i got an array of booleans, not an array of (post-)arrays. To get the expected result i did the following:</p>\n\n<pre><code> //Instead of \n foreach ( $major_array as $field ) \n //Shuffle returns boolean, so $sorted will be a\n $sorted[] = shuffle( $field ); \n\n // I went with\n foreach ( $major_array as $field ) {\n shuffle( $field ); // 1. Shuffle $field, which is an array\n $sorted[] = $field; // Then add this \n }\n</code></pre>\n"
}
] |
2016/05/11
|
[
"https://wordpress.stackexchange.com/questions/226229",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64450/"
] |
I have a working query which returns a set of custom posts which are ordered by their package ID (ASC). For a query with 9 results this may return for example:
>
> 4 posts (Post ID's 1,2,3,4) with Package ID 1
>
>
> 3 posts (Post ID's 5,6,7) with Package ID 2
>
>
> 2 posts (Post ID's 8,9) with Package ID 3
>
>
>
When these posts are displayed they are always in the same order. In other words, they are displayed in order from Post ID 1 to Post ID 9.
What I am trying to achieve is to sort the results of each subset (defined by Package ID) randomly. In this way the posts would be displayed as such:
>
> Random display of Post ID's 1 through to 4 (eg 2,1,4,3)
>
>
> Random display of Post ID's 5 through to 7 (eg 6,5,7)
>
>
> Random display of Post ID's 8 through to 9 (eg 8,9)
>
>
>
So the posts are still grouped by the Package ID but the posts within each package are displayed randomly.
This is how my current query looks:
```
$args = array(
'post_type' => 'custom_post_type',
'post_status' => 'publish',
'posts_per_page' => 9,
'meta_key' => 'pkg_id',
'orderby' => 'pkg_id',
'order' => 'ASC'
);
```
What I thought 'might' work but doesn't:
```
$args = array(
'post_type' => 'custom_post_type',
'post_status' => 'publish',
'posts_per_page' => 9,
'meta_key' => 'pkg_id',
'orderby' => array( 'pkg_id' => 'ASC', 'rand' )
);
```
Any suggestions as I am completely stumped!
|
There is no need to do an overrated amount of queries to accomplish this. you can still use **only** one query, `the_posts` filter and some PHP to sort your code as needed.
I take that this is a custom query from what I read in your question, so we can do the following:
* First, we want to introduce a custom `WP_Query` parameter so that we can use that parameter as a trigger for our `the_posts` filter. We will call this parameter n `wpse_custom_sort` and it will take a value of `true` in order to trigger the filter
* Next, we will use the `the_posts` filter to sort the posts according to custom field, then sort those posts randomly per custom field and finally return the sorted posts
THE CODE
--------
Just a few notes though
* The code is untested and needs at least PHP 5.4
* I have used `get_post_meta()` to return the custom field values per post, as you are using ACF, you might need to adjust this to use `get_field()`. I'm not familiar with ACF, so you will need to sort that part. The logic would still remain the same though
* Just remember, querying custom fields does not result in extra queries as they are cached, so this is a very lean, optimized way to accomplish your end goal
Here is the code for the custom query. All you basically need to do is to add the extra parameter to your query args in your custom page template
```
// Run your query normally
$args = [
'wpse_custom_sort' => true, // This parameter will trigger or the_posts filter
// Your query args here
];
$q = new WP_Query( $args );
// Your loop as normal
```
Now, we will run our filter (*this goes into `functions.php` or preferably into a custom plugin*)
```
/**
* Function to flatten a multidimentional array (for later use)
*
* Credit to zdenko
* @link https://gist.github.com/kohnmd/11197713
*/
function flatten_array( $arg )
{
return is_array( $arg )
?
array_reduce( $arg, function ( $c, $a )
{
return array_merge( $c, flatten_array( $a ) );
}, [] )
:
[$arg];
}
// The the_posts filter
add_filter( 'the_posts', function ( $posts, $q )
{
// First we need remove our filter
remove_filter( current_filter(), __FUNCTION__ );
// Check if our custom parameter is set and is true, if not, bail early
if ( true !== $q->get( 'wpse_custom_sort' ) )
return $posts;
// Before we do any work, and to avoid WSOD, make sure that the flatten_array function exists
if ( !function_exists( 'flatten_array' ) )
return $posts;
// Our custom parameter is available and true, lets continue
// Loop through the posts
$major_array = [];
foreach ( $posts as $p ) {
$meta = get_post_meta(
$p->ID,
'pkg_id',
true
);
// Bail if we do not have a $meta value, just to be safe
if ( !$meta )
continue;
// Sanitize the value
$meta = filter_var( $meta, FILTER_SANITIZE_STRING );
// Lets build our array
$major_array[$meta][] = $p;
}
// Make sure we have a value for $major_array, if not, bail
if ( !$major_array )
return $posts;
// Lets randomize the posts under each custom field
$sorted = [];
foreach ( $major_array as $field )
$sorted[] = shuffle( $field );
// Lets flatten and return the array of posts
$posts = flatten_array( $sorted );
return array_values( $posts );
}, 10, 2 );
```
|
226,244 |
<p>I upgraded WordPress to 4.5.1 from 4.2.2 and it has broken the functionality I have extending the Walker class. The Walker extension:</p>
<pre><code>class ReturnWalker extends Walker{
public $db_fields = array( 'parent' => 'parent',
'id' => 'term_id' );
public $show_all = FALSE;
/*
*
* @param array
* @param object
* @param int
* @param
* @return NULL
*/
public function start_el( &$output, $category, $depth = 0, $args = array(), $current_object_id = 0) {
if( !is_array($output) )
$output = array();
$id = $this->db_fields['id'];
$parent = $this->db_fields['parent'];
if( $depth == 0 || (!$category->$parent) ){
$output[$category->term_id] = $category;
} else if( $depth > 0){
$this->search( $output, $category->$parent, $category );
}
}
/*
*
* @param array
* @param int
* @param object
*/
private function search( &$output, $key, $category){
$id = $this->db_fields['id'];
$parent = $this->db_fields['parent'];
if( count($output) ){
foreach( $output as $k => &$object){
if( $k == $key ){
$object->children[$category->term_id] = $category;
return;
} else if( isset($object->children[$key]) ){
$this->search( $object->children, $category->$parent, $category );
}
}
} else if( $this->show_all){
$output[$category->$id] = $category;
}
}
/*
* sets the field names used for id and parent id
* @param array(
* 'id' => string
* 'parent' => string
* )
* @return NULL
*/
public function setDbFields( array $db_fields){
$this->db_fields = array_merge( $this->db_fields, $db_fields );
}
}
</code></pre>
<p>takes categories retrieved by using "get_the_terms()" and passes it in to the walk method:</p>
<pre><code>$breadcrumbs = new ReturnWalker;
$category = get_the_terms( $post->ID, 'category' );
$struct = $breadcrumbs->walk( $category, 0 );
</code></pre>
<p>After some careful observation I noticed that $category is now an array of WP_Term objects and that the WP_Term class is final. This breaks the extension because it depended on the ability to add the property "children", but because the class is non-mutable, is no longer possible.</p>
<p>The end product is that the functionality would build out URLs and breadcrumbs based off of the custom taxonomy which the post lived under. Does anyone have any good solutions to this type of issue?</p>
<p><strong>Update</strong> -<br>
Creating a class that mimics WP_Terms and copying over the objects returned by get_the_terms() to my *_Terms class worked. Passing in the returned objects when instantiating my class hits the constructor and builds out a copy of the properties that I have control over without worrying about core code changes:</p>
<pre><code> $categoryTerms = get_the_terms( $post->ID, 'category' );
foreach( $categoryTerms as $categoryTerm ){
$category[] = new MyTerm( $categoryTerm );
}
$breadcrumbs = new MyWalker;
$struct = $breadcrumbs->walk( $category, 0, array());
</code></pre>
|
[
{
"answer_id": 226246,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Your original solution was a hack, and no surprise it failed. In general never add methods/attributes to objects that you do not control their class and future development.</p>\n\n<p>The right way is to create your own object to be passed to the walker. Pass to it the category object on construction and either populate fields is a similar way to the category object or write accesor functions for it (for full hacking points use <code>_get()</code> and <code>_set()</code> ;) ). Design it good enough and your walker code will not have to change at all, only the initialization.</p>\n"
},
{
"answer_id": 226701,
"author": "Jon Krane",
"author_id": 93845,
"author_profile": "https://wordpress.stackexchange.com/users/93845",
"pm_score": 1,
"selected": true,
"text": "<p>Update -\nCreating a class that mimics WP_Terms and copying over the objects returned by get_the_terms() to my *_Terms class worked. Passing in the returned objects when instantiating my class hits the constructor and builds out a copy of the properties that I have control over without worrying about core code changes:</p>\n\n<pre><code> $categoryTerms = get_the_terms( $post->ID, 'category' );\n\n foreach( $categoryTerms as $categoryTerm ){\n $category[] = new MyTerm( $categoryTerm );\n }\n\n $breadcrumbs = new MyWalker;\n $struct = $breadcrumbs->walk( $category, 0, array());\n</code></pre>\n"
}
] |
2016/05/11
|
[
"https://wordpress.stackexchange.com/questions/226244",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93845/"
] |
I upgraded WordPress to 4.5.1 from 4.2.2 and it has broken the functionality I have extending the Walker class. The Walker extension:
```
class ReturnWalker extends Walker{
public $db_fields = array( 'parent' => 'parent',
'id' => 'term_id' );
public $show_all = FALSE;
/*
*
* @param array
* @param object
* @param int
* @param
* @return NULL
*/
public function start_el( &$output, $category, $depth = 0, $args = array(), $current_object_id = 0) {
if( !is_array($output) )
$output = array();
$id = $this->db_fields['id'];
$parent = $this->db_fields['parent'];
if( $depth == 0 || (!$category->$parent) ){
$output[$category->term_id] = $category;
} else if( $depth > 0){
$this->search( $output, $category->$parent, $category );
}
}
/*
*
* @param array
* @param int
* @param object
*/
private function search( &$output, $key, $category){
$id = $this->db_fields['id'];
$parent = $this->db_fields['parent'];
if( count($output) ){
foreach( $output as $k => &$object){
if( $k == $key ){
$object->children[$category->term_id] = $category;
return;
} else if( isset($object->children[$key]) ){
$this->search( $object->children, $category->$parent, $category );
}
}
} else if( $this->show_all){
$output[$category->$id] = $category;
}
}
/*
* sets the field names used for id and parent id
* @param array(
* 'id' => string
* 'parent' => string
* )
* @return NULL
*/
public function setDbFields( array $db_fields){
$this->db_fields = array_merge( $this->db_fields, $db_fields );
}
}
```
takes categories retrieved by using "get\_the\_terms()" and passes it in to the walk method:
```
$breadcrumbs = new ReturnWalker;
$category = get_the_terms( $post->ID, 'category' );
$struct = $breadcrumbs->walk( $category, 0 );
```
After some careful observation I noticed that $category is now an array of WP\_Term objects and that the WP\_Term class is final. This breaks the extension because it depended on the ability to add the property "children", but because the class is non-mutable, is no longer possible.
The end product is that the functionality would build out URLs and breadcrumbs based off of the custom taxonomy which the post lived under. Does anyone have any good solutions to this type of issue?
**Update** -
Creating a class that mimics WP\_Terms and copying over the objects returned by get\_the\_terms() to my \*\_Terms class worked. Passing in the returned objects when instantiating my class hits the constructor and builds out a copy of the properties that I have control over without worrying about core code changes:
```
$categoryTerms = get_the_terms( $post->ID, 'category' );
foreach( $categoryTerms as $categoryTerm ){
$category[] = new MyTerm( $categoryTerm );
}
$breadcrumbs = new MyWalker;
$struct = $breadcrumbs->walk( $category, 0, array());
```
|
Update -
Creating a class that mimics WP\_Terms and copying over the objects returned by get\_the\_terms() to my \*\_Terms class worked. Passing in the returned objects when instantiating my class hits the constructor and builds out a copy of the properties that I have control over without worrying about core code changes:
```
$categoryTerms = get_the_terms( $post->ID, 'category' );
foreach( $categoryTerms as $categoryTerm ){
$category[] = new MyTerm( $categoryTerm );
}
$breadcrumbs = new MyWalker;
$struct = $breadcrumbs->walk( $category, 0, array());
```
|
226,252 |
<pre><code># Adds ability to add break tags on posts
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
add_filter( 'the_content', 'nl2br' );
add_filter( 'the_excerpt', 'nl2br' );
</code></pre>
<p>We had the above code in our custom plugin for years and it made the break tag work.</p>
<p>Well it still works. Except multiple line breaks do not work. We can put 50 break tags in a row and the text will just go to the next line. Problem is we need to copy/paste a lot of straight html and spacing is done using break tags.</p>
<p>So why did this stop working when going from 4.4.latest to 4.5.latest? And more importantly what can I do to get tinymce to just read what is there!!?? Also I did try to use the Advanced TinyMCE widget and show paragraph/breaks... That works again but not for multiple. (yes I understand people can have a nonbreaking space in between to show the line - this will involve a lot of work on our part and is truly ghetto)</p>
|
[
{
"answer_id": 246052,
"author": "sMyles",
"author_id": 51201,
"author_profile": "https://wordpress.stackexchange.com/users/51201",
"pm_score": 0,
"selected": false,
"text": "<p>When are you calling the code to remove and add the new filters? You can try calling them with a higher priority (if you're calling them from another hook).</p>\n\n<p>Chances are it's due to another plugin or theme doing it's own replacement on <code>the_content</code> ... whether it be calling wpautop itself or removing the <code>nl2br</code> filter.</p>\n\n<p>If it's removing the filter for <code>nl2br</code> you could just call your own function:</p>\n\n<pre><code>add_filter( 'the_content', 'myown_nl2br' );\nadd_filter( 'the_excerpt', 'myown_nl2br' );\n\nfunction myown_nl2br($string) { \n $string = str_replace(array(\"\\r\\n\", \"\\r\", \"\\n\"), \"<br />\", $string); \n return $string; \n} \n</code></pre>\n\n<p>Linebreak Reference: </p>\n\n<ul>\n<li>windows = \\r\\n </li>\n<li>unix = \\n </li>\n<li>osx/mac = \\r </li>\n</ul>\n\n<p>You could also just do a call to <code>nl2br()</code> in the function above, but with <code>str_replace</code> gives you an understanding of how it works, and technically <code>nl2br()</code> only inserts a <code><br/></code> in front of line break, doesn't actually remove the line break itself.</p>\n\n<hr>\n\n<p><strong>Tracking down the culprit:</strong></p>\n\n<p>Do a full search on your entire <code>wp-content</code> directory for <code>the_content</code>, and look for any matches where the filter is removed, added, etc. Also search for <code>nl2br</code> and <code>wpautop</code>, that should help track down the culprit.</p>\n\n<p>If for some reason the plugin or theme you find has a callback to a class object's method, the standard <code>remove_filter</code> will not work, here's a response to another question where I posted code to remove a filter when you don't have access to the class object:</p>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/239431/51201\">https://wordpress.stackexchange.com/a/239431/51201</a></p>\n"
},
{
"answer_id": 263016,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>From the comments, problems seems to be related to some plugin misbehaving.</p>\n"
}
] |
2016/05/11
|
[
"https://wordpress.stackexchange.com/questions/226252",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32393/"
] |
```
# Adds ability to add break tags on posts
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
add_filter( 'the_content', 'nl2br' );
add_filter( 'the_excerpt', 'nl2br' );
```
We had the above code in our custom plugin for years and it made the break tag work.
Well it still works. Except multiple line breaks do not work. We can put 50 break tags in a row and the text will just go to the next line. Problem is we need to copy/paste a lot of straight html and spacing is done using break tags.
So why did this stop working when going from 4.4.latest to 4.5.latest? And more importantly what can I do to get tinymce to just read what is there!!?? Also I did try to use the Advanced TinyMCE widget and show paragraph/breaks... That works again but not for multiple. (yes I understand people can have a nonbreaking space in between to show the line - this will involve a lot of work on our part and is truly ghetto)
|
From the comments, problems seems to be related to some plugin misbehaving.
|
226,256 |
<p>EDIT: Due to downvotes (with no comments!), I've edited this post to be a bit more specific...</p>
<p>Why isn't the following change working?</p>
<pre><code>$custom_message = get_the_title( $post->ID ) .''. $hash_tags;
</code></pre>
<p>to:</p>
<pre><code>$custom_message = get_the_content( $post->ID ) .' '. $hash_tags;
</code></pre>
<hr>
<p>Original Post</p>
<p>I'm trying to customise the text posted by Jetpack publicize to use the post content instead of the title as my posts don't have titles.
This used to work previously, but something seems to have changed in Jetpack which now defaults to using the title and URL. </p>
<p>The code in the Jetpack publicize module is as follows:</p>
<pre><code>function __construct() {
$this->default_message = Publicize_Util::build_sprintf( array(
/**
* Filter the default Publicize message.
*
* @module publicize
*
* @since 2.0.0
*
* @param string $this->default_message Publicize's default message. Default is the post title.
*/
apply_filters( 'wpas_default_message', $this->default_message ),
'title',
'url',
) );
$this->default_prefix = Publicize_Util::build_sprintf( array(
/**
* Filter the message prepended to the Publicize custom message.
*
* @module publicize
*
* @since 2.0.0
*
* @param string $this->default_prefix String prepended to the Publicize custom message.
*/
apply_filters( 'wpas_default_prefix', $this->default_prefix ),
'url',
) );
$this->default_suffix = Publicize_Util::build_sprintf( array(
/**
* Filter the message appended to the Publicize custom message.
*
* @module publicize
*
* @since 2.0.0
*
* @param string $this->default_suffix String appended to the Publicize custom message.
*/
apply_filters( 'wpas_default_suffix', $this->default_suffix ),
'url',
) );
</code></pre>
<p>I was wondering if it would be possible to add get_the_content into the wpas_default_message but haven't managed to get this working.</p>
<p>I also tried to modify the code from another plugin (by Jeremy Herve) which adds the post tags as hashtags as follows by <code>changing get_the_title</code> to <code>get_the_content</code> but it doesn't work:</p>
<pre><code>function tsj_publicize_hashtags() {
$post = get_post();
if ( ! empty( $post ) ) {
/* Grab the tags of the post */
$post_tags = get_the_tags( $post->ID );
/* Append tags to custom message */
if ( ! empty( $post_tags ) ) {
/* Create list of tags with hashtags in front of them */
$hash_tags = '';
foreach( $post_tags as $tag ) {
$hash_tags .= ' #' . $tag->name;
}
/* Create our custom message */
// $custom_message = get_the_title( $post->ID ) .''. $hash_tags;
$custom_message = get_the_content( $post->ID ) .' '. $hash_tags;
update_post_meta( $post->ID, '_wpas_mess', $custom_message );
}
}
}
/* Save that message */
function tsj_cust_pub_message_save() {
add_action( 'save_post', 'tsj_publicize_hashtags', 21 );
}
add_action( 'publish_post', 'tsj_cust_pub_message_save' );
}
</code></pre>
<p>Can anyone point me in the right direction please on how to get the post content to be used in the publicize text?</p>
|
[
{
"answer_id": 226279,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Just some general remarks:</p>\n\n<blockquote>\n <p>Why isn't the following change working?</p>\n\n<pre><code> $custom_message = get_the_title( $post->ID ) .''. $hash_tags;\n</code></pre>\n \n <p>to:</p>\n\n<pre><code> $custom_message = get_the_content( $post->ID ) .' '. $hash_tags;\n</code></pre>\n</blockquote>\n\n<p>Note that <code>get_the_content()</code> doesn't take a post ID as an input parameter and it depends on global variables, like <code>$pages</code> that's derived from <code>$post->post_content</code> (with some pagination adjustments), within the <code>WP_Query::setup_postdata()</code> method.</p>\n\n<p>This is how it's defined:</p>\n\n<pre><code>function get_the_content( $more_link_text = null, $strip_teaser = false ) {\n global $page, $more, $preview, $pages, $multipage;\n ...\n}\n</code></pre>\n\n<p>A starting point could be use</p>\n\n<pre><code>$post->post_content\n</code></pre>\n\n<p>if you have access to the <code>$post</code> object or </p>\n\n<pre><code>get_post_field( 'post_content', $post_ID );\n</code></pre>\n\n<p>if you only have the post ID and go from there.</p>\n\n<p>Note that if you need to use the <code>save_post</code> hook, you can get the post ID and post object from the callback:</p>\n\n<pre><code>do_action( 'save_post', $post_ID, $post, $update );\n</code></pre>\n\n<p>so you don't need to use <code>get_post()</code>.</p>\n\n<p>PS: I wonder if you can use this hook in JetPack (just skimmed through it):</p>\n\n<pre><code>do_action( 'publicize_save_meta', $submit_post, $post_id, $service_name, $connection );\n</code></pre>\n\n<p>but it seems to be fired for each services/connections.</p>\n"
},
{
"answer_id": 226281,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 0,
"selected": false,
"text": "<p>Complete code (thanks to @birgire) in case anyone else finds useful in the future:</p>\n\n<pre><code>// Append Tags as Hashtags to Jetpack publicise posts\nif ( class_exists( 'Jetpack' ) && Jetpack::is_module_active( 'publicize' ) ) {\n function tsj_publicize_hashtags() {\n $post = get_post();\n if ( ! empty( $post ) ) {\n /* Grab the tags and content of the post */\n $post_tags = get_the_tags( $post->ID );\n $content = get_post_field( 'post_content', $post->ID );\n //$content = $post->post_content;\n\n /* Append tags to custom message */\n if ( ! empty( $post_tags ) ) {\n /* Create list of tags with hashtags in front of them */\n $hash_tags = '';\n foreach( $post_tags as $tag ) {\n $hash_tags .= ' #' . $tag->name;\n }\n /* Create our custom message using content instead of title */\n $custom_message = $content . ' ' . $hash_tags; \n update_post_meta( $post->ID, '_wpas_mess', $custom_message );\n }\n }\n }\n /* Save that message */\n function tsj_cust_pub_message_save() {\n add_action( 'save_post', 'tsj_publicize_hashtags', 21 );\n }\n add_action( 'publish_post', 'tsj_cust_pub_message_save' );\n}\n</code></pre>\n"
}
] |
2016/05/11
|
[
"https://wordpress.stackexchange.com/questions/226256",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36980/"
] |
EDIT: Due to downvotes (with no comments!), I've edited this post to be a bit more specific...
Why isn't the following change working?
```
$custom_message = get_the_title( $post->ID ) .''. $hash_tags;
```
to:
```
$custom_message = get_the_content( $post->ID ) .' '. $hash_tags;
```
---
Original Post
I'm trying to customise the text posted by Jetpack publicize to use the post content instead of the title as my posts don't have titles.
This used to work previously, but something seems to have changed in Jetpack which now defaults to using the title and URL.
The code in the Jetpack publicize module is as follows:
```
function __construct() {
$this->default_message = Publicize_Util::build_sprintf( array(
/**
* Filter the default Publicize message.
*
* @module publicize
*
* @since 2.0.0
*
* @param string $this->default_message Publicize's default message. Default is the post title.
*/
apply_filters( 'wpas_default_message', $this->default_message ),
'title',
'url',
) );
$this->default_prefix = Publicize_Util::build_sprintf( array(
/**
* Filter the message prepended to the Publicize custom message.
*
* @module publicize
*
* @since 2.0.0
*
* @param string $this->default_prefix String prepended to the Publicize custom message.
*/
apply_filters( 'wpas_default_prefix', $this->default_prefix ),
'url',
) );
$this->default_suffix = Publicize_Util::build_sprintf( array(
/**
* Filter the message appended to the Publicize custom message.
*
* @module publicize
*
* @since 2.0.0
*
* @param string $this->default_suffix String appended to the Publicize custom message.
*/
apply_filters( 'wpas_default_suffix', $this->default_suffix ),
'url',
) );
```
I was wondering if it would be possible to add get\_the\_content into the wpas\_default\_message but haven't managed to get this working.
I also tried to modify the code from another plugin (by Jeremy Herve) which adds the post tags as hashtags as follows by `changing get_the_title` to `get_the_content` but it doesn't work:
```
function tsj_publicize_hashtags() {
$post = get_post();
if ( ! empty( $post ) ) {
/* Grab the tags of the post */
$post_tags = get_the_tags( $post->ID );
/* Append tags to custom message */
if ( ! empty( $post_tags ) ) {
/* Create list of tags with hashtags in front of them */
$hash_tags = '';
foreach( $post_tags as $tag ) {
$hash_tags .= ' #' . $tag->name;
}
/* Create our custom message */
// $custom_message = get_the_title( $post->ID ) .''. $hash_tags;
$custom_message = get_the_content( $post->ID ) .' '. $hash_tags;
update_post_meta( $post->ID, '_wpas_mess', $custom_message );
}
}
}
/* Save that message */
function tsj_cust_pub_message_save() {
add_action( 'save_post', 'tsj_publicize_hashtags', 21 );
}
add_action( 'publish_post', 'tsj_cust_pub_message_save' );
}
```
Can anyone point me in the right direction please on how to get the post content to be used in the publicize text?
|
Just some general remarks:
>
> Why isn't the following change working?
>
>
>
> ```
> $custom_message = get_the_title( $post->ID ) .''. $hash_tags;
>
> ```
>
> to:
>
>
>
> ```
> $custom_message = get_the_content( $post->ID ) .' '. $hash_tags;
>
> ```
>
>
Note that `get_the_content()` doesn't take a post ID as an input parameter and it depends on global variables, like `$pages` that's derived from `$post->post_content` (with some pagination adjustments), within the `WP_Query::setup_postdata()` method.
This is how it's defined:
```
function get_the_content( $more_link_text = null, $strip_teaser = false ) {
global $page, $more, $preview, $pages, $multipage;
...
}
```
A starting point could be use
```
$post->post_content
```
if you have access to the `$post` object or
```
get_post_field( 'post_content', $post_ID );
```
if you only have the post ID and go from there.
Note that if you need to use the `save_post` hook, you can get the post ID and post object from the callback:
```
do_action( 'save_post', $post_ID, $post, $update );
```
so you don't need to use `get_post()`.
PS: I wonder if you can use this hook in JetPack (just skimmed through it):
```
do_action( 'publicize_save_meta', $submit_post, $post_id, $service_name, $connection );
```
but it seems to be fired for each services/connections.
|
226,269 |
<p>I know I can get rid of some of the default WP theme files required using <code>get_template_part()</code> for instance. But some files still need to be present - for instance, how would I move page.php to a subfolder so it still works? I am also aware, that you can put you own page templates to a custom folder and they are being recognised normally. </p>
<p>I'm aware, that changing WP core hierarchy structure is probably not the best idea, but for developing specific pages (non-blog oriented) it just might be. I don't see how having many files in theme root is a good thing when you are trying to easily add a feature. </p>
<p>I know there are some similar questions out here, but none pointed to actual examples. Here are some:</p>
<ul>
<li><a href="https://wordpress.stackexchange.com/questions/65437/how-do-i-structure-my-theme-folder-to-avoid-one-huge-list-of-files">How do i structure my theme folder to avoid one huge list of files</a></li>
<li><a href="https://wordpress.stackexchange.com/questions/211632/can-i-put-my-wordpress-theme-files-in-another-folder">Can I put my Wordpress theme files in another folder?</a></li>
</ul>
<p>But can someone show an example of how to organise theme folder so that I would end up only with (roughly)</p>
<pre><code>- mytheme
-- functions
-- img
-- js
-- styles
-- languages
-- custom-templates
--- template-demo.php
--- ...
-- wp_template_parts
--- loop.php
--- pagination.php
--- comments.php
--- header.php
--- footer.php
--- sidebar.php
--- ...
-- wp_default_view_templates
--- page.php
--- single.php
--- 404.php
--- search.php
--- archive.php
--- ...
-- index.php
-- functions.php
-- style.css
</code></pre>
<p>where (for example) <code>wp_default_view_templates</code> folder consists of only WP default hierarchy templates.</p>
<p>Folder <code>wp_template_parts</code> includes default WP partials used multiple times.
(this already works via get_template_part())</p>
<p><code>views</code> folder would include my custom page templates such as template-customstuff.php etc.</p>
<p>I have functions and assets such as css/js managed all right now. The only thing bothering me still are all the WP files in the root of the theme. </p>
<p>Is this reorganisation really such a bad idea? </p>
|
[
{
"answer_id": 226279,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Just some general remarks:</p>\n\n<blockquote>\n <p>Why isn't the following change working?</p>\n\n<pre><code> $custom_message = get_the_title( $post->ID ) .''. $hash_tags;\n</code></pre>\n \n <p>to:</p>\n\n<pre><code> $custom_message = get_the_content( $post->ID ) .' '. $hash_tags;\n</code></pre>\n</blockquote>\n\n<p>Note that <code>get_the_content()</code> doesn't take a post ID as an input parameter and it depends on global variables, like <code>$pages</code> that's derived from <code>$post->post_content</code> (with some pagination adjustments), within the <code>WP_Query::setup_postdata()</code> method.</p>\n\n<p>This is how it's defined:</p>\n\n<pre><code>function get_the_content( $more_link_text = null, $strip_teaser = false ) {\n global $page, $more, $preview, $pages, $multipage;\n ...\n}\n</code></pre>\n\n<p>A starting point could be use</p>\n\n<pre><code>$post->post_content\n</code></pre>\n\n<p>if you have access to the <code>$post</code> object or </p>\n\n<pre><code>get_post_field( 'post_content', $post_ID );\n</code></pre>\n\n<p>if you only have the post ID and go from there.</p>\n\n<p>Note that if you need to use the <code>save_post</code> hook, you can get the post ID and post object from the callback:</p>\n\n<pre><code>do_action( 'save_post', $post_ID, $post, $update );\n</code></pre>\n\n<p>so you don't need to use <code>get_post()</code>.</p>\n\n<p>PS: I wonder if you can use this hook in JetPack (just skimmed through it):</p>\n\n<pre><code>do_action( 'publicize_save_meta', $submit_post, $post_id, $service_name, $connection );\n</code></pre>\n\n<p>but it seems to be fired for each services/connections.</p>\n"
},
{
"answer_id": 226281,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 0,
"selected": false,
"text": "<p>Complete code (thanks to @birgire) in case anyone else finds useful in the future:</p>\n\n<pre><code>// Append Tags as Hashtags to Jetpack publicise posts\nif ( class_exists( 'Jetpack' ) && Jetpack::is_module_active( 'publicize' ) ) {\n function tsj_publicize_hashtags() {\n $post = get_post();\n if ( ! empty( $post ) ) {\n /* Grab the tags and content of the post */\n $post_tags = get_the_tags( $post->ID );\n $content = get_post_field( 'post_content', $post->ID );\n //$content = $post->post_content;\n\n /* Append tags to custom message */\n if ( ! empty( $post_tags ) ) {\n /* Create list of tags with hashtags in front of them */\n $hash_tags = '';\n foreach( $post_tags as $tag ) {\n $hash_tags .= ' #' . $tag->name;\n }\n /* Create our custom message using content instead of title */\n $custom_message = $content . ' ' . $hash_tags; \n update_post_meta( $post->ID, '_wpas_mess', $custom_message );\n }\n }\n }\n /* Save that message */\n function tsj_cust_pub_message_save() {\n add_action( 'save_post', 'tsj_publicize_hashtags', 21 );\n }\n add_action( 'publish_post', 'tsj_cust_pub_message_save' );\n}\n</code></pre>\n"
}
] |
2016/05/11
|
[
"https://wordpress.stackexchange.com/questions/226269",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65585/"
] |
I know I can get rid of some of the default WP theme files required using `get_template_part()` for instance. But some files still need to be present - for instance, how would I move page.php to a subfolder so it still works? I am also aware, that you can put you own page templates to a custom folder and they are being recognised normally.
I'm aware, that changing WP core hierarchy structure is probably not the best idea, but for developing specific pages (non-blog oriented) it just might be. I don't see how having many files in theme root is a good thing when you are trying to easily add a feature.
I know there are some similar questions out here, but none pointed to actual examples. Here are some:
* [How do i structure my theme folder to avoid one huge list of files](https://wordpress.stackexchange.com/questions/65437/how-do-i-structure-my-theme-folder-to-avoid-one-huge-list-of-files)
* [Can I put my Wordpress theme files in another folder?](https://wordpress.stackexchange.com/questions/211632/can-i-put-my-wordpress-theme-files-in-another-folder)
But can someone show an example of how to organise theme folder so that I would end up only with (roughly)
```
- mytheme
-- functions
-- img
-- js
-- styles
-- languages
-- custom-templates
--- template-demo.php
--- ...
-- wp_template_parts
--- loop.php
--- pagination.php
--- comments.php
--- header.php
--- footer.php
--- sidebar.php
--- ...
-- wp_default_view_templates
--- page.php
--- single.php
--- 404.php
--- search.php
--- archive.php
--- ...
-- index.php
-- functions.php
-- style.css
```
where (for example) `wp_default_view_templates` folder consists of only WP default hierarchy templates.
Folder `wp_template_parts` includes default WP partials used multiple times.
(this already works via get\_template\_part())
`views` folder would include my custom page templates such as template-customstuff.php etc.
I have functions and assets such as css/js managed all right now. The only thing bothering me still are all the WP files in the root of the theme.
Is this reorganisation really such a bad idea?
|
Just some general remarks:
>
> Why isn't the following change working?
>
>
>
> ```
> $custom_message = get_the_title( $post->ID ) .''. $hash_tags;
>
> ```
>
> to:
>
>
>
> ```
> $custom_message = get_the_content( $post->ID ) .' '. $hash_tags;
>
> ```
>
>
Note that `get_the_content()` doesn't take a post ID as an input parameter and it depends on global variables, like `$pages` that's derived from `$post->post_content` (with some pagination adjustments), within the `WP_Query::setup_postdata()` method.
This is how it's defined:
```
function get_the_content( $more_link_text = null, $strip_teaser = false ) {
global $page, $more, $preview, $pages, $multipage;
...
}
```
A starting point could be use
```
$post->post_content
```
if you have access to the `$post` object or
```
get_post_field( 'post_content', $post_ID );
```
if you only have the post ID and go from there.
Note that if you need to use the `save_post` hook, you can get the post ID and post object from the callback:
```
do_action( 'save_post', $post_ID, $post, $update );
```
so you don't need to use `get_post()`.
PS: I wonder if you can use this hook in JetPack (just skimmed through it):
```
do_action( 'publicize_save_meta', $submit_post, $post_id, $service_name, $connection );
```
but it seems to be fired for each services/connections.
|
226,292 |
<p>If the answer is case-by-case basis, check out this blog post: <a href="http://www.inquisitr.com/3078539/starting-in-west-virginia-bernie-sanders-could-win-8-of-the-next-9-primaries/" rel="nofollow">http://www.inquisitr.com/3078539/starting-in-west-virginia-bernie-sanders-could-win-8-of-the-next-9-primaries/</a></p>
<p>Does the title and description of images ever get shown on WordPress sites?</p>
|
[
{
"answer_id": 226279,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Just some general remarks:</p>\n\n<blockquote>\n <p>Why isn't the following change working?</p>\n\n<pre><code> $custom_message = get_the_title( $post->ID ) .''. $hash_tags;\n</code></pre>\n \n <p>to:</p>\n\n<pre><code> $custom_message = get_the_content( $post->ID ) .' '. $hash_tags;\n</code></pre>\n</blockquote>\n\n<p>Note that <code>get_the_content()</code> doesn't take a post ID as an input parameter and it depends on global variables, like <code>$pages</code> that's derived from <code>$post->post_content</code> (with some pagination adjustments), within the <code>WP_Query::setup_postdata()</code> method.</p>\n\n<p>This is how it's defined:</p>\n\n<pre><code>function get_the_content( $more_link_text = null, $strip_teaser = false ) {\n global $page, $more, $preview, $pages, $multipage;\n ...\n}\n</code></pre>\n\n<p>A starting point could be use</p>\n\n<pre><code>$post->post_content\n</code></pre>\n\n<p>if you have access to the <code>$post</code> object or </p>\n\n<pre><code>get_post_field( 'post_content', $post_ID );\n</code></pre>\n\n<p>if you only have the post ID and go from there.</p>\n\n<p>Note that if you need to use the <code>save_post</code> hook, you can get the post ID and post object from the callback:</p>\n\n<pre><code>do_action( 'save_post', $post_ID, $post, $update );\n</code></pre>\n\n<p>so you don't need to use <code>get_post()</code>.</p>\n\n<p>PS: I wonder if you can use this hook in JetPack (just skimmed through it):</p>\n\n<pre><code>do_action( 'publicize_save_meta', $submit_post, $post_id, $service_name, $connection );\n</code></pre>\n\n<p>but it seems to be fired for each services/connections.</p>\n"
},
{
"answer_id": 226281,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 0,
"selected": false,
"text": "<p>Complete code (thanks to @birgire) in case anyone else finds useful in the future:</p>\n\n<pre><code>// Append Tags as Hashtags to Jetpack publicise posts\nif ( class_exists( 'Jetpack' ) && Jetpack::is_module_active( 'publicize' ) ) {\n function tsj_publicize_hashtags() {\n $post = get_post();\n if ( ! empty( $post ) ) {\n /* Grab the tags and content of the post */\n $post_tags = get_the_tags( $post->ID );\n $content = get_post_field( 'post_content', $post->ID );\n //$content = $post->post_content;\n\n /* Append tags to custom message */\n if ( ! empty( $post_tags ) ) {\n /* Create list of tags with hashtags in front of them */\n $hash_tags = '';\n foreach( $post_tags as $tag ) {\n $hash_tags .= ' #' . $tag->name;\n }\n /* Create our custom message using content instead of title */\n $custom_message = $content . ' ' . $hash_tags; \n update_post_meta( $post->ID, '_wpas_mess', $custom_message );\n }\n }\n }\n /* Save that message */\n function tsj_cust_pub_message_save() {\n add_action( 'save_post', 'tsj_publicize_hashtags', 21 );\n }\n add_action( 'publish_post', 'tsj_cust_pub_message_save' );\n}\n</code></pre>\n"
}
] |
2016/05/11
|
[
"https://wordpress.stackexchange.com/questions/226292",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86497/"
] |
If the answer is case-by-case basis, check out this blog post: <http://www.inquisitr.com/3078539/starting-in-west-virginia-bernie-sanders-could-win-8-of-the-next-9-primaries/>
Does the title and description of images ever get shown on WordPress sites?
|
Just some general remarks:
>
> Why isn't the following change working?
>
>
>
> ```
> $custom_message = get_the_title( $post->ID ) .''. $hash_tags;
>
> ```
>
> to:
>
>
>
> ```
> $custom_message = get_the_content( $post->ID ) .' '. $hash_tags;
>
> ```
>
>
Note that `get_the_content()` doesn't take a post ID as an input parameter and it depends on global variables, like `$pages` that's derived from `$post->post_content` (with some pagination adjustments), within the `WP_Query::setup_postdata()` method.
This is how it's defined:
```
function get_the_content( $more_link_text = null, $strip_teaser = false ) {
global $page, $more, $preview, $pages, $multipage;
...
}
```
A starting point could be use
```
$post->post_content
```
if you have access to the `$post` object or
```
get_post_field( 'post_content', $post_ID );
```
if you only have the post ID and go from there.
Note that if you need to use the `save_post` hook, you can get the post ID and post object from the callback:
```
do_action( 'save_post', $post_ID, $post, $update );
```
so you don't need to use `get_post()`.
PS: I wonder if you can use this hook in JetPack (just skimmed through it):
```
do_action( 'publicize_save_meta', $submit_post, $post_id, $service_name, $connection );
```
but it seems to be fired for each services/connections.
|
226,303 |
<p>So i spent the entire day yesterday trying to achieve a full width responsive background video inside of a custom wordpress page template. </p>
<p>This is the bg-video code added to landing.php (my future landing page)</p>
<pre><code><div class="fullscreen-bg">
<video loop muted autoplay poster="public_html/wp-content/themes/gt3-wp-pure/page-templates/landingvid.gif" class="fullscreen-bg__video">
<source src="public_html/wp-content/themes/gt3-wp-pure/page-templates/landingvid.webm" type="video/webm">
<source src="public_html/wp-content/themes/gt3-wp-pure/page-templates/landingvid.mp4" type="video/mp4">
</video>
</code></pre>
<p></p>
<p>I have also included</p>
<pre><code><base href="http://angeloconstantinou.com/" />
</code></pre>
<p>This is the Themes.CSS dealing with the video:</p>
<pre><code>.fullscreen-bg {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
z-index: -100;
}
.fullscreen-bg__video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
@media (min-aspect-ratio: 16/9) {
.fullscreen-bg__video {
height: 300%;
top: -100%;
}
}
@media (max-aspect-ratio: 16/9) {
.fullscreen-bg__video {
width: 300%;
left: -100%;
}
}
@media (max-width: 767px) {
.fullscreen-bg {
background: url('../img/videoframe.jpg') center center / cover no-repeat;
}
.fullscreen-bg__video {
display: none;
}
}
</code></pre>
<p>Below is a screenshot of the error messages telling me the file couldn't be located. If i follow the exact path it is trying to pull the files from, I can see the files sitting there. (picture 2)</p>
<p><a href="https://i.stack.imgur.com/rpFbP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rpFbP.png" alt="404 error message"></a>
<a href="https://i.stack.imgur.com/A8O8q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A8O8q.png" alt="enter image description here"></a></p>
<p><strong>Things I have tried so far:</strong></p>
<ul>
<li>Moving landing.php out of a page-templates folder</li>
<li>Moving source files into every other possible directory</li>
<li>Using base URL re-write to stop Wordpress searching within a blog post ( i think i've got that right)</li>
<li>Writing full route url instead of source src='landingvid.mp4'</li>
</ul>
<p>I am not an expert with any of this and chances are I'm asking the wrong questions. Hopefully with all of the screenshots and snippets someone will be able to help.</p>
<p>the website & page in question is www.angeloconstantinou.com/landing.php - when i have this working I will set this as my static front page, with a button that leads to the usual front page / portfolio menu of the website.</p>
|
[
{
"answer_id": 226279,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Just some general remarks:</p>\n\n<blockquote>\n <p>Why isn't the following change working?</p>\n\n<pre><code> $custom_message = get_the_title( $post->ID ) .''. $hash_tags;\n</code></pre>\n \n <p>to:</p>\n\n<pre><code> $custom_message = get_the_content( $post->ID ) .' '. $hash_tags;\n</code></pre>\n</blockquote>\n\n<p>Note that <code>get_the_content()</code> doesn't take a post ID as an input parameter and it depends on global variables, like <code>$pages</code> that's derived from <code>$post->post_content</code> (with some pagination adjustments), within the <code>WP_Query::setup_postdata()</code> method.</p>\n\n<p>This is how it's defined:</p>\n\n<pre><code>function get_the_content( $more_link_text = null, $strip_teaser = false ) {\n global $page, $more, $preview, $pages, $multipage;\n ...\n}\n</code></pre>\n\n<p>A starting point could be use</p>\n\n<pre><code>$post->post_content\n</code></pre>\n\n<p>if you have access to the <code>$post</code> object or </p>\n\n<pre><code>get_post_field( 'post_content', $post_ID );\n</code></pre>\n\n<p>if you only have the post ID and go from there.</p>\n\n<p>Note that if you need to use the <code>save_post</code> hook, you can get the post ID and post object from the callback:</p>\n\n<pre><code>do_action( 'save_post', $post_ID, $post, $update );\n</code></pre>\n\n<p>so you don't need to use <code>get_post()</code>.</p>\n\n<p>PS: I wonder if you can use this hook in JetPack (just skimmed through it):</p>\n\n<pre><code>do_action( 'publicize_save_meta', $submit_post, $post_id, $service_name, $connection );\n</code></pre>\n\n<p>but it seems to be fired for each services/connections.</p>\n"
},
{
"answer_id": 226281,
"author": "TomC",
"author_id": 36980,
"author_profile": "https://wordpress.stackexchange.com/users/36980",
"pm_score": 0,
"selected": false,
"text": "<p>Complete code (thanks to @birgire) in case anyone else finds useful in the future:</p>\n\n<pre><code>// Append Tags as Hashtags to Jetpack publicise posts\nif ( class_exists( 'Jetpack' ) && Jetpack::is_module_active( 'publicize' ) ) {\n function tsj_publicize_hashtags() {\n $post = get_post();\n if ( ! empty( $post ) ) {\n /* Grab the tags and content of the post */\n $post_tags = get_the_tags( $post->ID );\n $content = get_post_field( 'post_content', $post->ID );\n //$content = $post->post_content;\n\n /* Append tags to custom message */\n if ( ! empty( $post_tags ) ) {\n /* Create list of tags with hashtags in front of them */\n $hash_tags = '';\n foreach( $post_tags as $tag ) {\n $hash_tags .= ' #' . $tag->name;\n }\n /* Create our custom message using content instead of title */\n $custom_message = $content . ' ' . $hash_tags; \n update_post_meta( $post->ID, '_wpas_mess', $custom_message );\n }\n }\n }\n /* Save that message */\n function tsj_cust_pub_message_save() {\n add_action( 'save_post', 'tsj_publicize_hashtags', 21 );\n }\n add_action( 'publish_post', 'tsj_cust_pub_message_save' );\n}\n</code></pre>\n"
}
] |
2016/05/11
|
[
"https://wordpress.stackexchange.com/questions/226303",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93651/"
] |
So i spent the entire day yesterday trying to achieve a full width responsive background video inside of a custom wordpress page template.
This is the bg-video code added to landing.php (my future landing page)
```
<div class="fullscreen-bg">
<video loop muted autoplay poster="public_html/wp-content/themes/gt3-wp-pure/page-templates/landingvid.gif" class="fullscreen-bg__video">
<source src="public_html/wp-content/themes/gt3-wp-pure/page-templates/landingvid.webm" type="video/webm">
<source src="public_html/wp-content/themes/gt3-wp-pure/page-templates/landingvid.mp4" type="video/mp4">
</video>
```
I have also included
```
<base href="http://angeloconstantinou.com/" />
```
This is the Themes.CSS dealing with the video:
```
.fullscreen-bg {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
z-index: -100;
}
.fullscreen-bg__video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
@media (min-aspect-ratio: 16/9) {
.fullscreen-bg__video {
height: 300%;
top: -100%;
}
}
@media (max-aspect-ratio: 16/9) {
.fullscreen-bg__video {
width: 300%;
left: -100%;
}
}
@media (max-width: 767px) {
.fullscreen-bg {
background: url('../img/videoframe.jpg') center center / cover no-repeat;
}
.fullscreen-bg__video {
display: none;
}
}
```
Below is a screenshot of the error messages telling me the file couldn't be located. If i follow the exact path it is trying to pull the files from, I can see the files sitting there. (picture 2)
[](https://i.stack.imgur.com/rpFbP.png)
[](https://i.stack.imgur.com/A8O8q.png)
**Things I have tried so far:**
* Moving landing.php out of a page-templates folder
* Moving source files into every other possible directory
* Using base URL re-write to stop Wordpress searching within a blog post ( i think i've got that right)
* Writing full route url instead of source src='landingvid.mp4'
I am not an expert with any of this and chances are I'm asking the wrong questions. Hopefully with all of the screenshots and snippets someone will be able to help.
the website & page in question is www.angeloconstantinou.com/landing.php - when i have this working I will set this as my static front page, with a button that leads to the usual front page / portfolio menu of the website.
|
Just some general remarks:
>
> Why isn't the following change working?
>
>
>
> ```
> $custom_message = get_the_title( $post->ID ) .''. $hash_tags;
>
> ```
>
> to:
>
>
>
> ```
> $custom_message = get_the_content( $post->ID ) .' '. $hash_tags;
>
> ```
>
>
Note that `get_the_content()` doesn't take a post ID as an input parameter and it depends on global variables, like `$pages` that's derived from `$post->post_content` (with some pagination adjustments), within the `WP_Query::setup_postdata()` method.
This is how it's defined:
```
function get_the_content( $more_link_text = null, $strip_teaser = false ) {
global $page, $more, $preview, $pages, $multipage;
...
}
```
A starting point could be use
```
$post->post_content
```
if you have access to the `$post` object or
```
get_post_field( 'post_content', $post_ID );
```
if you only have the post ID and go from there.
Note that if you need to use the `save_post` hook, you can get the post ID and post object from the callback:
```
do_action( 'save_post', $post_ID, $post, $update );
```
so you don't need to use `get_post()`.
PS: I wonder if you can use this hook in JetPack (just skimmed through it):
```
do_action( 'publicize_save_meta', $submit_post, $post_id, $service_name, $connection );
```
but it seems to be fired for each services/connections.
|
226,312 |
<p>I am working on a wordpress project with the following plugins :</p>
<ul>
<li>Woocommerce</li>
<li>Woocommerce product vendors</li>
<li>WP Job Manager</li>
<li>Wp Job Manager products</li>
</ul>
<p>I am trying to <strong>upgrade the user role</strong> after adding a job, so the user can access the wp-admin and edit his own product.</p>
<p>Now the user can be upgraded to Manage his Vendor dashboard but the problem that the first time he adds a Job he must login/logout in order to refresh his roles and be able to access the Dashboard.</p>
<p>Here what I tried : </p>
<pre><code> $current_user = wp_get_current_user();
//Code 1 :
$user_id = wp_update_user( array( 'ID' => $current_user->ID, 'role' => 'wc_product_vendors_manager_vendor' ) );
//Code 2 :
$user = new WP_User( $current_user->ID );
$user->remove_role( 'customer' );
$user->set_role( 'wc_product_vendors_manager_vendor' );
//Code 3 : ( this will make the user with 2 roles )
$current_user->add_role( 'wc_product_vendors_manager_vendor' );
</code></pre>
<p>Is it possible to achieve this by deleting the <strong>wp_cache_delete</strong> ... does anyone knows a good solution to upgrade user roles without login/logout ?</p>
<p>Thank you for you help!</p>
|
[
{
"answer_id": 226315,
"author": "Shane",
"author_id": 10555,
"author_profile": "https://wordpress.stackexchange.com/users/10555",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried logging in the user after your changes?</p>\n\n<p>Such as:</p>\n\n<pre><code> wp_set_current_user( $current_user->ID, $current_user->user_login );\n\n wp_set_auth_cookie( $current_user->ID );\n\n do_action( 'wp_login', $current_user->user_login );\n</code></pre>\n"
},
{
"answer_id": 226325,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 3,
"selected": true,
"text": "<p>I think you are on the right track, <code>wp_cache_delete</code> was what finally helped me get an auto-signup with auto-login plugin working... I have this from there:</p>\n\n<pre><code>wp_cache_delete($current_user->ID, 'users');\nwp_cache_delete($current_user->user_login, 'userlogins');\n</code></pre>\n\n<p>Then see what roles you get after that with:</p>\n\n<pre><code>$current_user = wp_get_current_user();\n</code></pre>\n"
}
] |
2016/05/11
|
[
"https://wordpress.stackexchange.com/questions/226312",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76008/"
] |
I am working on a wordpress project with the following plugins :
* Woocommerce
* Woocommerce product vendors
* WP Job Manager
* Wp Job Manager products
I am trying to **upgrade the user role** after adding a job, so the user can access the wp-admin and edit his own product.
Now the user can be upgraded to Manage his Vendor dashboard but the problem that the first time he adds a Job he must login/logout in order to refresh his roles and be able to access the Dashboard.
Here what I tried :
```
$current_user = wp_get_current_user();
//Code 1 :
$user_id = wp_update_user( array( 'ID' => $current_user->ID, 'role' => 'wc_product_vendors_manager_vendor' ) );
//Code 2 :
$user = new WP_User( $current_user->ID );
$user->remove_role( 'customer' );
$user->set_role( 'wc_product_vendors_manager_vendor' );
//Code 3 : ( this will make the user with 2 roles )
$current_user->add_role( 'wc_product_vendors_manager_vendor' );
```
Is it possible to achieve this by deleting the **wp\_cache\_delete** ... does anyone knows a good solution to upgrade user roles without login/logout ?
Thank you for you help!
|
I think you are on the right track, `wp_cache_delete` was what finally helped me get an auto-signup with auto-login plugin working... I have this from there:
```
wp_cache_delete($current_user->ID, 'users');
wp_cache_delete($current_user->user_login, 'userlogins');
```
Then see what roles you get after that with:
```
$current_user = wp_get_current_user();
```
|
226,363 |
<p><code>Wordpress version 4.5.1</code></p>
<p>I'm trying to dynamically update page titles on a particular template. After lots of digging and learning about the <code>wp_title()</code> changes, I'm attempting to use <code>document_title_parts</code>. However, I can't get the filter to run at all.</p>
<p>I'm in a child theme, <code>functions.php</code>:</p>
<pre><code>add_theme_support( 'title-tag' );
//add_filter("after_setup_theme", function(){ add_theme_support("title-tag"); });
add_filter( 'document_title_parts', function( $title )
{
error_log('here');
return $title;
}, 10, 1 );
</code></pre>
<p>I've tried both variations of adding theme support as shown above, but watching my log, nothing appears on page reload. That <code>error_log</code> was working with other functions (such as <code>wp_title</code>), so the error logging is working.</p>
<p>I've also tried <code>pre_get_document_title</code>, which does fire on page load, though I'm unable to get it to actually change the title. </p>
<p>So! I'm either using the filter wrong, didn't set up my theme correctly, or something else I'm unaware of. Any help would be greatly appreciated!</p>
<p><em>edit to add more detail</em></p>
<p>Attempting an init function, but that also isn't working: <a href="https://gist.github.com/anonymous/6db5af892a4cf4fb029655167d7002a4">https://gist.github.com/anonymous/6db5af892a4cf4fb029655167d7002a4</a></p>
<p>Also, while I've removed any reference to <code><title></code> from <code>header.php</code>, the actual site title is still showing up in the source.</p>
|
[
{
"answer_id": 230963,
"author": "Nikhil Chavan",
"author_id": 85061,
"author_profile": "https://wordpress.stackexchange.com/users/85061",
"pm_score": 2,
"selected": false,
"text": "<p>If the parent theme does not declare support for <code>title-tag</code> you can do it like this in child theme</p>\n\n<pre><code>/**\n * Theme support should be added on `after_setup_theme`\n */\nfunction add_theme_support_child() {\n\n add_theme_support( 'title-tag' );\n\n}\n\nadd_action( 'after_setup_theme', 'add_theme_support_child', 11 );\n</code></pre>\n\n<p>Filter <code>document_title_parts</code> expected return type array, like this, be sure to change the if condition as per your requirements, or remove it completely to change the title throughout the site just for testing if it works.</p>\n\n<pre><code>/**\n * Change title of a page conditionally\n * \n * @return $title - type array\n * $title['title'] - Page Title\n * $title['tagline'] - Site Tagline\n */\nfunction change_title_for_a_template( $title ) {\n\n // Check if current page template is 'template-homepage.php'\n if ( is_page_template( 'template-homepage.php' ) ) {\n $title['title'] = 'Changed title for a template';\n }\n\n return $title;\n\n}\n\nadd_filter( 'document_title_parts', 'change_title_for_a_template' );\n</code></pre>\n\n<p>Can you try thes two functions?</p>\n"
},
{
"answer_id": 231078,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>Having read your post from top to botom and bottom to top, you have in all probabilty a filter that is passing a title through the <code>pre_get_document_title</code> filter. The clue here the following statement:</p>\n\n<blockquote>\n <p>I've also tried <code>pre_get_document_title</code>, which does fire on page load, </p>\n</blockquote>\n\n<p>Looking at the <a href=\"https://developer.wordpress.org/reference/functions/wp_get_document_title/\" rel=\"nofollow\">soure code for <code>wp_get_document_title()</code></a>, we see the following code:</p>\n\n<pre><code>$title = apply_filters( 'pre_get_document_title', '' );\nif ( ! empty( $title ) ) {\n return $title;\n}\n</code></pre>\n\n<p>What this means is, whenever a non empty value is passes through the <code>pre_get_document_title</code> filter, the <code>wp_get_document_title()</code> function will return whatever value that was passed via the <code>pre_get_document_title</code> filter. It this case, the <code>document_title_separator</code> filter and the <code>document_title_parts</code> filter will never be executed as these only run after the <code>pre_get_document_title</code> filter. </p>\n\n<p>Looking at what you said a bit further on:</p>\n\n<blockquote>\n <p>...though I'm unable to get it to actually change the title.</p>\n</blockquote>\n\n<p>you definitely have a <code>pre_get_document_title</code> filter with authority which is overriding your instance of the same filter, and because of this filter, the function return whatever is passed to it which results in your <code>document_title_parts</code> filter not being executed. </p>\n\n<p>What you will need to do is is to use either <code>grep</code> or a good editor and search your entire <code>wp-content</code> folder for that <code>pre_get_document_title</code> filter. Once you located that filter, you can take it from there to remove that filter and replace it with your own</p>\n"
},
{
"answer_id": 231141,
"author": "tillinberlin",
"author_id": 26059,
"author_profile": "https://wordpress.stackexchange.com/users/26059",
"pm_score": 3,
"selected": false,
"text": "<p>After some experimenting I came to the following suggestion: could it be, that the <code><title></code> tag is \"hard coded\" inside your parent theme's <code>header.php</code>? If that is the case, you could try to remove the <code><title></code> tag from your child theme's <code>header.php</code> (copy your parent's <code>header.php</code> into your child theme folder) and then add the theme support back through the <code>functions.php</code>: </p>\n\n<pre><code>add_theme_support( 'title-tag' );\n</code></pre>\n\n<p>I'll try to explain what lead me to this suggestion: I tried as you and others suggested βΒ but it turned out that I found <strong>two <code><title></code> tags</strong> in the source code. The first one had the <em>standard title</em>, the second one the <em>modified title</em>. But (of course) in the browser title bar I could only see the default title.</p>\n\n<p>I then checked the <code>header.php</code> of the parent theme I used (twentyfourteen) and the <code><title></code> tag was indeed hard coded inside that template like this:</p>\n\n<pre><code><title><?php wp_title( '|', true, 'right' ); ?></title>\n</code></pre>\n\n<p>After I removed it, I added the following code to the child theme's <code>functions.php</code> and it worked:</p>\n\n<pre><code>/**\n * Theme support added\n */\n\nfunction add_theme_support_child() {\n\n add_theme_support( 'title-tag' );\n\n}\n\nadd_action( 'after_setup_theme', 'add_theme_support_child', 11 );\n\n\n/**\n * Change the title of a page\n * \n */\n\nfunction change_title_for_a_template( $title ) {\n\n// Check if current page template is 'template-homepage.php'\n// if ( is_page_template( 'template-homepage.php' ) ) {\n\n // change title parts here\n $title['title'] = 'My Title'; \n $title['tagline'] = 'My fancy tagline'; // optional\n $title['site'] = 'example.org'; //optional\n\n// }\n\nreturn $title; \n\n}\n\nadd_filter( 'document_title_parts', 'change_title_for_a_template', 10, 1 );\n</code></pre>\n\n<p>So it basically also worked before removing the <code><title></code> tag from the template βΒ only that there were then <strong>two</strong> <code><title></code> tags of which the later was ignored. Could this be the same problem with your theme?</p>\n\n<p><strong>Since wp 4.4.0 however the <code><title></code> tag is created dynamically</strong> by the function <code>_wp_render_title_tag()</code> which basically calls another function <code>wp_get_document_title()</code> and wraps the html tags around the result. Long story short: if your theme's <code>header.php</code> is missing the <code><title></code> tag, chances are that you can override the title directly through <code>pre_get_document_title</code> or <code>document_title_parts</code> as described <a href=\"https://stackoverflow.com/questions/34266520/wordpress-4-4-wp-title-filter-takes-no-effect-on-the-title-tag\">here</a>:</p>\n\n<p>1) change the title directly:</p>\n\n<pre><code>add_filter('pre_get_document_title', 'change_the_title');\nfunction change_the_title() {\n return 'The expected title';\n}\n</code></pre>\n\n<p>2) filtering the title parts:</p>\n\n<pre><code>add_filter('document_title_parts', 'filter_title_part');\nfunction filter_title_part($title) {\n return array('a', 'b', 'c');\n}\n</code></pre>\n"
},
{
"answer_id": 231195,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 5,
"selected": true,
"text": "<p>I ran your filter in my development area. It didn't work. Then I switched off the Yoast SEO plugin, which I knew was also messing with the page title. Then it worked. So my suggestion would be another plugin is messing with it.</p>\n\n<p>In the case of Yoast, it was a filter call to <code>pre_get_document_title</code> returning non empty. In that case <a href=\"https://developer.wordpress.org/reference/functions/wp_get_document_title/\" rel=\"noreferrer\"><code>wp_get_document_title</code></a> is short circuited and the rest of the function, including the <code>documents_title_parts</code> filter, is not evaluated, as you can see from the first lines of code:</p>\n\n<pre><code>$title = apply_filters( 'pre_get_document_title', '' );\nif ( ! empty( $title ) ) {\n return $title;\n }\n</code></pre>\n\n<p>So, I took your filter and changed the hook to <code>pre_get_document_title</code>. It didn't work. Then I changed the priority to a higher level than the same filter in Yoast. Then it worked. So, I don't know about your set-up, but I suggest you give this a try:</p>\n\n<pre><code>add_filter( 'pre_get_document_title', function( $title )\n {\n error_log('here');\n return $title;\n }, 999, 1 );\n</code></pre>\n"
}
] |
2016/05/12
|
[
"https://wordpress.stackexchange.com/questions/226363",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/7229/"
] |
`Wordpress version 4.5.1`
I'm trying to dynamically update page titles on a particular template. After lots of digging and learning about the `wp_title()` changes, I'm attempting to use `document_title_parts`. However, I can't get the filter to run at all.
I'm in a child theme, `functions.php`:
```
add_theme_support( 'title-tag' );
//add_filter("after_setup_theme", function(){ add_theme_support("title-tag"); });
add_filter( 'document_title_parts', function( $title )
{
error_log('here');
return $title;
}, 10, 1 );
```
I've tried both variations of adding theme support as shown above, but watching my log, nothing appears on page reload. That `error_log` was working with other functions (such as `wp_title`), so the error logging is working.
I've also tried `pre_get_document_title`, which does fire on page load, though I'm unable to get it to actually change the title.
So! I'm either using the filter wrong, didn't set up my theme correctly, or something else I'm unaware of. Any help would be greatly appreciated!
*edit to add more detail*
Attempting an init function, but that also isn't working: <https://gist.github.com/anonymous/6db5af892a4cf4fb029655167d7002a4>
Also, while I've removed any reference to `<title>` from `header.php`, the actual site title is still showing up in the source.
|
I ran your filter in my development area. It didn't work. Then I switched off the Yoast SEO plugin, which I knew was also messing with the page title. Then it worked. So my suggestion would be another plugin is messing with it.
In the case of Yoast, it was a filter call to `pre_get_document_title` returning non empty. In that case [`wp_get_document_title`](https://developer.wordpress.org/reference/functions/wp_get_document_title/) is short circuited and the rest of the function, including the `documents_title_parts` filter, is not evaluated, as you can see from the first lines of code:
```
$title = apply_filters( 'pre_get_document_title', '' );
if ( ! empty( $title ) ) {
return $title;
}
```
So, I took your filter and changed the hook to `pre_get_document_title`. It didn't work. Then I changed the priority to a higher level than the same filter in Yoast. Then it worked. So, I don't know about your set-up, but I suggest you give this a try:
```
add_filter( 'pre_get_document_title', function( $title )
{
error_log('here');
return $title;
}, 999, 1 );
```
|
226,398 |
<p>I have setup .htaccess to map a custom url to a custom php script. This page is not part of wordpress, but i want it to use the wordpress theme. At the top of the script I load up Wordpress. And from here i populate the global $post object with my own custom data. </p>
<pre><code>require_once('../wp-blog-header.php');
//change status to 200 from 404
//custom code to get data and populate the $post
include get_template_directory()."/page.php";
</code></pre>
<p>This works great in a web browser, but in some exceptions it causes problems. For example if i have a blog post in wordpress with a slug of <code>/some-post</code> and i have a custom page with a url of site.com/somethingelse. Wordpress generates a 301 redirect to <code>/some-post</code>. This occurs in the require_once, which means i cannot override it. It happens as soon as a call the wp-blog-header.php script. This means that google does not index this page correctly. Is there a way i can call the theme without wordpress redirecting or doing anything like this. </p>
|
[
{
"answer_id": 226399,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure this will be suitable to your case but you can try:</p>\n\n<pre><code>define('SHORTINIT',true); \n</code></pre>\n\n<p>before including <code>wp-blog-header.php</code> and many things will not load - perhaps the redirect will be one of them? </p>\n\n<p>(But, it does mean you may have to include a lot of <code>wp-includes</code> files manually too for many of the WordPress functions to be able to run without fatal errors.)</p>\n"
},
{
"answer_id": 226405,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": true,
"text": "<p>If you want the WordPress framework without the querying, use <code>wp-load.php</code>:</p>\n\n<pre><code>require '/path/to/wordpress/wp-load.php';\n</code></pre>\n"
}
] |
2016/05/12
|
[
"https://wordpress.stackexchange.com/questions/226398",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190834/"
] |
I have setup .htaccess to map a custom url to a custom php script. This page is not part of wordpress, but i want it to use the wordpress theme. At the top of the script I load up Wordpress. And from here i populate the global $post object with my own custom data.
```
require_once('../wp-blog-header.php');
//change status to 200 from 404
//custom code to get data and populate the $post
include get_template_directory()."/page.php";
```
This works great in a web browser, but in some exceptions it causes problems. For example if i have a blog post in wordpress with a slug of `/some-post` and i have a custom page with a url of site.com/somethingelse. Wordpress generates a 301 redirect to `/some-post`. This occurs in the require\_once, which means i cannot override it. It happens as soon as a call the wp-blog-header.php script. This means that google does not index this page correctly. Is there a way i can call the theme without wordpress redirecting or doing anything like this.
|
If you want the WordPress framework without the querying, use `wp-load.php`:
```
require '/path/to/wordpress/wp-load.php';
```
|
226,400 |
<p>I have a problem with ajax load more for my CustomPostType. I think i have mistake but don't know where. If it possible to edit my code, i will happy.</p>
<p><strong>UPDATE</strong></p>
<p>I have create div <code>cool</code> to paste in it loaded more post. After clicking load more i have 0 in div cool. What does it mean?</p>
<p><strong>In functions.php</strong></p>
<pre><code> add_shortcode( 'list-posts-basic', 'rmcc_post_listing_shortcode1' );
function rmcc_post_listing_shortcode1( $atts ) {
ob_start();
$query = new WP_Query( array(
'post_type' => 'imggal',
'order' => 'ASC',
'orderby' => 'title',
'posts_per_page' => 1,
) );
if ( $query->have_posts() ) { ?>
<ul id="ajaxx" class="clothes-listing">
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile;
wp_reset_postdata(); ?>
<div id="cool"></div>
<a id="more_posts" href="#">Load More</a>
</ul>
<?php $myvariable = ob_get_clean();
return $myvariable;
}
}
add_action('wp_ajax_nopriv_rmcc_post_listing_shortcode1', 'rmcc_post_listing_shortcode1');
add_action('wp_ajax_rmcc_post_listing_shortcode1', 'rmcc_post_listing_shortcode1');
</code></pre>
<p><strong>AJAX</strong></p>
<pre><code> (function($) {
$(document).ready(function($) {
$("#more_posts").on("click",function(e){ // When btn is pressed.
e.preventDefault();
$.ajax({
url: ajax_object.ajax_url,
data: {
'action' : 'rmcc_post_listing_shortcode1'
},
success: function (data) {
if (data.length > 0) {
$('#cool').html(data);
}
},
});
});
});
})(jQuery);
</code></pre>
<p>Please help me!</p>
|
[
{
"answer_id": 226417,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>This will (*should) fix your first problem:</p>\n\n<pre><code>function rmcc_post_listing_shortcode1( $atts ) {\n // No need for output buffering - AJAX handlers should ECHO their response\n // ob_start();\n\n // ..\n\n // So long, farewell\n // $myvariable = ob_get_clean();\n // return $myvariable;\n\n // Now terminate\n exit;\n}\n</code></pre>\n\n<p>Your second problem is that you are not implementing any kind of pagination/increment in your AJAX handler - \"load more\" will always load the same post.</p>\n"
},
{
"answer_id": 226418,
"author": "Cai",
"author_id": 81652,
"author_profile": "https://wordpress.stackexchange.com/users/81652",
"pm_score": 0,
"selected": false,
"text": "<p>Your first problem is that your AJAX function in <code>functions.php</code> should <code>echo</code> its results, not <code>return</code>. You also need a call to <code>wp_die()</code> at the end.</p>\n\n<p>I'm not completely sure what you are trying to do but it looks like half of your loop probably shouldn't be there. Currently you are outputing the whole <code>#ajaxx</code> list inside itself every time you click <code>#load-more</code>. Which at the <em>very least</em> will give you problems with duplicate IDs.</p>\n\n<p>I suspect what you want is:</p>\n\n<p><strong>whatever-page-template.php</strong></p>\n\n<pre><code>// Rest of page template and beginning of loop\n\n<ul id=\"ajaxx\" class=\"clothes-listing\">\n\n <?php while ( $query->have_posts() ) : $query->the_post(); ?>\n <li id=\"post-<?php the_ID(); ?>\" <?php post_class(); ?>>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n </li>\n <?php endwhile;\n wp_reset_postdata(); ?>\n\n <div id=\"cool\"></div>\n <a id=\"more_posts\" href=\"#\">Load More</a>\n</ul>\n\n// etc...\n</code></pre>\n\n<p><strong>functions.php</strong></p>\n\n<pre><code>function rmcc_post_listing_shortcode1( $atts )\n{\n ob_start();\n\n $query = new WP_Query( array(\n 'post_type' => 'imggal',\n 'order' => 'ASC',\n 'orderby' => 'title',\n 'posts_per_page' => 1,\n ));\n\n if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>\n <li id=\"post-<?php the_ID(); ?>\" <?php post_class(); ?>>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n </li>\n <?php endwhile; endif;\n wp_reset_postdata();\n\n $myvariable = ob_get_clean();\n echo $myvariable;\n\n wp_die();\n}\n</code></pre>\n\n<p>You are also always loading the same post so you need to implement some kind of pagination, but I would get the basic AJAX call fixed first!</p>\n\n<p>You can read more about AJAX in Wordpress (including debugging!) here:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/AJAX_in_Plugins\" rel=\"nofollow\">WordPress - AJAX in Plugins</a></li>\n</ul>\n"
},
{
"answer_id": 226423,
"author": "Darren Cooney",
"author_id": 12868,
"author_profile": "https://wordpress.stackexchange.com/users/12868",
"pm_score": -1,
"selected": false,
"text": "<p>You should consider giving the Ajax Load More WordPress plugin a try.\n<a href=\"https://wordpress.org/plugins/ajax-load-more/\" rel=\"nofollow\">https://wordpress.org/plugins/ajax-load-more/</a></p>\n"
}
] |
2016/05/12
|
[
"https://wordpress.stackexchange.com/questions/226400",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88709/"
] |
I have a problem with ajax load more for my CustomPostType. I think i have mistake but don't know where. If it possible to edit my code, i will happy.
**UPDATE**
I have create div `cool` to paste in it loaded more post. After clicking load more i have 0 in div cool. What does it mean?
**In functions.php**
```
add_shortcode( 'list-posts-basic', 'rmcc_post_listing_shortcode1' );
function rmcc_post_listing_shortcode1( $atts ) {
ob_start();
$query = new WP_Query( array(
'post_type' => 'imggal',
'order' => 'ASC',
'orderby' => 'title',
'posts_per_page' => 1,
) );
if ( $query->have_posts() ) { ?>
<ul id="ajaxx" class="clothes-listing">
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile;
wp_reset_postdata(); ?>
<div id="cool"></div>
<a id="more_posts" href="#">Load More</a>
</ul>
<?php $myvariable = ob_get_clean();
return $myvariable;
}
}
add_action('wp_ajax_nopriv_rmcc_post_listing_shortcode1', 'rmcc_post_listing_shortcode1');
add_action('wp_ajax_rmcc_post_listing_shortcode1', 'rmcc_post_listing_shortcode1');
```
**AJAX**
```
(function($) {
$(document).ready(function($) {
$("#more_posts").on("click",function(e){ // When btn is pressed.
e.preventDefault();
$.ajax({
url: ajax_object.ajax_url,
data: {
'action' : 'rmcc_post_listing_shortcode1'
},
success: function (data) {
if (data.length > 0) {
$('#cool').html(data);
}
},
});
});
});
})(jQuery);
```
Please help me!
|
This will (\*should) fix your first problem:
```
function rmcc_post_listing_shortcode1( $atts ) {
// No need for output buffering - AJAX handlers should ECHO their response
// ob_start();
// ..
// So long, farewell
// $myvariable = ob_get_clean();
// return $myvariable;
// Now terminate
exit;
}
```
Your second problem is that you are not implementing any kind of pagination/increment in your AJAX handler - "load more" will always load the same post.
|
226,403 |
<p>My problem is that I can't verify if some user insert an existing email into AJAX registration form. However my form is working fine, it's registering users and it's giving all other errors, like "invalid email" or "empty fields".
The only thing it doesn't disaply is <strong>the error for the existing emails</strong>.</p>
<pre><code>function ajax_register(){
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-register-nonce', 'security' );
$user_login = $_POST['user_login'];
$sanitized_user_login = sanitize_user( $user_login );
$user_email = $_POST['user_email'];
$user_pass = wp_generate_password( 12, false);
$user_tp = $_POST['user_tp'];
if(empty($user_tp)) $capa = 'subscriber';
else $capa = $user_tp;
//Adding errors
$newerrors = my_errors($user_email);
//CREATE USERS
$user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email, $capa );
if (is_wp_error($user_id)){
//VERIFYNG WITH DEFAULT ERRORS
} elseif (is_wp_error($newerrors)){
//VERIFYING WITH MY CUSTOM ERRORS
echo json_encode(array('loggedin'=>false, 'message'=>__($newerrors->get_error_message())));
} else {
//REGISTER USERS
}
die();
}
//MY CUSTOM ERROR FUNCTION
function my_errors($user_email) {
$errors = new WP_Error();
$user_email = apply_filters( 'user_registration_email', $user_email );
if ( $user_email == '' ) {
$errors->add( 'empty_email', __( 'Please, insert your email.') );
} elseif ( ! is_email( $user_email ) ) {
$errors->add( 'invalid_email', __( 'The email is not valid.') );
$user_email = '';
//THIS IS WHERE I CHECK THE EXISTING EMAIL ***
} elseif ( email_exists( $user_email ) ) {
$errors->add( 'registered', __( 'This email is already registered.' ) );
}
if ($errors->get_error_code())
return $errors;
}
</code></pre>
<p>*** At this point I verify if the <code>$user_email</code> is existing already. But when I test it the message isn't displayed and the form is stuck.</p>
<p>Is there a need of an <code>add_action</code>? Can you explain me where I'm wrong?
Thanks</p>
|
[
{
"answer_id": 226407,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 2,
"selected": true,
"text": "<p>Why are you making work hard for yourself? <code>wp_create_user</code> already checks if the email/login exists, which is also why your code is \"failing\" - <code>$user_id</code> will already be a <code>WP_Error</code>, so your <code>elseif ( is_wp_error( $newerrors ) )</code> never fires.</p>\n\n<p>All you need is:</p>\n\n<pre><code>$user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email, $capa );\n\nif ( is_wp_error( $user_id ) ) {\n wp_send_json( array(\n 'loggedin' => false,\n 'message' => $user_id->get_error_message(),\n ) );\n}\n\nexit;\n</code></pre>\n\n<p>Also note I've used the WordPress helper <a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json\" rel=\"nofollow\"><code>wp_send_json</code></a>, which is the <em>correct</em> way of sending JSON data back to the client.</p>\n"
},
{
"answer_id": 226411,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>You could create your own email_exists function to check it in a different way, I ended up doing this in a plugin as I was not getting consistent results with <code>email_exists</code> for some reason:</p>\n\n<pre><code>function check_email_exists($email) {\n global $wpdb;\n $user_id = $wpdb->get_var($wpdb->prepare(\"SELECT ID FROM \".$wpdb->users.\" WHERE user_email = '%s'\",$email));\n return $user_id;\n}\n</code></pre>\n"
}
] |
2016/05/12
|
[
"https://wordpress.stackexchange.com/questions/226403",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93927/"
] |
My problem is that I can't verify if some user insert an existing email into AJAX registration form. However my form is working fine, it's registering users and it's giving all other errors, like "invalid email" or "empty fields".
The only thing it doesn't disaply is **the error for the existing emails**.
```
function ajax_register(){
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-register-nonce', 'security' );
$user_login = $_POST['user_login'];
$sanitized_user_login = sanitize_user( $user_login );
$user_email = $_POST['user_email'];
$user_pass = wp_generate_password( 12, false);
$user_tp = $_POST['user_tp'];
if(empty($user_tp)) $capa = 'subscriber';
else $capa = $user_tp;
//Adding errors
$newerrors = my_errors($user_email);
//CREATE USERS
$user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email, $capa );
if (is_wp_error($user_id)){
//VERIFYNG WITH DEFAULT ERRORS
} elseif (is_wp_error($newerrors)){
//VERIFYING WITH MY CUSTOM ERRORS
echo json_encode(array('loggedin'=>false, 'message'=>__($newerrors->get_error_message())));
} else {
//REGISTER USERS
}
die();
}
//MY CUSTOM ERROR FUNCTION
function my_errors($user_email) {
$errors = new WP_Error();
$user_email = apply_filters( 'user_registration_email', $user_email );
if ( $user_email == '' ) {
$errors->add( 'empty_email', __( 'Please, insert your email.') );
} elseif ( ! is_email( $user_email ) ) {
$errors->add( 'invalid_email', __( 'The email is not valid.') );
$user_email = '';
//THIS IS WHERE I CHECK THE EXISTING EMAIL ***
} elseif ( email_exists( $user_email ) ) {
$errors->add( 'registered', __( 'This email is already registered.' ) );
}
if ($errors->get_error_code())
return $errors;
}
```
\*\*\* At this point I verify if the `$user_email` is existing already. But when I test it the message isn't displayed and the form is stuck.
Is there a need of an `add_action`? Can you explain me where I'm wrong?
Thanks
|
Why are you making work hard for yourself? `wp_create_user` already checks if the email/login exists, which is also why your code is "failing" - `$user_id` will already be a `WP_Error`, so your `elseif ( is_wp_error( $newerrors ) )` never fires.
All you need is:
```
$user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email, $capa );
if ( is_wp_error( $user_id ) ) {
wp_send_json( array(
'loggedin' => false,
'message' => $user_id->get_error_message(),
) );
}
exit;
```
Also note I've used the WordPress helper [`wp_send_json`](https://codex.wordpress.org/Function_Reference/wp_send_json), which is the *correct* way of sending JSON data back to the client.
|
226,436 |
<p>I am trying to figure out how to replace the value of one advanced custom field with the value from a different custom field. Would anyone be able to help me structure a SQL query that will do this across the database?</p>
<p>The meta_key that contains the material I am looking to duplicate is "ehp_citation", and the target of the duplication is "ehp_citation".</p>
|
[
{
"answer_id": 309605,
"author": "Cubakos",
"author_id": 107648,
"author_profile": "https://wordpress.stackexchange.com/users/107648",
"pm_score": 2,
"selected": false,
"text": "<p>First take a db backup! \nSecond, in your question you mention the same meta_key, so made the following assumption:</p>\n\n<blockquote>\n <p>The meta_key you want to keep is \"ehp_citation\"</p>\n \n <p>The meta_key you want to change is \"ehp_citation_old\" * so make the correction accordingly</p>\n</blockquote>\n\n<p>Then you can try something like:</p>\n\n<pre><code>UPDATE `wp_postmeta` AS pm_to_change\nLEFT JOIN `wp_postmeta` AS pm_we_want ON pm_to_change.post_id = pm_we_want.post_id\nSET pm_to_change.meta_value = pm_we_want.meta_value\nWHERE pm_to_change.meta_key = 'ehp_citation_old'\n AND pm_we_want.meta_key = 'ehp_citation'\n AND pm_we_want.meta_value != ''\n</code></pre>\n\n<p>also make sure you change the db prefix to mach yours.</p>\n\n<p>To explain,</p>\n\n<p>1) we say we want to update the <code>wp_postmeta</code> table and for reference we give it a name: <code>pm_to_change</code></p>\n\n<p>2) we make an LEFT JOIN to the same table (<code>wp_postmeta</code>) but this time we refer to it by: 'pm_we_want' and also we say that we want the data for the same <code>post_id</code></p>\n\n<p>3) here we say what to change. we want the <code>meta_value</code> of the <code>pm_to_change</code> to be SET to the <code>meta_value</code> of the <code>pm_we_want</code></p>\n\n<p>3) Finally we specify from which <code>meta_key</code> we want the above values. \nSo we want the <code>meta_key</code> of the <code>pm_to_change</code> table to be: <code>ehp_citation_old</code> and the <code>meta_key</code> of the <code>pm_we_want</code> table to be: <code>ehp_citation</code>.</p>\n\n<p><em>Bonus 1</em>: The <code>AND pm_we_want.meta_value != ''</code> in the end also checks if the value we want, from <code>ehp_citation</code> is not empty. Which means that if it is empty, the we keep the old <code>ehp_citation_old</code></p>\n\n<p><em>Bonus 2</em>: Run this SELECT first to check that we got the correct data: </p>\n\n<pre><code>SELECT pm_to_change.meta_value AS 'Change_This', pm_we_want.meta_value AS 'To_That'\nFROM `wp_postmeta` AS pm_to_change\nLEFT JOIN `wp_postmeta` AS pm_we_want ON pm_to_change.post_id = pm_we_want.post_id\nWHERE pm_to_change.meta_key = 'ehp_citation_old'\n AND pm_we_want.meta_key = 'ehp_citation'\n AND pm_we_want.meta_value != ''\n</code></pre>\n"
},
{
"answer_id": 320865,
"author": "Jim",
"author_id": 155159,
"author_profile": "https://wordpress.stackexchange.com/users/155159",
"pm_score": 1,
"selected": false,
"text": "<p>You could try to do this using Wordpress it's own function. You should consider looking into this: <a href=\"https://codex.wordpress.org/Function_Reference/update_post_meta\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/update_post_meta</a> / <a href=\"https://www.advancedcustomfields.com/resources/update_field/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/update_field/</a></p>\n\n<p>You could do a code that does the following</p>\n\n<ul>\n<li>Request all the posts/pages in which the posts that you need are loaded</li>\n<li>Loop through these items using a foreach loop or have_posts() function</li>\n<li>Within the posts, change the values for fields that you want to update.</li>\n</ul>\n\n<p>Note that this is a work-around. It has worked for me many times, hope it works for you too.</p>\n"
}
] |
2016/05/12
|
[
"https://wordpress.stackexchange.com/questions/226436",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54061/"
] |
I am trying to figure out how to replace the value of one advanced custom field with the value from a different custom field. Would anyone be able to help me structure a SQL query that will do this across the database?
The meta\_key that contains the material I am looking to duplicate is "ehp\_citation", and the target of the duplication is "ehp\_citation".
|
First take a db backup!
Second, in your question you mention the same meta\_key, so made the following assumption:
>
> The meta\_key you want to keep is "ehp\_citation"
>
>
> The meta\_key you want to change is "ehp\_citation\_old" \* so make the correction accordingly
>
>
>
Then you can try something like:
```
UPDATE `wp_postmeta` AS pm_to_change
LEFT JOIN `wp_postmeta` AS pm_we_want ON pm_to_change.post_id = pm_we_want.post_id
SET pm_to_change.meta_value = pm_we_want.meta_value
WHERE pm_to_change.meta_key = 'ehp_citation_old'
AND pm_we_want.meta_key = 'ehp_citation'
AND pm_we_want.meta_value != ''
```
also make sure you change the db prefix to mach yours.
To explain,
1) we say we want to update the `wp_postmeta` table and for reference we give it a name: `pm_to_change`
2) we make an LEFT JOIN to the same table (`wp_postmeta`) but this time we refer to it by: 'pm\_we\_want' and also we say that we want the data for the same `post_id`
3) here we say what to change. we want the `meta_value` of the `pm_to_change` to be SET to the `meta_value` of the `pm_we_want`
3) Finally we specify from which `meta_key` we want the above values.
So we want the `meta_key` of the `pm_to_change` table to be: `ehp_citation_old` and the `meta_key` of the `pm_we_want` table to be: `ehp_citation`.
*Bonus 1*: The `AND pm_we_want.meta_value != ''` in the end also checks if the value we want, from `ehp_citation` is not empty. Which means that if it is empty, the we keep the old `ehp_citation_old`
*Bonus 2*: Run this SELECT first to check that we got the correct data:
```
SELECT pm_to_change.meta_value AS 'Change_This', pm_we_want.meta_value AS 'To_That'
FROM `wp_postmeta` AS pm_to_change
LEFT JOIN `wp_postmeta` AS pm_we_want ON pm_to_change.post_id = pm_we_want.post_id
WHERE pm_to_change.meta_key = 'ehp_citation_old'
AND pm_we_want.meta_key = 'ehp_citation'
AND pm_we_want.meta_value != ''
```
|
226,482 |
<p>I have a form with a WP Media to allow user uploads for a custom post type on the front end. Every time I try to upload as a user I can the message <code>You don't have permission to attach files to this post.</code></p>
<p>Investigating it further, I get denied action in the file <code>ajax-actions.php</code> where it checks <code>current_user_can( 'edit_post', $post_id )</code> before uploading the file. I've bent myself backwards trying to user <code>user_has_cap</code> filter to allow user to this action, but it looks awfully unsecured:</p>
<pre><code>public function allow_user_to_upload( $allcaps, $caps, $args ) {
if ( $args[2] != 9 ) // 9 is the post_id where the form is
return $allcaps;
foreach ($caps as $cap ) {
$allcaps[$cap] = true;
}
return $allcaps;
} add_filter( 'user_has_cap', array( $this, 'allow_user_to_upload'), 100, 3 );
</code></pre>
<p>This works but it looks terribly unsecured. There must be a better way to do this, please help!!!</p>
|
[
{
"answer_id": 226486,
"author": "Sisir",
"author_id": 3094,
"author_profile": "https://wordpress.stackexchange.com/users/3094",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to allow user to upload files. <code>edit_post</code> is wrong cap to check. Instead you will need to add cap <code>upload_files</code> to users and check against it. If you want to allow only images you may custom filer the allowed MIME type.</p>\n\n<p>See more at <a href=\"https://codex.wordpress.org/Roles_and_Capabilities#upload_files\" rel=\"nofollow\">https://codex.wordpress.org/Roles_and_Capabilities#upload_files</a></p>\n"
},
{
"answer_id": 226501,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": true,
"text": "<p>If I understood correctly the situation described in the question and its comments, the user has capabilities to upload files and to edit your post type, so you shouldn't be fitering capabilities, the user already has the correct capabilities.</p>\n\n<p>The problem is that <code>wp_editor()</code> use the global <code>$post</code> by default, and in your context the global <code>$post</code> is for the page where you embed the editor.</p>\n\n<p>The solution: set the global <code>$post</code> to the post being edited before executing <code>wp_editor()</code>:</p>\n\n<pre><code>global $post;\n// Set the global post to your post object\n// Exmple if the ID of your post is 2\n$post = get_post( 2 );\nwp_editor();\n</code></pre>\n\n<p>If you are in a new post form:</p>\n\n<pre><code>global $post;\n// Get default post object of my_post_type\n$post = get_default_post_to_edit( 'my_post_type', true );\nwp_editor();\n</code></pre>\n"
}
] |
2016/05/13
|
[
"https://wordpress.stackexchange.com/questions/226482",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54189/"
] |
I have a form with a WP Media to allow user uploads for a custom post type on the front end. Every time I try to upload as a user I can the message `You don't have permission to attach files to this post.`
Investigating it further, I get denied action in the file `ajax-actions.php` where it checks `current_user_can( 'edit_post', $post_id )` before uploading the file. I've bent myself backwards trying to user `user_has_cap` filter to allow user to this action, but it looks awfully unsecured:
```
public function allow_user_to_upload( $allcaps, $caps, $args ) {
if ( $args[2] != 9 ) // 9 is the post_id where the form is
return $allcaps;
foreach ($caps as $cap ) {
$allcaps[$cap] = true;
}
return $allcaps;
} add_filter( 'user_has_cap', array( $this, 'allow_user_to_upload'), 100, 3 );
```
This works but it looks terribly unsecured. There must be a better way to do this, please help!!!
|
If I understood correctly the situation described in the question and its comments, the user has capabilities to upload files and to edit your post type, so you shouldn't be fitering capabilities, the user already has the correct capabilities.
The problem is that `wp_editor()` use the global `$post` by default, and in your context the global `$post` is for the page where you embed the editor.
The solution: set the global `$post` to the post being edited before executing `wp_editor()`:
```
global $post;
// Set the global post to your post object
// Exmple if the ID of your post is 2
$post = get_post( 2 );
wp_editor();
```
If you are in a new post form:
```
global $post;
// Get default post object of my_post_type
$post = get_default_post_to_edit( 'my_post_type', true );
wp_editor();
```
|
226,483 |
<p>I want to display a list of categories excluding the category of the current single post that the user is navigating on. The list is displayed on the <code>single.php</code> template.</p>
<p>I'm using this code to display all categories and is working well but I can't find a way to exclude the current post category:</p>
<pre><code><ul class="submenu-category">
<?php
// your taxonomy name
$tax = 'category';
// get the terms of taxonomy
$terms = get_terms( $tax, $args = array(
'hide_empty' => false, // do not hide empty terms
));
// loop through all terms
foreach( $terms as $term ) {
// Get the term link
$term_link = get_term_link( $term );
if( $term->count > 0 )
// display link to term archive
// echo '<a href="' . esc_url( $term_link ) . '">' . $term->name .'</a>';
echo '<li><a data-filter=".'. $term->slug .'" href="javascript:void(0)" >' . $term->name .'</a></li>';
elseif( $term->count !== 0 )
// display name
echo '' . $term->name .'';
} ?>
</ul>
</code></pre>
<p>Any idea on how to achieve it?</p>
|
[
{
"answer_id": 226490,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>First you will need an array that contains all categories of the current post:</p>\n\n<pre><code>$current_cats = wp_get_post_categories(); // assuming you are in the loop\n</code></pre>\n\n<p>Then you have to loop through $current_cats and remove the items from $terms</p>\n\n<pre><code> foreach( $current_cats as $cat ) {\n if (($key = array_search($cat, $terms)) !== false) {\n unset($terms[$key]);\n }\n }\n</code></pre>\n\n<p>Hopefully that works.</p>\n"
},
{
"answer_id": 226498,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": true,
"text": "<p>The idea here would be to use the queried object's ID to get the post terms (<em>because we are most probably outside the loop here, if inside the loop, just use <code>get_the_ID()</code></em>). From there, we can use <code>wp_list_pluck()</code> to get all the term ID's and simply pass that to <code>get_terms()</code> <code>exclude</code> parameter</p>\n\n<p>Just a note, as from WordPress V4.5, the taxonomy should be passed as an arguments of <code>$args</code>, I'll handle both cases</p>\n\n<h2>PRE 4.5</h2>\n\n<pre><code>// Set all our variables\n$taxonomy = 'category';\n$post_id = $GLOBALS['wp_the_query']->get_queried_object_id();\n$args = [\n 'hide_empty' => false\n];\n\n// Get the ID's from the post terms\n$post_terms = get_the_terms( $post_id, $taxonomy );\nif ( $post_terms\n && !is_wp_error( $post_terms )\n) {\n $term_ids = wp_list_pluck( $post_terms, 'term_id' );\n\n // Get all the terms with the post terms excluded\n $args['exclude'] = $term_ids;\n}\n\n$terms = get_terms( $taxonomy, $args );\n</code></pre>\n\n<h2>V 4.5 + version</h2>\n\n<pre><code>// Set all our variables\n$taxonomy = 'category';\n$post_id = $GLOBALS['wp_the_query']->get_queried_object_id();\n$args = [\n 'taxonomy' => $taxonomy,\n 'hide_empty' => false\n];\n\n// Get the ID's from the post terms\n$post_terms = get_the_terms( $post_id, $taxonomy );\nif ( $post_terms\n && !is_wp_error( $post_terms )\n) {\n $term_ids = wp_list_pluck( $post_terms, 'term_id' );\n\n // Get all the terms with the post terms excluded\n $args['exclude'] = $term_ids;\n}\n\n$terms = get_terms( $args );\n</code></pre>\n"
}
] |
2016/05/13
|
[
"https://wordpress.stackexchange.com/questions/226483",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22933/"
] |
I want to display a list of categories excluding the category of the current single post that the user is navigating on. The list is displayed on the `single.php` template.
I'm using this code to display all categories and is working well but I can't find a way to exclude the current post category:
```
<ul class="submenu-category">
<?php
// your taxonomy name
$tax = 'category';
// get the terms of taxonomy
$terms = get_terms( $tax, $args = array(
'hide_empty' => false, // do not hide empty terms
));
// loop through all terms
foreach( $terms as $term ) {
// Get the term link
$term_link = get_term_link( $term );
if( $term->count > 0 )
// display link to term archive
// echo '<a href="' . esc_url( $term_link ) . '">' . $term->name .'</a>';
echo '<li><a data-filter=".'. $term->slug .'" href="javascript:void(0)" >' . $term->name .'</a></li>';
elseif( $term->count !== 0 )
// display name
echo '' . $term->name .'';
} ?>
</ul>
```
Any idea on how to achieve it?
|
The idea here would be to use the queried object's ID to get the post terms (*because we are most probably outside the loop here, if inside the loop, just use `get_the_ID()`*). From there, we can use `wp_list_pluck()` to get all the term ID's and simply pass that to `get_terms()` `exclude` parameter
Just a note, as from WordPress V4.5, the taxonomy should be passed as an arguments of `$args`, I'll handle both cases
PRE 4.5
-------
```
// Set all our variables
$taxonomy = 'category';
$post_id = $GLOBALS['wp_the_query']->get_queried_object_id();
$args = [
'hide_empty' => false
];
// Get the ID's from the post terms
$post_terms = get_the_terms( $post_id, $taxonomy );
if ( $post_terms
&& !is_wp_error( $post_terms )
) {
$term_ids = wp_list_pluck( $post_terms, 'term_id' );
// Get all the terms with the post terms excluded
$args['exclude'] = $term_ids;
}
$terms = get_terms( $taxonomy, $args );
```
V 4.5 + version
---------------
```
// Set all our variables
$taxonomy = 'category';
$post_id = $GLOBALS['wp_the_query']->get_queried_object_id();
$args = [
'taxonomy' => $taxonomy,
'hide_empty' => false
];
// Get the ID's from the post terms
$post_terms = get_the_terms( $post_id, $taxonomy );
if ( $post_terms
&& !is_wp_error( $post_terms )
) {
$term_ids = wp_list_pluck( $post_terms, 'term_id' );
// Get all the terms with the post terms excluded
$args['exclude'] = $term_ids;
}
$terms = get_terms( $args );
```
|
226,487 |
<p>First of all I do not have a lot of experience with wordpress plugins, but I am developing a plugin which has to connect and send data to a remote database ( which it is already doing ). But at this point of time my connection is not secure at all because all the database info is shown for the admin of the site.</p>
<p>This is my code at the moment, it works and all but how can I make sure that noone will see the database data that is in this file?</p>
<pre><code><?php
function webARX_connect_to_db(){
$servername = "remote_host";
$username = "username";
$password = "password";
$dbname = "database_name";
// Create connection
$webARX_connection = new wpdb($username, $password, $dbname, $servername);
if (empty($webARX_connection->show_errors())){
return $webARX_connection;
} else {
return $webARX_connection->show_errors();
}
}
?>
</code></pre>
|
[
{
"answer_id": 226631,
"author": "wax",
"author_id": 94014,
"author_profile": "https://wordpress.stackexchange.com/users/94014",
"pm_score": -1,
"selected": false,
"text": "<p>Great question. </p>\n\n<p>A couple of things:</p>\n\n<p>First, best practices tell us to always keep these types of assets outside of our Web serverβs document root. PHP isn't limited by the same restrictions as a Web server, from a permissions perspective, so you can make a directory on the same level as your document root and place all of your sensitive data and code there.</p>\n\n<p>Second, create a new database user that is limited in what it can do. Use this account for calls, rather than a super-privileged user. </p>\n\n<p>Using these two methods will greatly minimize your risks.</p>\n\n<p>Hope I've offered some help.</p>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 226635,
"author": "jake",
"author_id": 93548,
"author_profile": "https://wordpress.stackexchange.com/users/93548",
"pm_score": 0,
"selected": false,
"text": "<p>I'd recommend setting up an API, and also ensuring the sites are HTTPS (have an SSL certificate) to encrypt communication between the servers.</p>\n\n<p>If you don't have one already, there are free certifiers such as <a href=\"https://letsencrypt.org/\" rel=\"nofollow\">https://letsencrypt.org/</a></p>\n"
}
] |
2016/05/13
|
[
"https://wordpress.stackexchange.com/questions/226487",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93989/"
] |
First of all I do not have a lot of experience with wordpress plugins, but I am developing a plugin which has to connect and send data to a remote database ( which it is already doing ). But at this point of time my connection is not secure at all because all the database info is shown for the admin of the site.
This is my code at the moment, it works and all but how can I make sure that noone will see the database data that is in this file?
```
<?php
function webARX_connect_to_db(){
$servername = "remote_host";
$username = "username";
$password = "password";
$dbname = "database_name";
// Create connection
$webARX_connection = new wpdb($username, $password, $dbname, $servername);
if (empty($webARX_connection->show_errors())){
return $webARX_connection;
} else {
return $webARX_connection->show_errors();
}
}
?>
```
|
I'd recommend setting up an API, and also ensuring the sites are HTTPS (have an SSL certificate) to encrypt communication between the servers.
If you don't have one already, there are free certifiers such as <https://letsencrypt.org/>
|
226,533 |
<p>Is it possible to stop WordPress adding a width and height to an object when you pate it in to the source view?</p>
<p>When I paste in</p>
<pre><code><a href="#"><object data="grid-linked-in.svg" type="image/svg+xml"></object></a>
</code></pre>
<p>WP changes it to</p>
<pre><code><a href="#"><object width="300" height="150" type="image/svg+xml" data="grid-linked-in.svg"></object></a>
</code></pre>
|
[
{
"answer_id": 226539,
"author": "Captain Yar",
"author_id": 87544,
"author_profile": "https://wordpress.stackexchange.com/users/87544",
"pm_score": 0,
"selected": false,
"text": "<p>You can use jQuery for this:</p>\n\n<pre><code>$('object').each(function(){\n $(this).removeAttr('width height');\n});\n</code></pre>\n\n<p>That should remove those attributes for you. You can even set attributes as well if need be. Put the following inside the function above (Obviously you can change the attributes as need be).</p>\n\n<pre><code>$(this).css('max-height',500);\n</code></pre>\n"
},
{
"answer_id": 226565,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 2,
"selected": true,
"text": "<p>You can try this:</p>\n\n<pre><code>add_filter( 'media_send_to_editor', 'remove_width_height_attribute', 10 );\n\nfunction remove_width_height_attribute( $html ) {\n $html = preg_replace( '/(width|height)=\"\\d*\"\\s/', \"\", $html );\n return $html;\n}\n</code></pre>\n"
}
] |
2016/05/13
|
[
"https://wordpress.stackexchange.com/questions/226533",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94003/"
] |
Is it possible to stop WordPress adding a width and height to an object when you pate it in to the source view?
When I paste in
```
<a href="#"><object data="grid-linked-in.svg" type="image/svg+xml"></object></a>
```
WP changes it to
```
<a href="#"><object width="300" height="150" type="image/svg+xml" data="grid-linked-in.svg"></object></a>
```
|
You can try this:
```
add_filter( 'media_send_to_editor', 'remove_width_height_attribute', 10 );
function remove_width_height_attribute( $html ) {
$html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
return $html;
}
```
|
226,581 |
<p>Can anyone explain what is the difference between <code>update_user_meta</code> and <code>update_user_option</code> and in which scenarios the both can be used?</p>
|
[
{
"answer_id": 226585,
"author": "Jarod Thornton",
"author_id": 44017,
"author_profile": "https://wordpress.stackexchange.com/users/44017",
"pm_score": 3,
"selected": false,
"text": "<p>Both write their data in the βusermetaβ table. User options stored in the usermeta table retain the wordpress table prefix e.g. wp_ whereas the user meta also stored in the usermeta table doesn't. </p>\n\n<p>User options support blog-specific options, useful in multisite. The user meta is based on the user id specific meta data like profile information. </p>\n\n<p>The parameters are quite different in fact. User option has $user_id, $option_name, $newvalue, $global and user meta has $user_id, $meta_key, $meta_value, $prev_value. </p>\n\n<p>Here are some values for both options and user usermeta.</p>\n\n<p>Options</p>\n\n<ul>\n<li>wp_user_level</li>\n<li>wp_user-settings</li>\n<li>wp_capabilities</li>\n<li>wp_user-settings-time</li>\n</ul>\n\n<p>User</p>\n\n<ul>\n<li>first_name</li>\n<li>last_name</li>\n<li>nickname</li>\n<li>rich_editing</li>\n<li>show_admin_bar_front</li>\n<li>admin_color</li>\n</ul>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/update_user_option#Parameters\">https://codex.wordpress.org/Function_Reference/update_user_option#Parameters</a></p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/update_user_meta#Parameters\">https://codex.wordpress.org/Function_Reference/update_user_meta#Parameters</a></p>\n\n<p>The codex pages examples provide real world use.</p>\n"
},
{
"answer_id": 226594,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 5,
"selected": true,
"text": "<p>In layman terms there is no major difference! <code>update_user_option()</code> uses <code>update_user_meta()</code> internally. The only difference is <code>update_user_option()</code> prefix the option name with database table prefix + blog ID if you are in multisite and just table prefix if you are in single site installation.</p>\n\n<p>Take a look at the code of <code>update_user_option()</code></p>\n\n<pre><code>/**\n * Update user option with global blog capability.\n *\n * User options are just like user metadata except that they have support for\n * global blog options. If the 'global' parameter is false, which it is by default\n * it will prepend the WordPress table prefix to the option name.\n *\n * Deletes the user option if $newvalue is empty.\n *\n * @since 2.0.0\n *\n * @global wpdb $wpdb WordPress database abstraction object.\n *\n * @param int $user_id User ID.\n * @param string $option_name User option name.\n * @param mixed $newvalue User option value.\n * @param bool $global Optional. Whether option name is global or blog specific.\n * Default false (blog specific).\n * @return int|bool User meta ID if the option didn't exist, true on successful update,\n * false on failure.\n */\nfunction update_user_option( $user_id, $option_name, $newvalue, $global = false ) {\n global $wpdb;\n\n if ( !$global )\n $option_name = $wpdb->get_blog_prefix() . $option_name;\n\n return update_user_meta( $user_id, $option_name, $newvalue );\n}\n</code></pre>\n\n<p>Your option name is prefixed with table prefix + blog ID (Only when ID is other than 1 and 0).</p>\n\n<p>If you set the last parameter <code>$global</code> to <code>true</code> it has no difference with <code>update_user_meta()</code>.</p>\n\n<p><strong>Purpose of <code>update_user_option()</code> function</strong></p>\n\n<p>Unlike other tables, WordPress does not create separate table for usermeta for each site. It saves user information in one usermeta table for all of the blogs (in multisite). It just prefix the key name for each site with <code>blog prefix</code> e.g. for blog ID 4 <code>wp_capabilities</code> is stored as <code>wp_4_capabilities</code>.</p>\n\n<p>So whatever information you will save using <code>update_user_option()</code>, for example <code>key_name_abc</code> will become <code>wp_key_name_abc</code> for main site in multisite or in single site installation. In future if you convert your single site to multisite the information will be available only in main site.</p>\n\n<p>Use this function when you think some information is depended on site + user as well. Not like name, email etc because these information belongs to user and site independent.</p>\n"
}
] |
2016/05/14
|
[
"https://wordpress.stackexchange.com/questions/226581",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48573/"
] |
Can anyone explain what is the difference between `update_user_meta` and `update_user_option` and in which scenarios the both can be used?
|
In layman terms there is no major difference! `update_user_option()` uses `update_user_meta()` internally. The only difference is `update_user_option()` prefix the option name with database table prefix + blog ID if you are in multisite and just table prefix if you are in single site installation.
Take a look at the code of `update_user_option()`
```
/**
* Update user option with global blog capability.
*
* User options are just like user metadata except that they have support for
* global blog options. If the 'global' parameter is false, which it is by default
* it will prepend the WordPress table prefix to the option name.
*
* Deletes the user option if $newvalue is empty.
*
* @since 2.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $user_id User ID.
* @param string $option_name User option name.
* @param mixed $newvalue User option value.
* @param bool $global Optional. Whether option name is global or blog specific.
* Default false (blog specific).
* @return int|bool User meta ID if the option didn't exist, true on successful update,
* false on failure.
*/
function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
global $wpdb;
if ( !$global )
$option_name = $wpdb->get_blog_prefix() . $option_name;
return update_user_meta( $user_id, $option_name, $newvalue );
}
```
Your option name is prefixed with table prefix + blog ID (Only when ID is other than 1 and 0).
If you set the last parameter `$global` to `true` it has no difference with `update_user_meta()`.
**Purpose of `update_user_option()` function**
Unlike other tables, WordPress does not create separate table for usermeta for each site. It saves user information in one usermeta table for all of the blogs (in multisite). It just prefix the key name for each site with `blog prefix` e.g. for blog ID 4 `wp_capabilities` is stored as `wp_4_capabilities`.
So whatever information you will save using `update_user_option()`, for example `key_name_abc` will become `wp_key_name_abc` for main site in multisite or in single site installation. In future if you convert your single site to multisite the information will be available only in main site.
Use this function when you think some information is depended on site + user as well. Not like name, email etc because these information belongs to user and site independent.
|
226,588 |
<p>I imported the <a href="https://codex.wordpress.org/Theme_Unit_Test" rel="nofollow">Theme Unit Test</a> xml file with the wordpress importer. But all of the data is imported as pages. I am following an online tutorial to build a wordpress theme development and I believe the data should be imported as posts.</p>
<p>When I proceed with the import. I can choose to import authors or to assign a existing author and I can choose to import/download attachments (which I did).</p>
<p>I get a fatal error</p>
<pre><code>Fatal error: Maximum execution time of 60 seconds exceeded in H:\wamp\www\custom\wp-includes\class-wp-http-curl.php
</code></pre>
<p>I get a bunch of pages and media but no posts.</p>
<p>Although I am also increase those values: </p>
<p>max_execution_time = 5000</p>
<p>max_input_time = 5000</p>
<p>memory_limit = 1000M</p>
<p>How should I fix this so I can import all the content?</p>
|
[
{
"answer_id": 226602,
"author": "Shadat501",
"author_id": 94059,
"author_profile": "https://wordpress.stackexchange.com/users/94059",
"pm_score": 3,
"selected": false,
"text": "<p>I get that answer. </p>\n\n<p>I go to this file: <code>wp-includes/deprecated.php</code> and find this line in (deprecated) <code>wp_get_http()</code> function:</p>\n\n<pre><code>@set_time_limit ( 60 );\n</code></pre>\n\n<p>just comment out this line and it works fine. </p>\n\n<p>Because wordpress hard coded that 60 seconds limit, this hard coded setting was over-ridding my <code>php.ini</code> settings. so I comment out that line, my <code>php.ini</code> settings will start working again. </p>\n"
},
{
"answer_id": 228926,
"author": "zakynthinos GR",
"author_id": 96317,
"author_profile": "https://wordpress.stackexchange.com/users/96317",
"pm_score": 0,
"selected": false,
"text": "<p>Just to the point..\nIn wp-config.php paste this code-line</p>\n\n<p>set_time_limit(180);</p>\n\n<p>set your recommend execution time (PHP Time Limit) and done!..</p>\n\n<p>Important: Paste before</p>\n\n<p>/* That's all, stop editing! Happy blogging. */</p>\n\n<p>That's all.</p>\n\n<p>Never forget this, Silence is golden :))</p>\n"
}
] |
2016/05/14
|
[
"https://wordpress.stackexchange.com/questions/226588",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94059/"
] |
I imported the [Theme Unit Test](https://codex.wordpress.org/Theme_Unit_Test) xml file with the wordpress importer. But all of the data is imported as pages. I am following an online tutorial to build a wordpress theme development and I believe the data should be imported as posts.
When I proceed with the import. I can choose to import authors or to assign a existing author and I can choose to import/download attachments (which I did).
I get a fatal error
```
Fatal error: Maximum execution time of 60 seconds exceeded in H:\wamp\www\custom\wp-includes\class-wp-http-curl.php
```
I get a bunch of pages and media but no posts.
Although I am also increase those values:
max\_execution\_time = 5000
max\_input\_time = 5000
memory\_limit = 1000M
How should I fix this so I can import all the content?
|
I get that answer.
I go to this file: `wp-includes/deprecated.php` and find this line in (deprecated) `wp_get_http()` function:
```
@set_time_limit ( 60 );
```
just comment out this line and it works fine.
Because wordpress hard coded that 60 seconds limit, this hard coded setting was over-ridding my `php.ini` settings. so I comment out that line, my `php.ini` settings will start working again.
|
226,589 |
<p>I want to filter posts based on multiple acf custom fields with AND relation. Something like this:</p>
<pre><code>$args = array(
'post_type' => 'product',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => 'blue',
'compare' => '=',
),
array(
'key' => 'price',
'value' => array( 20, 100 ),
'type' => 'numeric',
'compare' => 'BETWEEN',
),
),
);
</code></pre>
<p>I might even have more filters. How can I convert these to REST API 2 filters?</p>
|
[
{
"answer_id": 227814,
"author": "Igor Fedorov",
"author_id": 94657,
"author_profile": "https://wordpress.stackexchange.com/users/94657",
"pm_score": 1,
"selected": false,
"text": "<p>You can do it without Rest API\nLike this\n(It is my posts filter)</p>\n\n<pre>\n $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n$args = array(\n 'paged' => $paged,\n 'orderby' => 'date', // ΡΠΎΡΡΠΈΡΠΎΠ²ΠΊΠ° ΠΏΠΎ Π΄Π°ΡΠ΅ Ρ Π½Π°Ρ Π±ΡΠ΄Π΅Ρ Π² Π»ΡΠ±ΠΎΠΌ ΡΠ»ΡΡΠ°Π΅ (Π½ΠΎ Π²Ρ ΠΌΠΎΠΆΠ΅ΡΠ΅ ΠΈΠ·ΠΌΠ΅Π½ΠΈΡΡ/Π΄ΠΎΡΠ°Π±ΠΎΡΠ°ΡΡ ΡΡΠΎ)\n 'order' => 'DESC',\n );\n\n // ΡΠΎΠ·Π΄Π°ΡΠΌ ΠΌΠ°ΡΡΠΈΠ² $args['meta_query'] Π΅ΡΠ»ΠΈ ΡΠΊΠ°Π·Π°Π½Π° Ρ
ΠΎΡΡ Π±Ρ ΠΎΠ΄Π½Π° ΡΠ΅Π½Π° ΠΈΠ»ΠΈ ΠΎΡΠΌΠ΅ΡΠ΅Π½ ΡΠ΅ΠΊΠ±ΠΎΠΊΡ\n if( isset( $_GET['price_min'] ) || isset( $_GET['price_max'] ) || isset( $_GET['type'] ) )\n $args['meta_query'] = array( 'relation'=>'AND' ); // AND Π·Π½Π°ΡΠΈΡ Π²ΡΠ΅ ΡΡΠ»ΠΎΠ²ΠΈΡ meta_query Π΄ΠΎΠ»ΠΆΠ½Ρ Π²ΡΠΏΠΎΠ»Π½ΡΡΡΡΡ\n\n\n if( $type ){\n $args['meta_query'][] = array(\n 'key' => 'type',\n 'value' => $type,\n );\n };\n\n if( $plan ){\n $args['meta_query'][] = array(\n 'key' => 'plan',\n 'value' => $plan,\n );\n };\n\n if( $room_num ){\n $args['meta_query'][] = array(\n 'key' => 'room_num',\n 'value' => $room_num,\n );\n };\n\n if( $etage ){\n $args['meta_query'][] = array(\n 'key' => 'etage',\n 'value' => $etage,\n );\n }; \n\n if( $price_min || $price_max ){\n $args['meta_query'][] = array(\n 'key' => 'price',\n 'value' => array( $price_min, $price_max ),\n 'type' => 'numeric',\n 'compare' => 'BETWEEN'\n );\n }; \n\n if( $area_min || $area_max ){\n $args['meta_query'][] = array(\n 'key' => 'area',\n 'value' => array( $area_min, $area_max ),\n 'type' => 'numeric',\n 'compare' => 'BETWEEN'\n );\n };\n</pre>\n"
},
{
"answer_id": 227821,
"author": "emilushi",
"author_id": 63983,
"author_profile": "https://wordpress.stackexchange.com/users/63983",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a test i made on Localhost:</p>\n\n<p>For security reasons meta query is not allowed on WP Api, first what you have to do is to add meta_query to allowed rest_query by adding this function on your wordpress theme <code>functions.php</code></p>\n\n<pre><code>function api_allow_meta_query( $valid_vars ) {\n\n $valid_vars = array_merge( $valid_vars, array( 'meta_query') );\n return $valid_vars;\n}\nadd_filter( 'rest_query_vars', 'api_allow_meta_query' );\n</code></pre>\n\n<p>after that you will need build the html query by using this function on the other website that will get the data from the wordpress website</p>\n\n<pre><code>$curl = curl_init();\n$fields = array (\n 'filter[meta_query]' => array (\n 'relation' => 'AND',\n array (\n 'key' => 'color',\n 'value' => 'blue',\n 'compare' => '='\n ),\n array (\n 'key' => 'price',\n 'value' => array ( 20, 100 ),\n 'type' => 'numeric',\n 'compare' => 'BETWEEN'\n ),\n ),\n );\n\n$field_string = http_build_query($fields);\n\ncurl_setopt_array($curl, array (\n CURLOPT_RETURNTRANSFER => 1,\n CURLOPT_URL => 'http://yourwordpreswebssite.com/wp-json/wp/v2/posts?' . $field_string\n )\n);\n\n$result = curl_exec($curl);\n\necho htmlentities($result);\n</code></pre>\n\n<p>I change the fields array so the look now like your query arguments.\nThe encoded query string will look like this:</p>\n\n<pre><code>http://yourwordpreswebssite.com/wp-json/wp/v2/posts?filter%5Btaxonomy%5D=product&filter%5Bmeta_query%5D%5Brelation%5D=AND&filter%5Bmeta_query%5D%5B0%5D%5Bkey%5D=color&filter%5Bmeta_query%5D%5B0%5D%5Bvalue%5D=blue&filter%5Bmeta_query%5D%5B0%5D%5Bcompare%5D=%3D&filter%5Bmeta_query%5D%5B1%5D%5Bkey%5D=price&filter%5Bmeta_query%5D%5B1%5D%5Bvalue%5D%5B0%5D=20&filter%5Bmeta_query%5D%5B1%5D%5Bvalue%5D%5B1%5D=100&filter%5Bmeta_query%5D%5B1%5D%5Btype%5D=numeric&filter%5Bmeta_query%5D%5B1%5D%5Bcompare%5D=BETWEEN\n</code></pre>\n\n<p>By using <code>urldecode()</code>, which in this case will be: <code>urldecode('http://yourwordpreswebssite.com/wp-json/wp/v2/posts?' . $field_string);</code> you will have an URL like this one:</p>\n\n<pre><code>http://yourwordpreswebssite.com/wp-json/wp/v2/posts?filter[taxonomy]=product&filter[meta_query][relation]=AND&filter[meta_query][0][key]=color&filter[meta_query][0][value]=blue&filter[meta_query][0][compare]==&filter[meta_query][1][key]=price&filter[meta_query][1][value][0]=20&filter[meta_query][1][value][1]=100&filter[meta_query][1][type]=numeric&filter[meta_query][1][compare]=BETWEEN\n</code></pre>\n\n<p>If you can provide us your live website URL so we can test it using postman directly on your website, because to test it on localhost or any existing WordPress site will be needed to create product custom post type and add meta fields etc etc. Cheers!</p>\n"
},
{
"answer_id": 227869,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 3,
"selected": false,
"text": "<p>This solution works with <a href=\"https://github.com/WP-API/WP-API/blob/develop/lib/endpoints/class-wp-rest-posts-controller.php#L81\" rel=\"noreferrer\"><code>get_items()</code></a> in <a href=\"https://github.com/WP-API/WP-API/blob/develop/lib/endpoints/class-wp-rest-posts-controller.php\" rel=\"noreferrer\"><code>/lib/endpoints/class-wp-rest-posts-controller.php</code></a> of the <a href=\"http://v2.wp-api.org\" rel=\"noreferrer\"><code>v2 WP Rest API</code></a>.</p>\n\n<hr>\n\n<p>First, you'll want to construct the <a href=\"http://php.net/manual/en/reserved.variables.get.php\" rel=\"noreferrer\"><code>GET</code></a> arguments like you would for a <a href=\"https://generatewp.com/wp_query/\" rel=\"noreferrer\"><code>new WP_Query()</code></a>. The easiest way to do this is with <a href=\"http://php.net/manual/en/function.http-build-query.php\" rel=\"noreferrer\"><code>http_build_query()</code></a>.</p>\n\n<pre><code>$args = array (\n 'filter' => array (\n 'meta_query' => array (\n 'relation' => 'AND',\n array (\n 'key' => 'color',\n 'value' => 'blue',\n 'compare' => '=',\n ),\n array (\n 'key' => 'test',\n 'value' => 'testing',\n 'compare' => '=',\n ),\n ),\n ),\n);\n$field_string = http_build_query( $args );\n</code></pre>\n\n<p>It'll produce something like:</p>\n\n<p><code>filter%5Bmeta_query%5D%5Brelation%5D=AND&filter%5Bmeta_query%5D%5B0%5D%5Bkey%5D=color&filter%5Bmeta_query%5D%5B0%5D%5Bvalue%5D=blue&filter%5Bmeta_query%5D%5B0%5D%5Bcompare%5D=%3D&filter%5Bmeta_query%5D%5B1%5D%5Bkey%5D=test&filter%5Bmeta_query%5D%5B1%5D%5Bvalue%5D=testing&filter%5Bmeta_query%5D%5B1%5D%5Bcompare%5D=%3D</code></p>\n\n<p>Which, if you want readable, you can also use Chrome tools and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent\" rel=\"noreferrer\"><code>decodeURIComponent('your-query-here')</code></a> to make it a easier to read when you throw it into your <a href=\"http://v2.wp-api.org/reference/\" rel=\"noreferrer\">JSON Rest API URL</a>:</p>\n\n<p><a href=\"https://demo.wp-api.org/wp-json/wp/v2/product?filter[meta_query][relation]=AND&filter[meta_query][0][key]=color&filter[meta_query][0][value]=blue&filter[meta_query][0][compare]==&filter[meta_query][1][key]=test&filter[meta_query][1][value]=testing&filter[meta_query][1][compare]==\" rel=\"noreferrer\"><code>https://demo.wp-api.org/wp-json/wp/v2/product?filter[meta_query][relation]=AND&filter[meta_query][0][key]=color&filter[meta_query][0][value]=blue&filter[meta_query][0][compare]==&filter[meta_query][1][key]=test&filter[meta_query][1][value]=testing&filter[meta_query][1][compare]==</code></a></p>\n\n<p>Note: To use your custom post type you would put <code>product</code> before <code>?</code></p>\n\n<p><code>/wp-json/wp/v2/<custom-post-type>?filter[meta_query]</code></p>\n\n<hr>\n\n<p>So you have your query but we need to instruct WP how to handle a few things:</p>\n\n<ol>\n<li>Adding REST support for the custom post type <code>product</code></li>\n<li>Allowing the query args <code>meta_query</code></li>\n<li>Parsing <code>meta_query</code> </li>\n</ol>\n\n<hr>\n\n<pre><code>// 1) Add CPT Support <product>\n\n\nfunction wpse_20160526_add_product_rest_support() {\n global $wp_post_types;\n\n //be sure to set this to the name of your post type!\n $post_type_name = 'product';\n if( isset( $wp_post_types[ $post_type_name ] ) ) {\n $wp_post_types[$post_type_name]->show_in_rest = true;\n $wp_post_types[$post_type_name]->rest_base = $post_type_name;\n $wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';\n }\n}\n\nadd_action( 'init', 'wpse_20160526_add_product_rest_support', 25 );\n\n\n// 2) Add `meta_query` support in the GET request\n\nfunction wpse_20160526_rest_query_vars( $valid_vars ) {\n $valid_vars = array_merge( $valid_vars, array( 'meta_query' ) ); // Omit meta_key, meta_value if you don't need them\n return $valid_vars;\n}\n\nadd_filter( 'rest_query_vars', 'wpse_20160526_rest_query_vars', PHP_INT_MAX, 1 );\n\n\n// 3) Parse Custom Args\n\nfunction wpse_20160526_rest_product_query( $args, $request ) {\n\n if ( isset( $args[ 'meta_query' ] ) ) {\n\n $relation = 'AND';\n if( isset($args['meta_query']['relation']) && in_array($args['meta_query']['relation'], array('AND', 'OR'))) {\n $relation = sanitize_text_field( $args['meta_query']['relation'] );\n }\n $meta_query = array(\n 'relation' => $relation\n );\n\n foreach ( $args['meta_query'] as $inx => $query_req ) {\n /*\n Array (\n\n [key] => test\n [value] => testing\n [compare] => =\n )\n */\n $query = array();\n\n if( is_numeric($inx)) {\n\n if( isset($query_req['key'])) {\n $query['key'] = sanitize_text_field($query_req['key']);\n }\n if( isset($query_req['value'])) {\n $query['value'] = sanitize_text_field($query_req['value']);\n }\n if( isset($query_req['type'])) {\n $query['type'] = sanitize_text_field($query_req['type']);\n }\n if( isset($query_req['compare']) && in_array($query_req['compare'], array('=', '!=', '>','>=','<','<=','LIKE','NOT LIKE','IN','NOT IN','BETWEEN','NOT BETWEEN', 'NOT EXISTS')) ) {\n $query['compare'] = sanitize_text_field($query_req['compare']);\n }\n }\n\n if( ! empty($query) ) $meta_query[] = $query;\n }\n\n // replace with sanitized query args\n $args['meta_query'] = $meta_query;\n }\n\n return $args;\n}\nadd_action( 'rest_product_query', 'wpse_20160526_rest_product_query', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 252186,
"author": "Michele Fortunato",
"author_id": 109855,
"author_profile": "https://wordpress.stackexchange.com/users/109855",
"pm_score": 1,
"selected": false,
"text": "<p>In Wordpress 4.7 the <code>filter</code> argument has been removed.</p>\n\n<p>You can reactivate it installing <a href=\"https://github.com/WP-API/rest-filter\" rel=\"nofollow noreferrer\">this</a> plugin provided by the Wordpress team. Only after that you can use one of the solutions proposed in the other answers.</p>\n\n<p>I've haven't found a solution to do the same without installing the plugin, yet.</p>\n"
},
{
"answer_id": 363415,
"author": "Rahman Rezaee",
"author_id": 176503,
"author_profile": "https://wordpress.stackexchange.com/users/176503",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>first add plugin or copy all code and paste all plugin in\nfunctions.php of this link\n<a href=\"https://github.com/WP-API/rest-filter\" rel=\"nofollow noreferrer\">https://github.com/WP-API/rest-filter</a></li>\n<li>use this </li>\n</ol>\n\n<p>\n\n<pre><code>?filter[meta_query][relation]=AND\n&filter[meta_query][0][key]=REAL_HOMES_property_price\n&filter[meta_query][0][value][0]=10\n&filter[meta_query][0][value][1]=10000001\n&filter[meta_query][0][compare]=''\n&filter[meta_query][1][key]=REAL_HOMES_property_price\n&filter[meta_query][1][value]=10\n&filter[meta_query][1][compare]='='\n</code></pre>\n"
}
] |
2016/05/14
|
[
"https://wordpress.stackexchange.com/questions/226589",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/72848/"
] |
I want to filter posts based on multiple acf custom fields with AND relation. Something like this:
```
$args = array(
'post_type' => 'product',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => 'blue',
'compare' => '=',
),
array(
'key' => 'price',
'value' => array( 20, 100 ),
'type' => 'numeric',
'compare' => 'BETWEEN',
),
),
);
```
I might even have more filters. How can I convert these to REST API 2 filters?
|
This solution works with [`get_items()`](https://github.com/WP-API/WP-API/blob/develop/lib/endpoints/class-wp-rest-posts-controller.php#L81) in [`/lib/endpoints/class-wp-rest-posts-controller.php`](https://github.com/WP-API/WP-API/blob/develop/lib/endpoints/class-wp-rest-posts-controller.php) of the [`v2 WP Rest API`](http://v2.wp-api.org).
---
First, you'll want to construct the [`GET`](http://php.net/manual/en/reserved.variables.get.php) arguments like you would for a [`new WP_Query()`](https://generatewp.com/wp_query/). The easiest way to do this is with [`http_build_query()`](http://php.net/manual/en/function.http-build-query.php).
```
$args = array (
'filter' => array (
'meta_query' => array (
'relation' => 'AND',
array (
'key' => 'color',
'value' => 'blue',
'compare' => '=',
),
array (
'key' => 'test',
'value' => 'testing',
'compare' => '=',
),
),
),
);
$field_string = http_build_query( $args );
```
It'll produce something like:
`filter%5Bmeta_query%5D%5Brelation%5D=AND&filter%5Bmeta_query%5D%5B0%5D%5Bkey%5D=color&filter%5Bmeta_query%5D%5B0%5D%5Bvalue%5D=blue&filter%5Bmeta_query%5D%5B0%5D%5Bcompare%5D=%3D&filter%5Bmeta_query%5D%5B1%5D%5Bkey%5D=test&filter%5Bmeta_query%5D%5B1%5D%5Bvalue%5D=testing&filter%5Bmeta_query%5D%5B1%5D%5Bcompare%5D=%3D`
Which, if you want readable, you can also use Chrome tools and [`decodeURIComponent('your-query-here')`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) to make it a easier to read when you throw it into your [JSON Rest API URL](http://v2.wp-api.org/reference/):
[`https://demo.wp-api.org/wp-json/wp/v2/product?filter[meta_query][relation]=AND&filter[meta_query][0][key]=color&filter[meta_query][0][value]=blue&filter[meta_query][0][compare]==&filter[meta_query][1][key]=test&filter[meta_query][1][value]=testing&filter[meta_query][1][compare]==`](https://demo.wp-api.org/wp-json/wp/v2/product?filter[meta_query][relation]=AND&filter[meta_query][0][key]=color&filter[meta_query][0][value]=blue&filter[meta_query][0][compare]==&filter[meta_query][1][key]=test&filter[meta_query][1][value]=testing&filter[meta_query][1][compare]==)
Note: To use your custom post type you would put `product` before `?`
`/wp-json/wp/v2/<custom-post-type>?filter[meta_query]`
---
So you have your query but we need to instruct WP how to handle a few things:
1. Adding REST support for the custom post type `product`
2. Allowing the query args `meta_query`
3. Parsing `meta_query`
---
```
// 1) Add CPT Support <product>
function wpse_20160526_add_product_rest_support() {
global $wp_post_types;
//be sure to set this to the name of your post type!
$post_type_name = 'product';
if( isset( $wp_post_types[ $post_type_name ] ) ) {
$wp_post_types[$post_type_name]->show_in_rest = true;
$wp_post_types[$post_type_name]->rest_base = $post_type_name;
$wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
}
}
add_action( 'init', 'wpse_20160526_add_product_rest_support', 25 );
// 2) Add `meta_query` support in the GET request
function wpse_20160526_rest_query_vars( $valid_vars ) {
$valid_vars = array_merge( $valid_vars, array( 'meta_query' ) ); // Omit meta_key, meta_value if you don't need them
return $valid_vars;
}
add_filter( 'rest_query_vars', 'wpse_20160526_rest_query_vars', PHP_INT_MAX, 1 );
// 3) Parse Custom Args
function wpse_20160526_rest_product_query( $args, $request ) {
if ( isset( $args[ 'meta_query' ] ) ) {
$relation = 'AND';
if( isset($args['meta_query']['relation']) && in_array($args['meta_query']['relation'], array('AND', 'OR'))) {
$relation = sanitize_text_field( $args['meta_query']['relation'] );
}
$meta_query = array(
'relation' => $relation
);
foreach ( $args['meta_query'] as $inx => $query_req ) {
/*
Array (
[key] => test
[value] => testing
[compare] => =
)
*/
$query = array();
if( is_numeric($inx)) {
if( isset($query_req['key'])) {
$query['key'] = sanitize_text_field($query_req['key']);
}
if( isset($query_req['value'])) {
$query['value'] = sanitize_text_field($query_req['value']);
}
if( isset($query_req['type'])) {
$query['type'] = sanitize_text_field($query_req['type']);
}
if( isset($query_req['compare']) && in_array($query_req['compare'], array('=', '!=', '>','>=','<','<=','LIKE','NOT LIKE','IN','NOT IN','BETWEEN','NOT BETWEEN', 'NOT EXISTS')) ) {
$query['compare'] = sanitize_text_field($query_req['compare']);
}
}
if( ! empty($query) ) $meta_query[] = $query;
}
// replace with sanitized query args
$args['meta_query'] = $meta_query;
}
return $args;
}
add_action( 'rest_product_query', 'wpse_20160526_rest_product_query', 10, 2 );
```
|
226,605 |
<p>I am working on a theme that uses dynamic in head CSS and gives admin an option to also place the same in a file. Problem is that I am not sure what WP folder is always writable. I originally added the CSS file creation to <code>themename/css/</code> dir but since WP deletes the theme on update this has become an issue. </p>
<p>What do you think is the best way to approach this and what is the safest writable WP folder that I could use for this feature? </p>
|
[
{
"answer_id": 226606,
"author": "Jorin van Vilsteren",
"author_id": 68062,
"author_profile": "https://wordpress.stackexchange.com/users/68062",
"pm_score": 0,
"selected": false,
"text": "<p>I think the best place to write to is to add a folder in the <code>wp-content</code> folder. Here you can write your css files without it is being overwritten when you have a theme update or have a WP update.</p>\n"
},
{
"answer_id": 226607,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 4,
"selected": true,
"text": "<p>Best place is the <code>uploads</code> directory - it'll be writable by the server, and it's the defacto directory for storing any user-generated/uploaded files:</p>\n\n<pre><code>$dirs = wp_upload_dir();\n$path = $dirs['basedir']; // /path/to/wordpress/wp-content/uploads\n</code></pre>\n"
},
{
"answer_id": 226608,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": false,
"text": "<p>The only directory with guaranteed write access is the upload directory. Everything else might be protected. </p>\n\n<p>Nowadays, we deploy sites with Composer, keep everything under version control and create completely new sites with each deploy in order to be able to roll back the deployed site. That means that the directory will be created completely new with each deploy.</p>\n\n<p>Use the uploads directory if you have to write files, becase that's the only one that is kept (outside of the other directories). </p>\n"
},
{
"answer_id": 226613,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": false,
"text": "<p>One alternative approach us to have a PHP file that gets the theme options and outputs the CSS and enqueue that directly instead. eg.</p>\n\n<pre><code>wp_enqueue_style('custom-css',trailingslashit(get_template_directory_uri()).'styles.php');\n</code></pre>\n\n<p>This may seem like a strange thing to do at first, but since actually writing a new file should be done via the WP Filesystem for correct owner/group permissions, this is one way around that problem.</p>\n\n<pre><code>// send CSS Header\nheader(\"Content-type: text/css; charset: UTF-8\");\n\n// faster load by reducing memory with SHORTINIT\ndefine('SHORTINIT', true);\n\n// recursively find WordPress load\nfunction find_require($file,$folder=null) {\n if ($folder === null) {$folder = dirname(__FILE__);}\n $path = $folder.DIRECTORY_SEPARATOR.$file;\n if (file_exists($path)) {require($path); return $folder;}\n else {\n $upfolder = find_require($file,dirname($folder));\n if ($upfolder != '') {return $upfolder;}\n }\n}\n\n// load WordPress core (minimal)\n$wp_root_path = find_require('wp-load.php');\ndefine('ABSPATH', $wp_root_path);\ndefine('WPINC', 'wp-includes');\n</code></pre>\n\n<p>At this point you will need to include whatever other <code>wp-includes</code> files you need to get the theme options, which may vary depending on your how you are saving those. (You will probably need to add more so you do not get fatal errors.) eg. </p>\n\n<pre><code>include(ABSPATH.WPINC.DIRECTORY_SEPARATOR.'version.php');\ninclude(ABSPATH.WPINC.DIRECTORY_SEPARATOR.'general-template.php');\ninclude(ABSPATH.WPINC.DIRECTORY_SEPARATOR.'link-template.php');\n</code></pre>\n\n<p>Then just output the CSS options... eg.</p>\n\n<pre><code>echo 'body {color:' . get_theme_mod('body_color') . ';}';\necho 'body {backgroundcolor:' . get_theme_mod('body_background_color') . ';}';\nexit;\n</code></pre>\n"
}
] |
2016/05/14
|
[
"https://wordpress.stackexchange.com/questions/226605",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67176/"
] |
I am working on a theme that uses dynamic in head CSS and gives admin an option to also place the same in a file. Problem is that I am not sure what WP folder is always writable. I originally added the CSS file creation to `themename/css/` dir but since WP deletes the theme on update this has become an issue.
What do you think is the best way to approach this and what is the safest writable WP folder that I could use for this feature?
|
Best place is the `uploads` directory - it'll be writable by the server, and it's the defacto directory for storing any user-generated/uploaded files:
```
$dirs = wp_upload_dir();
$path = $dirs['basedir']; // /path/to/wordpress/wp-content/uploads
```
|
226,609 |
<p>I am in the process of importing large amounts of data into a custom post type that has several custom fields (postmeta fields created by <a href="https://wordpress.org/plugins/advanced-custom-fields/" rel="nofollow">Advanced Custom Fields</a>). I am using the following function to import the data and it works fine with my test file of about 10 posts with the exception of the postmeta. Here is the function I am using for the import: </p>
<pre><code>function mysite_import_json() {
$json_feed = 'http://local.mysite.com/wp-content/test.json';
$json = file_get_contents( $json_feed );
$objs = json_decode( $json, true );
$wp_error = true;
$post_id = - 1;
foreach ( $objs as $obj ) {
$title = $obj['title'];
$meta1 = $obj['taxonomy'][0];
$meta2 = $obj['nom'];
$meta3 = $obj['prenom'];
$d = new DateTime();
$d->setTimestamp( $obj['created'] );
$date_created = $d->format( 'Y-m-d H:i:s' );
$post_meta = array(
'meta_1' => $meta1,
'meta_2' => $meta2,
'meta_3' => $meta3,
);
$post_data = array(
'post_title' => $title,
'post_date' => $date_created,
'post_status' => 'publish',
'post_type' => 'cpt',
'meta_input' => $post_meta,
);
if ( null === get_page_by_title( $title, 'object', 'message' ) ) {
$post_id = wp_insert_post( $post_data, $wp_error );
foreach ( $post_meta as $key => $value ) {
update_field( $key, $value, $post_id );
}
} else {
$post_id = - 2;
}
}
}
add_action( 'after_setup_theme', 'mysite_import_json' );
</code></pre>
<p>The post meta is indeed imported but I have to manually click the update button in order to display the data on the front-end. I researched this a bit and found this (below, I would link the article but I've lost it) which I tried and limited the number of posts to 10 to rule out memory problems but it still doesn't have the desired effect of reproducing the click on publish button. </p>
<pre><code>function mass_update_posts() {
$args = array(
'post_type' => 'message',
'posts_per_page' => 10
);
$my_posts = get_posts( $args );
foreach ( $my_posts as $key => $my_post ) {
$meta_values = get_post_meta( $my_post->ID );
foreach ( $meta_values as $meta_key => $meta_value ) {
update_field( $meta_key, $meta_value[0], $my_post->ID );
}
}
}
add_action( 'init', 'mass_update_posts' );
</code></pre>
<p>I am also aware that this is going to be expensive memory-wise and am not sure the best way to go about this. Maybe in batches? </p>
<p>EDIT:
I should mention that the data is displayed on the front end by way of the WP API which actually seems to be the issue. So I suppose I need to update the API rather that the post meta in the database. The plugin that displays the ACF meta data for the WP API is <a href="https://wordpress.org/plugins/acf-to-wp-api/" rel="nofollow">ACF to WP-API</a>. </p>
|
[
{
"answer_id": 226606,
"author": "Jorin van Vilsteren",
"author_id": 68062,
"author_profile": "https://wordpress.stackexchange.com/users/68062",
"pm_score": 0,
"selected": false,
"text": "<p>I think the best place to write to is to add a folder in the <code>wp-content</code> folder. Here you can write your css files without it is being overwritten when you have a theme update or have a WP update.</p>\n"
},
{
"answer_id": 226607,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 4,
"selected": true,
"text": "<p>Best place is the <code>uploads</code> directory - it'll be writable by the server, and it's the defacto directory for storing any user-generated/uploaded files:</p>\n\n<pre><code>$dirs = wp_upload_dir();\n$path = $dirs['basedir']; // /path/to/wordpress/wp-content/uploads\n</code></pre>\n"
},
{
"answer_id": 226608,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": false,
"text": "<p>The only directory with guaranteed write access is the upload directory. Everything else might be protected. </p>\n\n<p>Nowadays, we deploy sites with Composer, keep everything under version control and create completely new sites with each deploy in order to be able to roll back the deployed site. That means that the directory will be created completely new with each deploy.</p>\n\n<p>Use the uploads directory if you have to write files, becase that's the only one that is kept (outside of the other directories). </p>\n"
},
{
"answer_id": 226613,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": false,
"text": "<p>One alternative approach us to have a PHP file that gets the theme options and outputs the CSS and enqueue that directly instead. eg.</p>\n\n<pre><code>wp_enqueue_style('custom-css',trailingslashit(get_template_directory_uri()).'styles.php');\n</code></pre>\n\n<p>This may seem like a strange thing to do at first, but since actually writing a new file should be done via the WP Filesystem for correct owner/group permissions, this is one way around that problem.</p>\n\n<pre><code>// send CSS Header\nheader(\"Content-type: text/css; charset: UTF-8\");\n\n// faster load by reducing memory with SHORTINIT\ndefine('SHORTINIT', true);\n\n// recursively find WordPress load\nfunction find_require($file,$folder=null) {\n if ($folder === null) {$folder = dirname(__FILE__);}\n $path = $folder.DIRECTORY_SEPARATOR.$file;\n if (file_exists($path)) {require($path); return $folder;}\n else {\n $upfolder = find_require($file,dirname($folder));\n if ($upfolder != '') {return $upfolder;}\n }\n}\n\n// load WordPress core (minimal)\n$wp_root_path = find_require('wp-load.php');\ndefine('ABSPATH', $wp_root_path);\ndefine('WPINC', 'wp-includes');\n</code></pre>\n\n<p>At this point you will need to include whatever other <code>wp-includes</code> files you need to get the theme options, which may vary depending on your how you are saving those. (You will probably need to add more so you do not get fatal errors.) eg. </p>\n\n<pre><code>include(ABSPATH.WPINC.DIRECTORY_SEPARATOR.'version.php');\ninclude(ABSPATH.WPINC.DIRECTORY_SEPARATOR.'general-template.php');\ninclude(ABSPATH.WPINC.DIRECTORY_SEPARATOR.'link-template.php');\n</code></pre>\n\n<p>Then just output the CSS options... eg.</p>\n\n<pre><code>echo 'body {color:' . get_theme_mod('body_color') . ';}';\necho 'body {backgroundcolor:' . get_theme_mod('body_background_color') . ';}';\nexit;\n</code></pre>\n"
}
] |
2016/05/14
|
[
"https://wordpress.stackexchange.com/questions/226609",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34045/"
] |
I am in the process of importing large amounts of data into a custom post type that has several custom fields (postmeta fields created by [Advanced Custom Fields](https://wordpress.org/plugins/advanced-custom-fields/)). I am using the following function to import the data and it works fine with my test file of about 10 posts with the exception of the postmeta. Here is the function I am using for the import:
```
function mysite_import_json() {
$json_feed = 'http://local.mysite.com/wp-content/test.json';
$json = file_get_contents( $json_feed );
$objs = json_decode( $json, true );
$wp_error = true;
$post_id = - 1;
foreach ( $objs as $obj ) {
$title = $obj['title'];
$meta1 = $obj['taxonomy'][0];
$meta2 = $obj['nom'];
$meta3 = $obj['prenom'];
$d = new DateTime();
$d->setTimestamp( $obj['created'] );
$date_created = $d->format( 'Y-m-d H:i:s' );
$post_meta = array(
'meta_1' => $meta1,
'meta_2' => $meta2,
'meta_3' => $meta3,
);
$post_data = array(
'post_title' => $title,
'post_date' => $date_created,
'post_status' => 'publish',
'post_type' => 'cpt',
'meta_input' => $post_meta,
);
if ( null === get_page_by_title( $title, 'object', 'message' ) ) {
$post_id = wp_insert_post( $post_data, $wp_error );
foreach ( $post_meta as $key => $value ) {
update_field( $key, $value, $post_id );
}
} else {
$post_id = - 2;
}
}
}
add_action( 'after_setup_theme', 'mysite_import_json' );
```
The post meta is indeed imported but I have to manually click the update button in order to display the data on the front-end. I researched this a bit and found this (below, I would link the article but I've lost it) which I tried and limited the number of posts to 10 to rule out memory problems but it still doesn't have the desired effect of reproducing the click on publish button.
```
function mass_update_posts() {
$args = array(
'post_type' => 'message',
'posts_per_page' => 10
);
$my_posts = get_posts( $args );
foreach ( $my_posts as $key => $my_post ) {
$meta_values = get_post_meta( $my_post->ID );
foreach ( $meta_values as $meta_key => $meta_value ) {
update_field( $meta_key, $meta_value[0], $my_post->ID );
}
}
}
add_action( 'init', 'mass_update_posts' );
```
I am also aware that this is going to be expensive memory-wise and am not sure the best way to go about this. Maybe in batches?
EDIT:
I should mention that the data is displayed on the front end by way of the WP API which actually seems to be the issue. So I suppose I need to update the API rather that the post meta in the database. The plugin that displays the ACF meta data for the WP API is [ACF to WP-API](https://wordpress.org/plugins/acf-to-wp-api/).
|
Best place is the `uploads` directory - it'll be writable by the server, and it's the defacto directory for storing any user-generated/uploaded files:
```
$dirs = wp_upload_dir();
$path = $dirs['basedir']; // /path/to/wordpress/wp-content/uploads
```
|
226,610 |
<p>That's my loop:</p>
<pre><code><main id="main">
<?php
// the query
$args = array('posts_per_page' => 10 );
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) { ?>
<!-- loop -->
<?php while ( $the_query->have_posts() ) {
$the_query->the_post(); ?>
</code></pre>
<p> </p>
<pre><code> <div id="thumbnail">
<?php
if ( has_post_thumbnail() ) { the_post_thumbnail(array( "class"=>"thumbnail")); } ?>
</div>
<h2><a href="<?php the_permalink();?>"><?php the_title(); ?></a></h2>
<div class="entry">
<?php the_excerpt(); ?>
</div>
</code></pre>
<p></p>
<pre><code> <?php } } else { ?>
<p><?php _e( 'Die Posts entsprechen leider nicht den Kriterien.' ); ?></p>
<?php } ?>
<!-- end of the loop -->
<?php wp_reset_postdata(); ?>
</code></pre>
<p></p>
<p>I want to use instead of 150x150px 200x200px but nothing works for me. Images should be crop.</p>
<p>Currently it looks like this: <a href="http://prnt.sc/b3v88w" rel="nofollow">http://prnt.sc/b3v88w</a></p>
<p>I tried set_post_thumbnail_size( 200, 200 ); but any changes...</p>
|
[
{
"answer_id": 226611,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p><code>set_post_thumbnail_size()</code> (and other API functions which add/change sizes) applies to generation while it's <em>active</em>. So <em>existing</em> generated image sizes won't be retroactively affected by it.</p>\n\n<p>There are plenty of tools around (plugins, wp-cli) which regenerate files with current sizes configuration.</p>\n"
},
{
"answer_id": 226622,
"author": "Howard E",
"author_id": 57589,
"author_profile": "https://wordpress.stackexchange.com/users/57589",
"pm_score": 1,
"selected": false,
"text": "<p>I use the Aqua Resizer in my theme development. <a href=\"https://github.com/syamilmj/Aqua-Resizer\" rel=\"nofollow\">https://github.com/syamilmj/Aqua-Resizer</a> </p>\n\n<p>It's pretty easy to implement, and it should do exactly what you want. This function will allow you to resize any existing WordPress image. The below example would create a 200 x 200 image from the WP Medium image, and hard crop it to 200 x 200.</p>\n\n<pre><code>$thumb = get_post_thumbnail_id();\n$img_url = wp_get_attachment_url( $thumb,'medium' ); //get full URL to image \n$image = aq_resize( $img_url, 200, 200, true ); //resize & crop the image\n</code></pre>\n\n<p>Then to call the image... </p>\n\n<pre><code> <?php if($image) : ?>\n <img src=\"<?php echo $image ?>\"/>\n <?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 226636,
"author": "jake",
"author_id": 93548,
"author_profile": "https://wordpress.stackexchange.com/users/93548",
"pm_score": 1,
"selected": false,
"text": "<p>In your function.php you can add a custom size, for example:\nadd_image_size ('custom_thumbail', 200, 200);\nThen once you regenerate thumbnails (recommended plugin by wordpress) it will create these, or any new uploaded images will have this size.</p>\n\n<p>Then you can call them in your post.</p>\n\n<p>Echo wp_get_attachment_url('your post id', 'custom_thumbail');</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_image_size/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/add_image_size/</a></p>\n"
}
] |
2016/05/14
|
[
"https://wordpress.stackexchange.com/questions/226610",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94072/"
] |
That's my loop:
```
<main id="main">
<?php
// the query
$args = array('posts_per_page' => 10 );
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) { ?>
<!-- loop -->
<?php while ( $the_query->have_posts() ) {
$the_query->the_post(); ?>
```
```
<div id="thumbnail">
<?php
if ( has_post_thumbnail() ) { the_post_thumbnail(array( "class"=>"thumbnail")); } ?>
</div>
<h2><a href="<?php the_permalink();?>"><?php the_title(); ?></a></h2>
<div class="entry">
<?php the_excerpt(); ?>
</div>
```
```
<?php } } else { ?>
<p><?php _e( 'Die Posts entsprechen leider nicht den Kriterien.' ); ?></p>
<?php } ?>
<!-- end of the loop -->
<?php wp_reset_postdata(); ?>
```
I want to use instead of 150x150px 200x200px but nothing works for me. Images should be crop.
Currently it looks like this: <http://prnt.sc/b3v88w>
I tried set\_post\_thumbnail\_size( 200, 200 ); but any changes...
|
`set_post_thumbnail_size()` (and other API functions which add/change sizes) applies to generation while it's *active*. So *existing* generated image sizes won't be retroactively affected by it.
There are plenty of tools around (plugins, wp-cli) which regenerate files with current sizes configuration.
|
226,621 |
<p>I currently have this code from a plugin.</p>
<pre><code>[imdbi meta_name=poster]
</code></pre>
<p>This cache an Image Link, and it simply display the link, I want it to display it as an image. Is this possible?</p>
|
[
{
"answer_id": 226637,
"author": "Usce",
"author_id": 81451,
"author_profile": "https://wordpress.stackexchange.com/users/81451",
"pm_score": 2,
"selected": true,
"text": "<p>This is some specific shortcode to some plugin, that if you just want to paste an image in wordpress editor isn't necessary. (Also there is not enough info about what this shortcode is about). </p>\n\n<p>So there is simple HTML that will simply display link you want as an image, following: </p>\n\n<pre><code><img src=\"http://here-goes-some-url-of-your-image\" />\n</code></pre>\n\n<p>Make sure you put the url in between the quotations as mentioned in this tag, and that you put actual link in there. Also make sure you paste this in wordpress text editor(tab next to visual editor) and when you publish your post/page it will be there :) </p>\n"
},
{
"answer_id": 226641,
"author": "Anand Prakash",
"author_id": 94086,
"author_profile": "https://wordpress.stackexchange.com/users/94086",
"pm_score": 0,
"selected": false,
"text": "<p>Go to visuals when writing a post or building a page. Then use this:</p>\n\n<pre><code><img src=\"http://your image .jpg\" />\n</code></pre>\n\n<p>Just copy the complete image address and paste it in between the quotes \" \".</p>\n"
}
] |
2016/05/14
|
[
"https://wordpress.stackexchange.com/questions/226621",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94079/"
] |
I currently have this code from a plugin.
```
[imdbi meta_name=poster]
```
This cache an Image Link, and it simply display the link, I want it to display it as an image. Is this possible?
|
This is some specific shortcode to some plugin, that if you just want to paste an image in wordpress editor isn't necessary. (Also there is not enough info about what this shortcode is about).
So there is simple HTML that will simply display link you want as an image, following:
```
<img src="http://here-goes-some-url-of-your-image" />
```
Make sure you put the url in between the quotations as mentioned in this tag, and that you put actual link in there. Also make sure you paste this in wordpress text editor(tab next to visual editor) and when you publish your post/page it will be there :)
|
226,652 |
<p>I am trying to make the featured images retrieved by the_post_thumbnai() in the loop responsive, but can't seem to find a simplified solution.</p>
<p>The logic I want to implement is something like this:</p>
<pre><code>If the screen size is less or equal to 728px
the_post_thumbnai('thumbnail') //Display the thumbnail size image
Else
the_post_thumbnai() //display the original size image
</code></pre>
<p>Can anyone suggest how I can do this without any plugins?</p>
<p>I am not a php expert, so please go easy on the lingo. Thanks in advance.</p>
|
[
{
"answer_id": 226637,
"author": "Usce",
"author_id": 81451,
"author_profile": "https://wordpress.stackexchange.com/users/81451",
"pm_score": 2,
"selected": true,
"text": "<p>This is some specific shortcode to some plugin, that if you just want to paste an image in wordpress editor isn't necessary. (Also there is not enough info about what this shortcode is about). </p>\n\n<p>So there is simple HTML that will simply display link you want as an image, following: </p>\n\n<pre><code><img src=\"http://here-goes-some-url-of-your-image\" />\n</code></pre>\n\n<p>Make sure you put the url in between the quotations as mentioned in this tag, and that you put actual link in there. Also make sure you paste this in wordpress text editor(tab next to visual editor) and when you publish your post/page it will be there :) </p>\n"
},
{
"answer_id": 226641,
"author": "Anand Prakash",
"author_id": 94086,
"author_profile": "https://wordpress.stackexchange.com/users/94086",
"pm_score": 0,
"selected": false,
"text": "<p>Go to visuals when writing a post or building a page. Then use this:</p>\n\n<pre><code><img src=\"http://your image .jpg\" />\n</code></pre>\n\n<p>Just copy the complete image address and paste it in between the quotes \" \".</p>\n"
}
] |
2016/05/14
|
[
"https://wordpress.stackexchange.com/questions/226652",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90205/"
] |
I am trying to make the featured images retrieved by the\_post\_thumbnai() in the loop responsive, but can't seem to find a simplified solution.
The logic I want to implement is something like this:
```
If the screen size is less or equal to 728px
the_post_thumbnai('thumbnail') //Display the thumbnail size image
Else
the_post_thumbnai() //display the original size image
```
Can anyone suggest how I can do this without any plugins?
I am not a php expert, so please go easy on the lingo. Thanks in advance.
|
This is some specific shortcode to some plugin, that if you just want to paste an image in wordpress editor isn't necessary. (Also there is not enough info about what this shortcode is about).
So there is simple HTML that will simply display link you want as an image, following:
```
<img src="http://here-goes-some-url-of-your-image" />
```
Make sure you put the url in between the quotations as mentioned in this tag, and that you put actual link in there. Also make sure you paste this in wordpress text editor(tab next to visual editor) and when you publish your post/page it will be there :)
|
226,685 |
<p>I have been asked to switch between the existing front/home page of a website which has the URL</p>
<pre class="lang-none prettyprint-override"><code>http://www.example.com
</code></pre>
<p>to a differnt page with the URL</p>
<pre class="lang-none prettyprint-override"><code>http://www.example.com/?i=0
</code></pre>
<p>It's a very old website (twenty twelve theme), and I can't understand what this <code>?i=0</code> means, and how they built this specific page.</p>
<p><strong>To add clarity</strong></p>
<p>In the website <code>www.example.com</code> there is a page which has a URL structure that is different from all other pages and this is the URL: <code>www.example.com/?i=0</code></p>
<p>The client wants that this page (<code>www.example.com/?i=0</code>) will be the home page and not an inner page, so I am trying to understand how to build it. Now it is not in the WordPress pages list, it's not a post or a category. I have also tried to disable all the plugins, but it didn't effect the page URL or its content, so I don't know where this page is coming from.</p>
|
[
{
"answer_id": 226672,
"author": "Monkey Puzzle",
"author_id": 48568,
"author_profile": "https://wordpress.stackexchange.com/users/48568",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, this is a known problem between ios devices and Wordpress. It's a real issue due to the high numbers of iPhone/ipad users who also use Wordpress, and I'm surprised it hasn't been addressed in the Wordpress core. Looks like it's still being debated/ worked on <a href=\"https://core.trac.wordpress.org/ticket/14459\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>It's a question that's been asked before <a href=\"https://stackoverflow.com/questions/10777335/wordpress-doesnt-apply-rotation-to-iphone-images\">here</a>. As that answer notes, there are plugins for this job, including <a href=\"https://wordpress.org/plugins/ios-images-fixer/\" rel=\"nofollow noreferrer\">ios images fixer</a> and <a href=\"https://wordpress.org/plugins/image-rotation-repair/\" rel=\"nofollow noreferrer\">image rotation repair</a> (not updated for a while) and <a href=\"https://wordpress.org/plugins/image-rotation-fixer/\" rel=\"nofollow noreferrer\">Image Rotation Fixer</a> although I'm not sure if they apply to existing images or only new uploads. </p>\n"
},
{
"answer_id": 226677,
"author": "jake",
"author_id": 93548,
"author_profile": "https://wordpress.stackexchange.com/users/93548",
"pm_score": 1,
"selected": false,
"text": "<p>Its the way the photos are encoded and they sometimes respond differently on different devices/platforms. </p>\n\n<p>If the images aren't referenced in your posts, you can open them all in a program such as Adobe Bridge/Lightbox and bulk re-save them all. This should fix the issue, but is a bit more manual. </p>\n"
}
] |
2016/05/15
|
[
"https://wordpress.stackexchange.com/questions/226685",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94124/"
] |
I have been asked to switch between the existing front/home page of a website which has the URL
```none
http://www.example.com
```
to a differnt page with the URL
```none
http://www.example.com/?i=0
```
It's a very old website (twenty twelve theme), and I can't understand what this `?i=0` means, and how they built this specific page.
**To add clarity**
In the website `www.example.com` there is a page which has a URL structure that is different from all other pages and this is the URL: `www.example.com/?i=0`
The client wants that this page (`www.example.com/?i=0`) will be the home page and not an inner page, so I am trying to understand how to build it. Now it is not in the WordPress pages list, it's not a post or a category. I have also tried to disable all the plugins, but it didn't effect the page URL or its content, so I don't know where this page is coming from.
|
Yes, this is a known problem between ios devices and Wordpress. It's a real issue due to the high numbers of iPhone/ipad users who also use Wordpress, and I'm surprised it hasn't been addressed in the Wordpress core. Looks like it's still being debated/ worked on [here](https://core.trac.wordpress.org/ticket/14459).
It's a question that's been asked before [here](https://stackoverflow.com/questions/10777335/wordpress-doesnt-apply-rotation-to-iphone-images). As that answer notes, there are plugins for this job, including [ios images fixer](https://wordpress.org/plugins/ios-images-fixer/) and [image rotation repair](https://wordpress.org/plugins/image-rotation-repair/) (not updated for a while) and [Image Rotation Fixer](https://wordpress.org/plugins/image-rotation-fixer/) although I'm not sure if they apply to existing images or only new uploads.
|
226,696 |
<p>I am working on a CSS and JS compiler and need to find a way to list the contents of <code>wp_head()</code> </p>
<p>I am trying to get a list of all CSS/JS files and inline CSS on any give page. </p>
<p>Hooking on the wp_head action does not do anything </p>
<p>I was hoping that something like this would work </p>
<pre><code>function head_content($list){
print_r($list);
}
add_action('wp_head', 'head_content');
</code></pre>
<p>any help is appreciated. </p>
<p><strong>UPDATE</strong>: </p>
<p>got something working </p>
<pre><code>function head_content($list){
print_r($list);
return $list;
}
add_filter('print_styles_array', 'head_content');
add_filter('print_script_array', 'head_content');
</code></pre>
<p>this lists all css/js files handles </p>
|
[
{
"answer_id": 226720,
"author": "Ismail",
"author_id": 70833,
"author_profile": "https://wordpress.stackexchange.com/users/70833",
"pm_score": 2,
"selected": false,
"text": "<p>Simple solution is to listen for <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head\" rel=\"nofollow\">wp_head</a> in a custom function, just like WordPress does in <code>wp-includes/general-template.php</code> for <code>wp_head()</code> function.</p>\n\n<p>I mean something like:</p>\n\n<pre><code>function head_content() {\n ob_start();\n do_action('wp_head');\n return ob_get_clean();\n}\n// contents\nvar_dump( head_content() );\n</code></pre>\n\n<p>Later, use regex or other tool to filter the contents you are targeting..</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 226728,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 2,
"selected": false,
"text": "<p>You could buffer the <code>wp_head</code> output by adding some wrapper actions to it:</p>\n\n<pre><code>add_action('wp_head','start_wp_head_buffer',0);\nfunction start_wp_head_buffer() {ob_start;}\nadd_action('wp_head','end_wp_head_buffer',99);\nfunction end_wp_head_buffer() {global $wpheadcontents; $wpheadcontents = ob_get_flush();}\n</code></pre>\n\n<p>You can then call <code>global $wpheadcontents;</code> elsewhere to access the content and process it.</p>\n\n<p>But, in this case, it may be simpler to just get the information you are looking for directly from the global <code>$wp_styles</code> and <code>$wp_scripts</code> variables.</p>\n\n<pre><code>function print_global_arrays() {\n global $wp_styles, $wp_scripts;\n echo \"Styles Array:\"; print_r($wp_styles);\n echo \"Scripts Array:\"; print_r($wp_scripts);\n}\nadd_action('wp_enqueue_scripts','print_global_arrays',999);\n</code></pre>\n"
},
{
"answer_id": 242249,
"author": "Putnik",
"author_id": 26437,
"author_profile": "https://wordpress.stackexchange.com/users/26437",
"pm_score": 4,
"selected": true,
"text": "<p>I wanted to search-and-replace in the header, but Neither @majick or @Samuel Elh answers worked for me directly. So, combining their answers I got what eventually works:</p>\n\n<pre><code>function start_wp_head_buffer() {\n ob_start();\n}\nadd_action('wp_head','start_wp_head_buffer',0);\n\nfunction end_wp_head_buffer() {\n $in = ob_get_clean();\n\n // here do whatever you want with the header code\n echo $in; // output the result unless you want to remove it\n}\nadd_action('wp_head','end_wp_head_buffer', PHP_INT_MAX); //PHP_INT_MAX will ensure this action is called after all other actions that can modify head\n</code></pre>\n\n<p>It was added to <code>functions.php</code> of my child theme.</p>\n"
}
] |
2016/05/15
|
[
"https://wordpress.stackexchange.com/questions/226696",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67176/"
] |
I am working on a CSS and JS compiler and need to find a way to list the contents of `wp_head()`
I am trying to get a list of all CSS/JS files and inline CSS on any give page.
Hooking on the wp\_head action does not do anything
I was hoping that something like this would work
```
function head_content($list){
print_r($list);
}
add_action('wp_head', 'head_content');
```
any help is appreciated.
**UPDATE**:
got something working
```
function head_content($list){
print_r($list);
return $list;
}
add_filter('print_styles_array', 'head_content');
add_filter('print_script_array', 'head_content');
```
this lists all css/js files handles
|
I wanted to search-and-replace in the header, but Neither @majick or @Samuel Elh answers worked for me directly. So, combining their answers I got what eventually works:
```
function start_wp_head_buffer() {
ob_start();
}
add_action('wp_head','start_wp_head_buffer',0);
function end_wp_head_buffer() {
$in = ob_get_clean();
// here do whatever you want with the header code
echo $in; // output the result unless you want to remove it
}
add_action('wp_head','end_wp_head_buffer', PHP_INT_MAX); //PHP_INT_MAX will ensure this action is called after all other actions that can modify head
```
It was added to `functions.php` of my child theme.
|
226,749 |
<p>I am developing a new WP site. My client complains that he see old site data like links that refer to old category names. On my PC and other I have no problems with this. On server side there is no cache plugin running. Reason: site is still in development. On my PC and in every browser there is no such problem. Always get the newest page info.</p>
<p>I only use in htaccess file this for Leverage Browser Caching</p>
<pre><code><IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType text/css "access 1 month"
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
# Leverage Browser Caching Ninja -- Ends here
</code></pre>
<p>What can I suggest my customer to do/change his local PC settings so he get always the newest data? </p>
|
[
{
"answer_id": 226751,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<p>Unsurprisingly so since you tell browser to cache everything for 1 month by default (<code>ExpiresDefault \"access plus 1 month\"</code>).</p>\n\n<p>You should limit long caching times to static resources and leave pages served by WP out of it.</p>\n\n<p>My go to resource for <a href=\"https://github.com/h5bp/server-configs-apache/blob/master/dist/.htaccess\" rel=\"nofollow\"><code>.htaccess</code> configuration</a> is HTML5 Boilerplate.</p>\n\n<p>It works with WP nicely and correctly excludes web pages from agressive browser caching (<code>ExpiresByType text/html \"access plus 0 seconds\"</code>).</p>\n"
},
{
"answer_id": 226753,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You should never set an expiry for the HTML which is longer then few hours and never set expiry for logged in users at all.</p>\n\n<p>The reason is that while you can cache bust CSS, JS and even images, you just can't do it with HTML as users are accessing html URLs directly and you have no way to instruct them to go to a \"fresher\" ones.</p>\n\n<p>In you case </p>\n\n<pre><code>ExpiresDefault \"access plus 1 month\"\n</code></pre>\n\n<p>Can trigger caching of the HTML for a month, and the lesser problem is when it is cached on the costumers computer, as he can use the browser tools to clear the cache, but if it is cached at any proxy then you will not have any way to clear it and the site will serve stale pages for a month.</p>\n\n<p>In addition to the general problem of cached pages this also have security implications as admin pages might be cache with whatever confidential information they contain and people that do not have read access to the site will be able to read it from the proxy.</p>\n"
}
] |
2016/05/16
|
[
"https://wordpress.stackexchange.com/questions/226749",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78746/"
] |
I am developing a new WP site. My client complains that he see old site data like links that refer to old category names. On my PC and other I have no problems with this. On server side there is no cache plugin running. Reason: site is still in development. On my PC and in every browser there is no such problem. Always get the newest page info.
I only use in htaccess file this for Leverage Browser Caching
```
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType text/css "access 1 month"
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
# Leverage Browser Caching Ninja -- Ends here
```
What can I suggest my customer to do/change his local PC settings so he get always the newest data?
|
Unsurprisingly so since you tell browser to cache everything for 1 month by default (`ExpiresDefault "access plus 1 month"`).
You should limit long caching times to static resources and leave pages served by WP out of it.
My go to resource for [`.htaccess` configuration](https://github.com/h5bp/server-configs-apache/blob/master/dist/.htaccess) is HTML5 Boilerplate.
It works with WP nicely and correctly excludes web pages from agressive browser caching (`ExpiresByType text/html "access plus 0 seconds"`).
|
226,765 |
<p>I want to add a meta value to my post , which will be based on another meta value , before publish post . This is what I have tried </p>
<pre><code>add_action('save_post_my_custom_post', 'add_custom_field_automatically' );
function add_custom_field_automatically($post_ID) {
$new_meta_value = get_post_meta($post_ID,'_my_meta_key',TRUE).'to ' .' something new';
add_post_meta($post_ID, '_my_new_meta_key', $new_meta_value, true);
}
</code></pre>
<p>But it doesn't work . The hook fired properly , it saves only "to something new" , but what I expect the value should be "my meta value to something new"</p>
|
[
{
"answer_id": 226857,
"author": "Mithun Sarker Shuvro",
"author_id": 56654,
"author_profile": "https://wordpress.stackexchange.com/users/56654",
"pm_score": 3,
"selected": true,
"text": "<p>The solution is using <code>added_post_meta</code> and <code>updated_post_meta</code> hook . </p>\n\n<p>Here is the working code . </p>\n\n<pre><code>add_action( 'added_post_meta', 'add_custom_field_automatically', 10, 4 );\nadd_action( 'updated_post_meta', 'add_custom_field_automatically', 10, 4 );\nfunction add_custom_field_automatically( $meta_id, $post_id, $meta_key, $meta_value )\n{\n if ( '_my_meta_key' == $meta_key ) {\n\n add_post_meta($post_id, '_my_new_meta_key', $meta_value.'to something new', true);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 226872,
"author": "AR Bhatti",
"author_id": 94177,
"author_profile": "https://wordpress.stackexchange.com/users/94177",
"pm_score": -1,
"selected": false,
"text": "<p>Use <code>global $post</code> at the top of the page just before the function start</p>\n\n<pre><code>global $post;\n</code></pre>\n"
}
] |
2016/05/16
|
[
"https://wordpress.stackexchange.com/questions/226765",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56654/"
] |
I want to add a meta value to my post , which will be based on another meta value , before publish post . This is what I have tried
```
add_action('save_post_my_custom_post', 'add_custom_field_automatically' );
function add_custom_field_automatically($post_ID) {
$new_meta_value = get_post_meta($post_ID,'_my_meta_key',TRUE).'to ' .' something new';
add_post_meta($post_ID, '_my_new_meta_key', $new_meta_value, true);
}
```
But it doesn't work . The hook fired properly , it saves only "to something new" , but what I expect the value should be "my meta value to something new"
|
The solution is using `added_post_meta` and `updated_post_meta` hook .
Here is the working code .
```
add_action( 'added_post_meta', 'add_custom_field_automatically', 10, 4 );
add_action( 'updated_post_meta', 'add_custom_field_automatically', 10, 4 );
function add_custom_field_automatically( $meta_id, $post_id, $meta_key, $meta_value )
{
if ( '_my_meta_key' == $meta_key ) {
add_post_meta($post_id, '_my_new_meta_key', $meta_value.'to something new', true);
}
}
```
|
226,832 |
<p>I'm trying to output an array into one table cell. Here is a truncated version of what I have now:</p>
<pre><code>$prerequisites = get_post_meta($post->ID, 'opl_prerequisites', true);
$output .= '<td>';
if(count($prerequisites) === 1){
foreach( $prerequisites as &$prerequisite ):
$prerequisite_object = get_post( $prerequisite );
$output .= $prerequisite_object->post_title;
endforeach;
} else {
foreach( $prerequisites as &$prerequisite ):
$prerequisite_object = get_post( $prerequisite );
$output .= $prerequisite_object->post_title.', ';
endforeach;
}
$output .= '</td>';
</code></pre>
<p>This returns basically what I want, although I know there are definitely some issues with how I am calling it. I just want the contents of the array to be returned in one cell separated by commas without a comma being at the very end. Currently this code puts a comma at the end if there are more than 1 items in the array. A couple of issues I'm trying to figure out:</p>
<ul>
<li><p>In the first IF statement, I have a foreach statement because I can't seem to get it to display the data inside the array unless I call it this way, even though there is only one item in the array. Is there a shorter way to get the post_title out? When I call it like <code>$output .= $prerequisites[0];</code> it only gives me the post ID instead of the post_title. </p></li>
<li><p>I have messed around with the <code>implode();</code> php function but I can't seem to find its exact use with this situation. I feel like that would be the short way to do what I'm trying to do.</p></li>
</ul>
<p>Any help would be greatly appreciated. Thanks in advance!</p>
|
[
{
"answer_id": 226834,
"author": "BillK",
"author_id": 87352,
"author_profile": "https://wordpress.stackexchange.com/users/87352",
"pm_score": 1,
"selected": false,
"text": "<p>Passing <code>true</code> as the 3rd parameter to <code>get_post_meta()</code> says to return only one item. Pass <code>false</code>, or leave it empty, to get an array of matching meta items.</p>\n\n<p>The <code>foreach</code> loop below should work, then remove the extra comma if present.</p>\n\n<pre><code>$prerequisites = get_post_meta($post->ID, 'opl_prerequisites', FALSE);\n\n$td_output = '<td>';\nforeach( $prerequisites as $prerequisite ){\n $td_output .= get_the_title( $prerequisite ) . ', ';\n}\nif( strlen($td_output) > 4 ){\n // remove trailing comma if any prerequisite titles added\n $td_output = substr( $td_output, 0, -2 ); \n}\n$td_output .= '</td>';\n$output .= $td_output;\n</code></pre>\n"
},
{
"answer_id": 226870,
"author": "AntonChanning",
"author_id": 5077,
"author_profile": "https://wordpress.stackexchange.com/users/5077",
"pm_score": 1,
"selected": true,
"text": "<p>Alternatively, make an array of the titles and then use <a href=\"http://php.net/manual/en/function.implode.php\" rel=\"nofollow\">implode</a>...</p>\n\n<pre><code>$prerequisites = get_post_meta($post->ID, 'opl_prerequisites', TRUE);\n$titles = array();\nforeach( $prerequisites as $prerequisite ){\n $titles[] = get_the_title( $prerequisite );\n}\n\n$output .= '<td>'.implode(\",\", $titles).'</td>';\n</code></pre>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226832",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93811/"
] |
I'm trying to output an array into one table cell. Here is a truncated version of what I have now:
```
$prerequisites = get_post_meta($post->ID, 'opl_prerequisites', true);
$output .= '<td>';
if(count($prerequisites) === 1){
foreach( $prerequisites as &$prerequisite ):
$prerequisite_object = get_post( $prerequisite );
$output .= $prerequisite_object->post_title;
endforeach;
} else {
foreach( $prerequisites as &$prerequisite ):
$prerequisite_object = get_post( $prerequisite );
$output .= $prerequisite_object->post_title.', ';
endforeach;
}
$output .= '</td>';
```
This returns basically what I want, although I know there are definitely some issues with how I am calling it. I just want the contents of the array to be returned in one cell separated by commas without a comma being at the very end. Currently this code puts a comma at the end if there are more than 1 items in the array. A couple of issues I'm trying to figure out:
* In the first IF statement, I have a foreach statement because I can't seem to get it to display the data inside the array unless I call it this way, even though there is only one item in the array. Is there a shorter way to get the post\_title out? When I call it like `$output .= $prerequisites[0];` it only gives me the post ID instead of the post\_title.
* I have messed around with the `implode();` php function but I can't seem to find its exact use with this situation. I feel like that would be the short way to do what I'm trying to do.
Any help would be greatly appreciated. Thanks in advance!
|
Alternatively, make an array of the titles and then use [implode](http://php.net/manual/en/function.implode.php)...
```
$prerequisites = get_post_meta($post->ID, 'opl_prerequisites', TRUE);
$titles = array();
foreach( $prerequisites as $prerequisite ){
$titles[] = get_the_title( $prerequisite );
}
$output .= '<td>'.implode(",", $titles).'</td>';
```
|
226,839 |
<p>In my site, I created a <code>custom post type</code> called: "Pictures"</p>
<pre><code>add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'Pictures',
array(
'labels' => array(
'name' => __( 'Pictures' ),
'singular_name' => __( 'Pictures' )
),
'public' => true,
'has_archive' => true,
)
);
}
</code></pre>
<p>In my site, I want to have two pages: Index and Pictures</p>
<p>->Index: It had posts only of text
->Pictures: It had posts only of pictures</p>
<p>In Dashboard -> Posts. All posts that I did go straight to the index.</p>
<p>I wonder how I can access the Dashboard-> Pictures-> Add New
. And each post I do, fall into the "Pictures" page.</p>
<p>How I can do this?</p>
|
[
{
"answer_id": 226840,
"author": "v3leno",
"author_id": 94216,
"author_profile": "https://wordpress.stackexchange.com/users/94216",
"pm_score": 1,
"selected": false,
"text": "<p>Hello maybe this can help, i use this kind of query to retrieve cpt query and display contents:</p>\n\n<pre><code> <?php // querying Database\n $args = array( 'post_type' => 'Pictures', 'posts_per_page' => 6);\n $the_query = new WP_Query( $args ); \n ?>\n <?php // creating the loog\n if ( $the_query->have_posts() ) : while( $the_query->have_posts() ) : $the_query->the_post();\n ?>\n\n- output goes here, like the_content() or what you need - \n\n <?php wp_reset_postdata(); ?>\n <?php endwhile; ?>\n <?php else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n</code></pre>\n\n<p>more... your CPT register name must be all lowercase, and at the end of your plugin file you have to add something like this to be able to query your cpt </p>\n\n<pre><code>// Querying custom post type\nadd_action( 'pre_get_posts', 'add_pictures_post_types_to_query' );\n\nfunction add_pictures_post_types_to_query( $query ) {\n if ( is_home() && $query->is_main_query() )\n $query->set( 'post_type', array( 'post', 'pictures' ) );\n return $query;\n}\n</code></pre>\n"
},
{
"answer_id": 226843,
"author": "AJD",
"author_id": 59712,
"author_profile": "https://wordpress.stackexchange.com/users/59712",
"pm_score": 1,
"selected": true,
"text": "<p>You need to add:</p>\n\n<pre><code>'supports' => array('title', 'editor','page-attributes','thumbnail')\n</code></pre>\n\n<p>add this to your array after 'singular name' => 'pictures'.</p>\n\n<p>The thumbnail adds the featured image option to your post type. </p>\n\n<p>You can access the post type archive: yoursite/archive-pictures, this will use your themes archive.php file if it exists. </p>\n\n<p>Or you can create a custom post type archive template with a custom loop: archive-pictures.php.</p>\n\n<p>Or you can create a custom page template and apply it to a page.</p>\n\n<p>Both the post-type archive and custom page template would contain similar code: a custom post type loop like this:</p>\n\n<pre><code>$args = array( 'post_type' => 'pictures', 'posts_per_page' => 10 );\n$loop = new WP_Query( $args );\nwhile ( $loop->have_posts() ) : $loop->the_post();\n the_title();\n echo '<div class=\"entry-content\">';\n the_content();\n the_post_thumbnail(\"medium\");\n echo '</div>';\nendwhile;\n</code></pre>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226839",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94215/"
] |
In my site, I created a `custom post type` called: "Pictures"
```
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'Pictures',
array(
'labels' => array(
'name' => __( 'Pictures' ),
'singular_name' => __( 'Pictures' )
),
'public' => true,
'has_archive' => true,
)
);
}
```
In my site, I want to have two pages: Index and Pictures
->Index: It had posts only of text
->Pictures: It had posts only of pictures
In Dashboard -> Posts. All posts that I did go straight to the index.
I wonder how I can access the Dashboard-> Pictures-> Add New
. And each post I do, fall into the "Pictures" page.
How I can do this?
|
You need to add:
```
'supports' => array('title', 'editor','page-attributes','thumbnail')
```
add this to your array after 'singular name' => 'pictures'.
The thumbnail adds the featured image option to your post type.
You can access the post type archive: yoursite/archive-pictures, this will use your themes archive.php file if it exists.
Or you can create a custom post type archive template with a custom loop: archive-pictures.php.
Or you can create a custom page template and apply it to a page.
Both the post-type archive and custom page template would contain similar code: a custom post type loop like this:
```
$args = array( 'post_type' => 'pictures', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
echo '<div class="entry-content">';
the_content();
the_post_thumbnail("medium");
echo '</div>';
endwhile;
```
|
226,841 |
<p>I am using a theme which shows the featured image as background image in post navigation elements (next and previous links on a single post). But I want to remove these background images. </p>
<p>Here is the actual code in template-tags.php file.</p>
<pre><code>function shoreditch_post_nav_background() {
if ( ! is_single() ) {
return;
}
$previous = ( is_attachment() ) ? get_post( get_post()->post_parent ) : get_adjacent_post( false, '', true );
$next = get_adjacent_post( false, '', false );
$css = '';
if ( is_attachment() && 'attachment' == $previous->post_type ) {
return;
}
if ( $previous && has_post_thumbnail( $previous->ID ) ) {
$prevthumb = wp_get_attachment_image_src( get_post_thumbnail_id( $previous->ID ), 'post-thumbnail' );
$css .= '
.post-navigation .nav-previous { background-image: url(' . esc_url( $prevthumb[0] ) . '); text-shadow: 0 0 0.15em rgba(0, 0, 0, 0.5); }
.post-navigation .nav-previous .post-title,
.post-navigation .nav-previous a:focus .post-title,
.post-navigation .nav-previous a:hover .post-title { color: #fff; }
.post-navigation .nav-previous .meta-nav { color: rgba(255, 255, 255, 0.75); }
.post-navigation .nav-previous a { background-color: rgba(0, 0, 0, 0.2); border: 0; }
.post-navigation .nav-previous a:focus,
.post-navigation .nav-previous a:hover { background-color: rgba(0, 0, 0, 0.4); }
';
}
if ( $next && has_post_thumbnail( $next->ID ) ) {
$nextthumb = wp_get_attachment_image_src( get_post_thumbnail_id( $next->ID ), 'post-thumbnail' );
$css .= '
.post-navigation .nav-next { background-image: url(' . esc_url( $nextthumb[0] ) . '); text-shadow: 0 0 0.15em rgba(0, 0, 0, 0.5); }
.post-navigation .nav-next .post-title,
.post-navigation .nav-next a:focus .post-title,
.post-navigation .nav-next a:hover .post-title { color: #fff; }
.post-navigation .nav-next .meta-nav { color: rgba(255, 255, 255, 0.75); }
.post-navigation .nav-next a { background-color: rgba(0, 0, 0, 0.2); border: 0; }
.post-navigation .nav-next a:focus,
.post-navigation .nav-next a:hover { background-color: rgba(0, 0, 0, 0.4); }
';
}
wp_add_inline_style( 'shoreditch-style', $css );
}
add_action( 'wp_enqueue_scripts', 'shoreditch_post_nav_background' );
</code></pre>
<p>How can I remove those background images while using my child theme functions.php file, without modifying the actual file in parent theme?</p>
|
[
{
"answer_id": 226840,
"author": "v3leno",
"author_id": 94216,
"author_profile": "https://wordpress.stackexchange.com/users/94216",
"pm_score": 1,
"selected": false,
"text": "<p>Hello maybe this can help, i use this kind of query to retrieve cpt query and display contents:</p>\n\n<pre><code> <?php // querying Database\n $args = array( 'post_type' => 'Pictures', 'posts_per_page' => 6);\n $the_query = new WP_Query( $args ); \n ?>\n <?php // creating the loog\n if ( $the_query->have_posts() ) : while( $the_query->have_posts() ) : $the_query->the_post();\n ?>\n\n- output goes here, like the_content() or what you need - \n\n <?php wp_reset_postdata(); ?>\n <?php endwhile; ?>\n <?php else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n</code></pre>\n\n<p>more... your CPT register name must be all lowercase, and at the end of your plugin file you have to add something like this to be able to query your cpt </p>\n\n<pre><code>// Querying custom post type\nadd_action( 'pre_get_posts', 'add_pictures_post_types_to_query' );\n\nfunction add_pictures_post_types_to_query( $query ) {\n if ( is_home() && $query->is_main_query() )\n $query->set( 'post_type', array( 'post', 'pictures' ) );\n return $query;\n}\n</code></pre>\n"
},
{
"answer_id": 226843,
"author": "AJD",
"author_id": 59712,
"author_profile": "https://wordpress.stackexchange.com/users/59712",
"pm_score": 1,
"selected": true,
"text": "<p>You need to add:</p>\n\n<pre><code>'supports' => array('title', 'editor','page-attributes','thumbnail')\n</code></pre>\n\n<p>add this to your array after 'singular name' => 'pictures'.</p>\n\n<p>The thumbnail adds the featured image option to your post type. </p>\n\n<p>You can access the post type archive: yoursite/archive-pictures, this will use your themes archive.php file if it exists. </p>\n\n<p>Or you can create a custom post type archive template with a custom loop: archive-pictures.php.</p>\n\n<p>Or you can create a custom page template and apply it to a page.</p>\n\n<p>Both the post-type archive and custom page template would contain similar code: a custom post type loop like this:</p>\n\n<pre><code>$args = array( 'post_type' => 'pictures', 'posts_per_page' => 10 );\n$loop = new WP_Query( $args );\nwhile ( $loop->have_posts() ) : $loop->the_post();\n the_title();\n echo '<div class=\"entry-content\">';\n the_content();\n the_post_thumbnail(\"medium\");\n echo '</div>';\nendwhile;\n</code></pre>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226841",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/20840/"
] |
I am using a theme which shows the featured image as background image in post navigation elements (next and previous links on a single post). But I want to remove these background images.
Here is the actual code in template-tags.php file.
```
function shoreditch_post_nav_background() {
if ( ! is_single() ) {
return;
}
$previous = ( is_attachment() ) ? get_post( get_post()->post_parent ) : get_adjacent_post( false, '', true );
$next = get_adjacent_post( false, '', false );
$css = '';
if ( is_attachment() && 'attachment' == $previous->post_type ) {
return;
}
if ( $previous && has_post_thumbnail( $previous->ID ) ) {
$prevthumb = wp_get_attachment_image_src( get_post_thumbnail_id( $previous->ID ), 'post-thumbnail' );
$css .= '
.post-navigation .nav-previous { background-image: url(' . esc_url( $prevthumb[0] ) . '); text-shadow: 0 0 0.15em rgba(0, 0, 0, 0.5); }
.post-navigation .nav-previous .post-title,
.post-navigation .nav-previous a:focus .post-title,
.post-navigation .nav-previous a:hover .post-title { color: #fff; }
.post-navigation .nav-previous .meta-nav { color: rgba(255, 255, 255, 0.75); }
.post-navigation .nav-previous a { background-color: rgba(0, 0, 0, 0.2); border: 0; }
.post-navigation .nav-previous a:focus,
.post-navigation .nav-previous a:hover { background-color: rgba(0, 0, 0, 0.4); }
';
}
if ( $next && has_post_thumbnail( $next->ID ) ) {
$nextthumb = wp_get_attachment_image_src( get_post_thumbnail_id( $next->ID ), 'post-thumbnail' );
$css .= '
.post-navigation .nav-next { background-image: url(' . esc_url( $nextthumb[0] ) . '); text-shadow: 0 0 0.15em rgba(0, 0, 0, 0.5); }
.post-navigation .nav-next .post-title,
.post-navigation .nav-next a:focus .post-title,
.post-navigation .nav-next a:hover .post-title { color: #fff; }
.post-navigation .nav-next .meta-nav { color: rgba(255, 255, 255, 0.75); }
.post-navigation .nav-next a { background-color: rgba(0, 0, 0, 0.2); border: 0; }
.post-navigation .nav-next a:focus,
.post-navigation .nav-next a:hover { background-color: rgba(0, 0, 0, 0.4); }
';
}
wp_add_inline_style( 'shoreditch-style', $css );
}
add_action( 'wp_enqueue_scripts', 'shoreditch_post_nav_background' );
```
How can I remove those background images while using my child theme functions.php file, without modifying the actual file in parent theme?
|
You need to add:
```
'supports' => array('title', 'editor','page-attributes','thumbnail')
```
add this to your array after 'singular name' => 'pictures'.
The thumbnail adds the featured image option to your post type.
You can access the post type archive: yoursite/archive-pictures, this will use your themes archive.php file if it exists.
Or you can create a custom post type archive template with a custom loop: archive-pictures.php.
Or you can create a custom page template and apply it to a page.
Both the post-type archive and custom page template would contain similar code: a custom post type loop like this:
```
$args = array( 'post_type' => 'pictures', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
echo '<div class="entry-content">';
the_content();
the_post_thumbnail("medium");
echo '</div>';
endwhile;
```
|
226,848 |
<p>I've coded a plugin that creates a shortcode, among other things. That shortcode expects a post_id parameter, it extracts the content of that post and it returns the filtered content of that post (e.g. it applies all filters so that any other shortcode in that content is done).
Here is a cut down version of the code:</p>
<pre><code>public static function myshortcode($atts = null, $content = "")
{
global $wp_filter, $merged_filters, $wp_current_filter, $post;
if (is_array($atts))
extract($atts, EXTR_OVERWRITE);
$save_wp_filter = $wp_filter;
$save_merged_filters = $merged_filters;
$save_wp_current_filter = $wp_current_filter;
$post = get_post($post_id);
setup_postdata($post);
$content = $post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
$wp_filter = $save_wp_filter;
$merged_filters = $save_merged_filters;
$wp_current_filter = $save_wp_current_filter;
return $content;
}
</code></pre>
<p>All works great, except that other plugins shortcodes fail to include their own CSS files (e.g. Ultimate Addons for Visual Composer has its own CSS files to include, but it does not include them when called this way).
I suspect the problem is that when WP executes the "the_content" hook for my shortcode (not the one I call explicitly, but the hook that WP itself calls in the first place and that leads to my shortcode execution) it is already too late to include CSS files in the page (e.g. the <head> tag is already closed), and Wordpress, at that point, has given a chance to include CSS files only to the plugins it sees as needed for the page (e.g. only my plugin, because the page initially contains only my shortcode).</p>
<p>I could use wp_enqueue_style to explicitly add the required third party CSS files, but the problem is I want to include them in a portable way. Today the problem is Ultimate Addons for VC, tomorrow will be Content Egg or something else. The best solution would be to call the function of WP which makes the decision about what are the required plugins for the page and calls them, handing that function the the actual content the page will have after my shortcode will be executed, instead of the content the page has before my shortcode is done.</p>
<p>Does such WP function exist?</p>
<p>EDIT:</p>
<p>For clarification after comments, yes, my shortcode is like [embed_page id="123"], except I need it the other way around, e.g. [embed_post id="123"] in a page. There's no risk of looping because it is meant to be used only to embed posts into pages, and it's not meant to be used in posts. And finally yes, the embedded content does include other third party shortcodes that should automatically enqueue their own CSS, JS, whatever.</p>
<p>EDIT AFTER THE RECEIVED ANSWERS:</p>
<p>The short answer is no, there doesn't exist such function in Wordpress. The long answer is below. I'd like to reward both @majick and @cjbj for their extensive and detailed answers, but I have to choose one...</p>
|
[
{
"answer_id": 227318,
"author": "Nefro",
"author_id": 86801,
"author_profile": "https://wordpress.stackexchange.com/users/86801",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li><p>Load visual compose css </p>\n\n<pre><code>function get_visual_composer_style($id) {\n return '<style>' . get_post_meta( $id, '_wpb_shortcodes_custom_css', true ) . '</style>';\n}\n</code></pre></li>\n<li><p>Load css based on shortcode</p>\n\n<pre><code>function custom_shortcode_scripts() {\n global $post;\n if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'custom-shortcode') ) {\n wp_enqueue_script( 'custom-script');\n }\n}\nadd_action( 'wp_enqueue_scripts', 'custom_shortcode_scripts');\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 227320,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>This may be a silly idea, but it might work:</p>\n\n<p>1 Let your shortcode explode to an <code>iframe</code> with a custom <code>query_var</code> (<a href=\"http://www.rlmseo.com/blog/passing-get-query-string-parameters-in-wordpress-url/\" rel=\"nofollow\">tutorial</a>). Like this:</p>\n\n<pre><code><iframe src=\"http://www.example.com/?p=123&my_query_var=content_only\"></iframe>\n</code></pre>\n\n<p>2 In your <code>single.php</code> detect the <code>query_var</code> and in that case skip visual header, sidebars, footer - anything not connected to the post content itself.</p>\n\n<p>In this way you load the post in the usual way and avoid all problems with other shortcodes not completely doing what they should do.</p>\n\n<p>EDIT - CLARIFICATION AFTER COMMENTS</p>\n\n<p>The philosophy behind this approach is that you have no idea what third party plugins do, perhaps even independent of the shortcode execution. So, if you try to catch what the shortcode does, you may still miss things. For instance, a shortcode may lead to the generation of <code>html</code> and the inclusion of a <code>css</code> file, but the plugin may also add a <code>body_class</code> upon which the <code>css</code> depends. There is no way of knowing. So, to make sure that the external plugin/shortcode behaves as expected, the best way is to have WP do a full page load. Hence the <code>iframe</code>.</p>\n\n<p>Now, this leaves you with the problem that you get a full page, including header, menu, sidebars and so on. So, you need a template that only runs <code>the_title()</code> and <code>the_content()</code> and maybe other parts of the post. In some way you have to tell WP that you don't want this. WP must know if it is supposed to generate a normal <code>single.php</code> or a bare bones one. This is where the <code>query_var</code> comes in. By adding it to the url as generated in your shortcode, you give WP a clue that this is not a normal call to <code>single.php</code>. This is still relatively easy, because you can set up a custom <code>query_var</code> with just a few lines of code.</p>\n\n<p>Things become complicated if you want your shortcode in a plugin, because then you also don't know what the theme does. You will have to overrule the theme and have to insert your bare bones <code>single.php</code>. Since you don't know how the theme is built, you won't be sure if the post has the same format as in the theme. You could also have your plugin analyse <code>single.php</code> and remove undesired elements, but that is a wild guess. Also there may be custom templates like <code>single-custompage.php</code>. So if you follow this path, it may be best to include an option page that lets users set the styles of posts that are included in pages.</p>\n"
},
{
"answer_id": 227386,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 3,
"selected": true,
"text": "<p>I think you could get around this by pre-running the shortcodes on the page by applying the content filters before the header is output. This should allow any internal shortcodes run inside the included post to add any action hooks properly and thus any needed stylesheets/resources.</p>\n\n<pre><code>add_action('wp_loaded','maybe_prerun_shortcodes');\nfunction maybe_prerun_shortcodes() {\n if (is_page()) {\n global $post; \n if (has_shortcode($post->post_content,'embed_post')) {\n $content = apply_filters('the_content',$post->post_content);\n }\n }\n}\n</code></pre>\n\n<p><strong>EDIT</strong> The above will only enqueue stylesheets and resources that are enqueued <em>within</em> any shortcode calls in the embedded post (which, although it is better practice, is actually not done very often.) It should work for those cases because applying the filters to the current page content will run the embed shortcode which then applies filters for the embedded post (in your existing function.)</p>\n\n<p>However, To get the stylesheets for a particular post you would have to fetch that particular post (which is why the iframe method works, well kind of, given the problems already discussed about that.) </p>\n\n<p>My suggested workaround in that case is to store the style resources loaded on a post when the post is loaded...</p>\n\n<pre><code>add_filter('style_loader_tag','custom_store_style_tags',11,2)\nfunction custom_store_style_tags($tag,$handle) {\n global $styletags; $styletags[$handle] = $tag;}\n}\n\nadd_action('wp_footer','custom_save_style_tags');\nfunction custom_save_style_tags() {\n global $embedstyles;\n if (is_single()) {\n global $styletags, $post; \n update_post_meta($post->ID,'styletags',$styletags);\n } elseif (is_array($embedstyles)) {\n global $styletags;\n foreach ($embedstyles as $handle => $tag) {\n if (!array_key_exists($handle,$styletags)) {echo $tag;}\n }\n }\n}\n</code></pre>\n\n<p>Then you can use the shortcode to retrieve the style tags to be retrieved and the second part of the above function will output them in the footer:</p>\n\n<pre><code>public static function myshortcode($atts = null, $content = \"\")\n{\n // EXISTING CODE SNIPPED\n\n global $embedstyles;\n $embedstyle = get_post_meta($post_id,'styletags',true);\n if (is_array($embedstyle)) {\n if (!is_array($embedstyles)) {$embedstyles = array();}\n $embedstyles = array_merge($embedstyle,$embedstyles);\n }\n\n return $content;\n}\n</code></pre>\n\n<p>And you could do the same for scripts via <code>script_loader_tag</code> filter and simply changing the variables to match...</p>\n\n<p>Of course there is still the possibility some <code>body</code> classes may not be targeted by styles as already mentioned by @cjbj... or some scripts may initialize in the footer even if they are enqueued properly.</p>\n\n<p>...and it does not account for inline styles/scripts printed (not enqueued) on the page yet... but it's a good start... depends how far you want to go with it.</p>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226848",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84622/"
] |
I've coded a plugin that creates a shortcode, among other things. That shortcode expects a post\_id parameter, it extracts the content of that post and it returns the filtered content of that post (e.g. it applies all filters so that any other shortcode in that content is done).
Here is a cut down version of the code:
```
public static function myshortcode($atts = null, $content = "")
{
global $wp_filter, $merged_filters, $wp_current_filter, $post;
if (is_array($atts))
extract($atts, EXTR_OVERWRITE);
$save_wp_filter = $wp_filter;
$save_merged_filters = $merged_filters;
$save_wp_current_filter = $wp_current_filter;
$post = get_post($post_id);
setup_postdata($post);
$content = $post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
$wp_filter = $save_wp_filter;
$merged_filters = $save_merged_filters;
$wp_current_filter = $save_wp_current_filter;
return $content;
}
```
All works great, except that other plugins shortcodes fail to include their own CSS files (e.g. Ultimate Addons for Visual Composer has its own CSS files to include, but it does not include them when called this way).
I suspect the problem is that when WP executes the "the\_content" hook for my shortcode (not the one I call explicitly, but the hook that WP itself calls in the first place and that leads to my shortcode execution) it is already too late to include CSS files in the page (e.g. the <head> tag is already closed), and Wordpress, at that point, has given a chance to include CSS files only to the plugins it sees as needed for the page (e.g. only my plugin, because the page initially contains only my shortcode).
I could use wp\_enqueue\_style to explicitly add the required third party CSS files, but the problem is I want to include them in a portable way. Today the problem is Ultimate Addons for VC, tomorrow will be Content Egg or something else. The best solution would be to call the function of WP which makes the decision about what are the required plugins for the page and calls them, handing that function the the actual content the page will have after my shortcode will be executed, instead of the content the page has before my shortcode is done.
Does such WP function exist?
EDIT:
For clarification after comments, yes, my shortcode is like [embed\_page id="123"], except I need it the other way around, e.g. [embed\_post id="123"] in a page. There's no risk of looping because it is meant to be used only to embed posts into pages, and it's not meant to be used in posts. And finally yes, the embedded content does include other third party shortcodes that should automatically enqueue their own CSS, JS, whatever.
EDIT AFTER THE RECEIVED ANSWERS:
The short answer is no, there doesn't exist such function in Wordpress. The long answer is below. I'd like to reward both @majick and @cjbj for their extensive and detailed answers, but I have to choose one...
|
I think you could get around this by pre-running the shortcodes on the page by applying the content filters before the header is output. This should allow any internal shortcodes run inside the included post to add any action hooks properly and thus any needed stylesheets/resources.
```
add_action('wp_loaded','maybe_prerun_shortcodes');
function maybe_prerun_shortcodes() {
if (is_page()) {
global $post;
if (has_shortcode($post->post_content,'embed_post')) {
$content = apply_filters('the_content',$post->post_content);
}
}
}
```
**EDIT** The above will only enqueue stylesheets and resources that are enqueued *within* any shortcode calls in the embedded post (which, although it is better practice, is actually not done very often.) It should work for those cases because applying the filters to the current page content will run the embed shortcode which then applies filters for the embedded post (in your existing function.)
However, To get the stylesheets for a particular post you would have to fetch that particular post (which is why the iframe method works, well kind of, given the problems already discussed about that.)
My suggested workaround in that case is to store the style resources loaded on a post when the post is loaded...
```
add_filter('style_loader_tag','custom_store_style_tags',11,2)
function custom_store_style_tags($tag,$handle) {
global $styletags; $styletags[$handle] = $tag;}
}
add_action('wp_footer','custom_save_style_tags');
function custom_save_style_tags() {
global $embedstyles;
if (is_single()) {
global $styletags, $post;
update_post_meta($post->ID,'styletags',$styletags);
} elseif (is_array($embedstyles)) {
global $styletags;
foreach ($embedstyles as $handle => $tag) {
if (!array_key_exists($handle,$styletags)) {echo $tag;}
}
}
}
```
Then you can use the shortcode to retrieve the style tags to be retrieved and the second part of the above function will output them in the footer:
```
public static function myshortcode($atts = null, $content = "")
{
// EXISTING CODE SNIPPED
global $embedstyles;
$embedstyle = get_post_meta($post_id,'styletags',true);
if (is_array($embedstyle)) {
if (!is_array($embedstyles)) {$embedstyles = array();}
$embedstyles = array_merge($embedstyle,$embedstyles);
}
return $content;
}
```
And you could do the same for scripts via `script_loader_tag` filter and simply changing the variables to match...
Of course there is still the possibility some `body` classes may not be targeted by styles as already mentioned by @cjbj... or some scripts may initialize in the footer even if they are enqueued properly.
...and it does not account for inline styles/scripts printed (not enqueued) on the page yet... but it's a good start... depends how far you want to go with it.
|
226,850 |
<p>How do I build goodlooking, custom pages into my themes. I've decided to use underscores to create custom client themes, as I need complete freedom in design, and all the tutorials I've found on theme development seem to just show how to build blog style websites, but I'd like to build sites with multi column layouts, icons, call-to-actions, a home slider.. basically mostly static content, but parts of the website where the client can add a gallery.. maybe a calendar, post updates, add slides to a slider ect.</p>
<p>Should I just throw the static html into a template file and then enqueue the css and scripts for it, and then add widgetized areas where needed? I would really appreciate anyone's help, and maybe links to reading material / tutorials on the topic? I've done a lot of research, but am still pretty lost...</p>
|
[
{
"answer_id": 226851,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>Why not build a blog style website first? If you're new to WordPress, it's better to start with something relatively easy, where there are lots of tutorials for. Practicing will give you the skills to reach for something higher, like the list of ambitions you give.</p>\n\n<p>If you need all those things you say right now, you're better of with buying a decent framework theme, that has all the elements you need. Really, it will only frustrate you if you try to build a complex theme from scratch without some easy and intermediate practice first.</p>\n"
},
{
"answer_id": 227219,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 0,
"selected": false,
"text": "<p>If you're already experienced with HTML & CSS, then I'd suggest starting by building pages the way you'd like them and then looking at <a href=\"https://codex.wordpress.org/Template_Tags\" rel=\"nofollow\">https://codex.wordpress.org/Template_Tags</a> to see how you can replace key sections of the pages dynamically from WordPress.</p>\n"
},
{
"answer_id": 227998,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 1,
"selected": false,
"text": "<h2>Static pages: Valid?</h2>\n\n<p>Yes. You absolutely can add static pages that have nothing to do with a blog aside from using WordPress \"routing\" API out of the box and the database.</p>\n\n<h2>Styles, Script: How?</h2>\n\n<p>Simply add your custom styles and scripts to your theme. Then <a href=\"https://developer.wordpress.org/themes/basics/including-css-javascript/\" rel=\"nofollow noreferrer\">register and enqueue them</a>. You can add your own <a href=\"https://codex.wordpress.org/Theme_Development#Template_Files\" rel=\"nofollow noreferrer\">Page Templates</a>. Since WP 3.4 the actual page template files can get collected in a themes <em>sub directory</em> for better organization. Just add a template comment and make them available:</p>\n\n<pre><code><?php\n/** Template Name: Landing Page for Small Business */\n\n// Optional: Use a custom header\nget_header( 'customheader' );\n// Rest of your static page template code\n</code></pre>\n\n<p>When you then add a new page, the new template will appear in your \"Page Attributes\" meta box and will look close to the following:</p>\n\n<p><a href=\"https://i.stack.imgur.com/9nOVI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9nOVI.png\" alt=\"enter image description here\"></a></p>\n\n<h2>Author Options: How?</h2>\n\n<p>Pages are, like nav menu entries and other things, just a plain post (in the database) with a different <code>post_type</code>. That means that you can add meta boxes like you would for every other (custom) post type as well. Just <a href=\"https://wordpress.stackexchange.com/search?q=add+meta+box\">add a new meta box</a>, then save the <a href=\"https://wordpress.stackexchange.com/search?q=save+post+meta\">new post meta data</a>. You can even <a href=\"https://wordpress.stackexchange.com/a/43406/385\">remove the default editor</a>. Finally just fetch your saved post meta data in your template. You can dump all your posts custom data using <a href=\"https://developer.wordpress.org/reference/functions/get_post_custom/\" rel=\"nofollow noreferrer\"><code>get_post_custom( get_the_ID() );</code></a> in the loop in your custom page template:</p>\n\n<pre><code><?php\n/** Template Name: Landing Page for Small Business */\nget_header( 'specialheader' );\n// The Loop:\nif ( have_posts() )\n{\n while ( have_posts )\n {\n the_post();\n\n the_title();\n // All your post meta data:\n var_dump( get_post_custom( get_the_ID() ) );\n }\n}\n</code></pre>\n\n<p>The rest is up to you and your imagination. Build a user interface for slider customization into your meta box, make selects, radio buttons or whatever other form elements and options you can come up with.</p>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94157/"
] |
How do I build goodlooking, custom pages into my themes. I've decided to use underscores to create custom client themes, as I need complete freedom in design, and all the tutorials I've found on theme development seem to just show how to build blog style websites, but I'd like to build sites with multi column layouts, icons, call-to-actions, a home slider.. basically mostly static content, but parts of the website where the client can add a gallery.. maybe a calendar, post updates, add slides to a slider ect.
Should I just throw the static html into a template file and then enqueue the css and scripts for it, and then add widgetized areas where needed? I would really appreciate anyone's help, and maybe links to reading material / tutorials on the topic? I've done a lot of research, but am still pretty lost...
|
Static pages: Valid?
--------------------
Yes. You absolutely can add static pages that have nothing to do with a blog aside from using WordPress "routing" API out of the box and the database.
Styles, Script: How?
--------------------
Simply add your custom styles and scripts to your theme. Then [register and enqueue them](https://developer.wordpress.org/themes/basics/including-css-javascript/). You can add your own [Page Templates](https://codex.wordpress.org/Theme_Development#Template_Files). Since WP 3.4 the actual page template files can get collected in a themes *sub directory* for better organization. Just add a template comment and make them available:
```
<?php
/** Template Name: Landing Page for Small Business */
// Optional: Use a custom header
get_header( 'customheader' );
// Rest of your static page template code
```
When you then add a new page, the new template will appear in your "Page Attributes" meta box and will look close to the following:
[](https://i.stack.imgur.com/9nOVI.png)
Author Options: How?
--------------------
Pages are, like nav menu entries and other things, just a plain post (in the database) with a different `post_type`. That means that you can add meta boxes like you would for every other (custom) post type as well. Just [add a new meta box](https://wordpress.stackexchange.com/search?q=add+meta+box), then save the [new post meta data](https://wordpress.stackexchange.com/search?q=save+post+meta). You can even [remove the default editor](https://wordpress.stackexchange.com/a/43406/385). Finally just fetch your saved post meta data in your template. You can dump all your posts custom data using [`get_post_custom( get_the_ID() );`](https://developer.wordpress.org/reference/functions/get_post_custom/) in the loop in your custom page template:
```
<?php
/** Template Name: Landing Page for Small Business */
get_header( 'specialheader' );
// The Loop:
if ( have_posts() )
{
while ( have_posts )
{
the_post();
the_title();
// All your post meta data:
var_dump( get_post_custom( get_the_ID() ) );
}
}
```
The rest is up to you and your imagination. Build a user interface for slider customization into your meta box, make selects, radio buttons or whatever other form elements and options you can come up with.
|
226,859 |
<p>We are using the Divi theme for our Wordpress site, we have also activated a Child Theme that we have named our SEO keyword.</p>
<p>However, when you look in the "View Source" and Theme Sniffer Chrome Extensions the Divi theme is still visible.</p>
<pre><code> <link rel='stylesheet' id='parent-style-css' href="http://example.com/wp-content/themes/Divi/style.css?ver=ad89301g28d6b0c3f6d525d4e252b7a7' type='text/css' media='all' />
<link rel='stylesheet' id='child-style-css' href='http://example.com/wp-content/themes/aire-valley-business-centre/style.css?ver=ad89355d28d6b0c3f6d525d4e252b7a7' type='text/css' media='all' />
</code></pre>
<p>How can i rename the Divi theme so no-one knows this theme is being used whilst still maintaining the ability to update the theme easily?</p>
|
[
{
"answer_id": 226863,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>You would have to rename the directory of the Divi theme. However, this could break the theme if there are components that depend on the directory being named Divi. Also, there may be copyright issues.</p>\n"
},
{
"answer_id": 226866,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<p>You'll be unable to automatically update the parent Divi theme when it's directory becomes renamed.</p>\n\n<p>You can use any of cachingβ plugins with <code>CSS minify</code> or/and <code>CSS combine</code> turned <code>ON</code>. This way everybody will see <code>/cache</code> directory instead of the actual theme directory.</p>\n\n<p>Or as the alternative, you can update renamed parent theme manually, directory by directory, file by file.</p>\n\n<p>BTW, there is no any connection between SEO and the theme name.</p>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226859",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93747/"
] |
We are using the Divi theme for our Wordpress site, we have also activated a Child Theme that we have named our SEO keyword.
However, when you look in the "View Source" and Theme Sniffer Chrome Extensions the Divi theme is still visible.
```
<link rel='stylesheet' id='parent-style-css' href="http://example.com/wp-content/themes/Divi/style.css?ver=ad89301g28d6b0c3f6d525d4e252b7a7' type='text/css' media='all' />
<link rel='stylesheet' id='child-style-css' href='http://example.com/wp-content/themes/aire-valley-business-centre/style.css?ver=ad89355d28d6b0c3f6d525d4e252b7a7' type='text/css' media='all' />
```
How can i rename the Divi theme so no-one knows this theme is being used whilst still maintaining the ability to update the theme easily?
|
You'll be unable to automatically update the parent Divi theme when it's directory becomes renamed.
You can use any of cachingβ plugins with `CSS minify` or/and `CSS combine` turned `ON`. This way everybody will see `/cache` directory instead of the actual theme directory.
Or as the alternative, you can update renamed parent theme manually, directory by directory, file by file.
BTW, there is no any connection between SEO and the theme name.
|
226,861 |
<p>I`m using my own page template, for display post from some category:</p>
<pre><code>$wp_query = new WP_Query();
$wp_query->query('&cat=9' . '&paged=' . $paged);
while ($wp_query->have_posts()) :
$wp_query->the_post(); ?>
<div class="post-list">
<div class="post-list-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
<div class="short-text">
<?php the_content('More >>'); ?>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
</code></pre>
<p>But when i create password for this page, content of the page are shown. I need to create password protection only for this page, and when i enter pass, all post from this page are shown.</p>
|
[
{
"answer_id": 226865,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 3,
"selected": true,
"text": "<p>This is because password protection applied on <code>get_the_content()</code> function. And you are not using it instead you've written your own custom loop.</p>\n\n<p>So you can alter the code before loop and check if page is not password protected using function <a href=\"https://codex.wordpress.org/Function_Reference/post_password_required\" rel=\"nofollow\"><code>post_password_required()</code></a> and then display form using <a href=\"https://developer.wordpress.org/reference/functions/get_the_password_form/\" rel=\"nofollow\"><code>get_the_password_form()</code></a> else display loop.</p>\n\n<p>Example:-</p>\n\n<pre><code>if ( post_password_required( get_the_ID() ) ) {\n echo get_the_password_form( get_the_ID() );\n} else {\n $wp_query = new WP_Query();\n $wp_query->query('&cat=9' . '&paged=' . $paged);\n while ($wp_query->have_posts()) :\n $wp_query->the_post(); ?>\n <div class=\"post-list\">\n <div class=\"post-list-title\"><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></div>\n\n <div class=\"short-text\">\n <?php the_content('More >>'); ?>\n </div>\n </div>\n <?php endwhile; ?>\n <?php wp_reset_postdata();\n}\n</code></pre>\n"
},
{
"answer_id": 226868,
"author": "AR Bhatti",
"author_id": 94177,
"author_profile": "https://wordpress.stackexchange.com/users/94177",
"pm_score": -1,
"selected": false,
"text": "<pre><code><?php global $post;\n\nif ( post_password_required( $post ) ) {\n echo get_the_password_form( $post );\n} else {\n $wp_query_pass = new WP_Query('&cat=9' . '&paged=' . $paged);\n while ($wp_query_pass->have_posts()) :\n $wp_query_pass->the_post(); ?>\n <div class=\"post-list\">\n <div class=\"post-list-title\"><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></div>\n\n <div class=\"short-text\">\n <?php the_content('Next >>'); ?>\n </div>\n </div>\n <?php endwhile; ?>\n <?php wp_reset_postdata();\n}\n</code></pre>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226861",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83974/"
] |
I`m using my own page template, for display post from some category:
```
$wp_query = new WP_Query();
$wp_query->query('&cat=9' . '&paged=' . $paged);
while ($wp_query->have_posts()) :
$wp_query->the_post(); ?>
<div class="post-list">
<div class="post-list-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
<div class="short-text">
<?php the_content('More >>'); ?>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
```
But when i create password for this page, content of the page are shown. I need to create password protection only for this page, and when i enter pass, all post from this page are shown.
|
This is because password protection applied on `get_the_content()` function. And you are not using it instead you've written your own custom loop.
So you can alter the code before loop and check if page is not password protected using function [`post_password_required()`](https://codex.wordpress.org/Function_Reference/post_password_required) and then display form using [`get_the_password_form()`](https://developer.wordpress.org/reference/functions/get_the_password_form/) else display loop.
Example:-
```
if ( post_password_required( get_the_ID() ) ) {
echo get_the_password_form( get_the_ID() );
} else {
$wp_query = new WP_Query();
$wp_query->query('&cat=9' . '&paged=' . $paged);
while ($wp_query->have_posts()) :
$wp_query->the_post(); ?>
<div class="post-list">
<div class="post-list-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
<div class="short-text">
<?php the_content('More >>'); ?>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_postdata();
}
```
|
226,862 |
<p>I have the code below on my homepage to list posts from a specific category, then a second piece to list posts from across the site. </p>
<p>The problem I'm having is that there is some sort of weirdness going on, where I can't scroll to the bottom of the page. When I reach the bottom the page instantly jumps up. </p>
<p>This behaviour happens in safari, but also FF, however in the latter it only happens when the web developer tools are open. </p>
<p>First list</p>
<pre><code><ul>
<?php
global $post;
$tmp_post = $post;
$args = array( 'numberposts' => 3, //'offset'=> 1,
'category' => 67 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<li>
<article class="front-page-summary">
<a href="<?php the_permalink(); ?>">
<?php echo the_post_thumbnail('homepage-thumb'); ?>
<div class="post-details-wrapper">
<h3><?php the_title(); ?></h3>
<?php the_excerpt(); ?>
</div>
</a>
</article>
</li>
<?php endforeach; ?>
<?php $post = $tmp_post; ?>
</ul>
</code></pre>
<p>Second list</p>
<pre><code><h2>Latest Posts</h2><hr class="section-divider">
<span class="subheading">My latest thoughts on travel, gear, and everything else</span>
<?php
global $post;
$tmp_post = $post;
$args = array( 'numberposts' => 3);
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<div class="latest-post-list">
<span class="meta"><?php the_date(); ?></span> / <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> / <span class="meta"><?php the_category(', '); ?></span>
</div>
<?php endforeach; ?>
<?php $post = $tmp_post; ?>
<div class="clear"></div>
</code></pre>
<p>The problem does not occur if I remove the 'first list' code, which leads me to believe that there is an error there. Can you see it?</p>
|
[
{
"answer_id": 226867,
"author": "AR Bhatti",
"author_id": 94177,
"author_profile": "https://wordpress.stackexchange.com/users/94177",
"pm_score": -1,
"selected": false,
"text": "<p>Use <code>wp_reset_query();</code> in the end of the loop </p>\n"
},
{
"answer_id": 226877,
"author": "Mikedefieslife",
"author_id": 68272,
"author_profile": "https://wordpress.stackexchange.com/users/68272",
"pm_score": 0,
"selected": false,
"text": "<p>It was Stellar parallax. Here is the offending code: </p>\n\n<p><code>// Stellar parallax var $ = jQuery.noConflict(); $(function(){ $.stellar({ horizontalScrolling: false, verticalOffset: 40 }); });</code></p>\n\n<p>I now need to go away and figure out what in this code was giving me the problem. </p>\n\n<p>Thanks for the prompts of where to look. </p>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226862",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68272/"
] |
I have the code below on my homepage to list posts from a specific category, then a second piece to list posts from across the site.
The problem I'm having is that there is some sort of weirdness going on, where I can't scroll to the bottom of the page. When I reach the bottom the page instantly jumps up.
This behaviour happens in safari, but also FF, however in the latter it only happens when the web developer tools are open.
First list
```
<ul>
<?php
global $post;
$tmp_post = $post;
$args = array( 'numberposts' => 3, //'offset'=> 1,
'category' => 67 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<li>
<article class="front-page-summary">
<a href="<?php the_permalink(); ?>">
<?php echo the_post_thumbnail('homepage-thumb'); ?>
<div class="post-details-wrapper">
<h3><?php the_title(); ?></h3>
<?php the_excerpt(); ?>
</div>
</a>
</article>
</li>
<?php endforeach; ?>
<?php $post = $tmp_post; ?>
</ul>
```
Second list
```
<h2>Latest Posts</h2><hr class="section-divider">
<span class="subheading">My latest thoughts on travel, gear, and everything else</span>
<?php
global $post;
$tmp_post = $post;
$args = array( 'numberposts' => 3);
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<div class="latest-post-list">
<span class="meta"><?php the_date(); ?></span> / <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> / <span class="meta"><?php the_category(', '); ?></span>
</div>
<?php endforeach; ?>
<?php $post = $tmp_post; ?>
<div class="clear"></div>
```
The problem does not occur if I remove the 'first list' code, which leads me to believe that there is an error there. Can you see it?
|
It was Stellar parallax. Here is the offending code:
`// Stellar parallax var $ = jQuery.noConflict(); $(function(){ $.stellar({ horizontalScrolling: false, verticalOffset: 40 }); });`
I now need to go away and figure out what in this code was giving me the problem.
Thanks for the prompts of where to look.
|
226,884 |
<p>I want to add <code>javascript:void(0);</code> to menu link item instead of <code>#</code> but it is not accepting any JavaScript.
Now i am thing to replace <code>#</code> with <code>javascript:void(0);</code> using filters, but could not find the appropriate filter for the task.</p>
<p>Can any one tell me which filter can be used for this task.</p>
<p>Note. I know this could be done with javascript/jQuery but this is for SEO purposes so have to do it with PHP on server side and render the correct html for google Spider, to avoid duplicate URL issue.</p>
|
[
{
"answer_id": 226920,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>I am not sure how it does effect the SEO but just to answer this\n question:-</p>\n</blockquote>\n\n<p>You can not save menu item with <code>javascript:void(0);</code> because WordPress filter the URL using function <a href=\"https://codex.wordpress.org/Function_Reference/esc_url\" rel=\"noreferrer\"><code>esc_url()</code></a> thus removing bad values. And it all happens in Nav Walker class. So you need to alter the URL when WordPress done with filtering and returning final safe HTML.</p>\n\n<p>You can use filter <code>walker_nav_menu_start_el</code> if your theme does not have custom nav menu walker class OR does have this filter in walker class.</p>\n\n<p>Example:-</p>\n\n<pre><code>add_filter('walker_nav_menu_start_el', 'wpse_226884_replace_hash', 999);\n/**\n * Replace # with js\n * @param string $menu_item item HTML\n * @return string item HTML\n */\nfunction wpse_226884_replace_hash($menu_item) {\n if (strpos($menu_item, 'href=\"#\"') !== false) {\n $menu_item = str_replace('href=\"#\"', 'href=\"javascript:void(0);\"', $menu_item);\n }\n return $menu_item;\n}\n</code></pre>\n"
},
{
"answer_id": 226948,
"author": "Deepti chipdey",
"author_id": 94146,
"author_profile": "https://wordpress.stackexchange.com/users/94146",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Simple Method</strong> </p>\n\n<p>First thing you need to do is add a new menu item in your menu. You can do that by going to Appearance Β» Menus. You want to add a custom link so give it the label you want. In the URL field, enter the # sign. Once done, click on the Add to Menu button. Save your menu once this custom link is added to the menu.\nAdding a custom link to the menu without URL</p>\n\n<p>Now click on the drop down arrow next to this custom link to edit this menu item. Go ahead and remove the pound sign from the URL field and save your menu. If you go to your live website, then you will see a menu item without link. You can add sub menus to this menu item and link them to any page or custom link you want.\nRemoving # sign and creating a menu without any link.</p>\n\n<p>check this link for more detail.</p>\n\n<p><a href=\"http://www.wpbeginner.com/beginners-guide/how-to-add-titles-in-wordpress-menu-without-linking-to-a-page/\" rel=\"nofollow\">http://www.wpbeginner.com/beginners-guide/how-to-add-titles-in-wordpress-menu-without-linking-to-a-page/</a></p>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226884",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76325/"
] |
I want to add `javascript:void(0);` to menu link item instead of `#` but it is not accepting any JavaScript.
Now i am thing to replace `#` with `javascript:void(0);` using filters, but could not find the appropriate filter for the task.
Can any one tell me which filter can be used for this task.
Note. I know this could be done with javascript/jQuery but this is for SEO purposes so have to do it with PHP on server side and render the correct html for google Spider, to avoid duplicate URL issue.
|
>
> I am not sure how it does effect the SEO but just to answer this
> question:-
>
>
>
You can not save menu item with `javascript:void(0);` because WordPress filter the URL using function [`esc_url()`](https://codex.wordpress.org/Function_Reference/esc_url) thus removing bad values. And it all happens in Nav Walker class. So you need to alter the URL when WordPress done with filtering and returning final safe HTML.
You can use filter `walker_nav_menu_start_el` if your theme does not have custom nav menu walker class OR does have this filter in walker class.
Example:-
```
add_filter('walker_nav_menu_start_el', 'wpse_226884_replace_hash', 999);
/**
* Replace # with js
* @param string $menu_item item HTML
* @return string item HTML
*/
function wpse_226884_replace_hash($menu_item) {
if (strpos($menu_item, 'href="#"') !== false) {
$menu_item = str_replace('href="#"', 'href="javascript:void(0);"', $menu_item);
}
return $menu_item;
}
```
|
226,889 |
<p>I am working on a site for a client and am using a plugin that adds an "<strong>event</strong>" custom post type and an "<strong>event-category</strong>" taxonomy.</p>
<p>I have also attached the "event-category" taxonomy to the default Wordpress "post" post type using the <strong>register_taxonomy_for_object_type</strong> function.</p>
<p>Now I have the following working URL scheme:</p>
<ul>
<li>Post are accessed using the URL structure
<strong>site-name.com/article/post-slug</strong></li>
<li>Events are accesed using the URL
structure <strong>site-name.com/event/event-slug</strong></li>
<li>Event category term archives
have the URL structure <strong>site-name.com/events/event-category-slug</strong></li>
</ul>
<p>I made the event category term archives display only events by using a <strong>pre_get_posts</strong> action with the following code:</p>
<pre><code>if (!$query->is_admin() && $query->is_main_query() && is_tax('event-category')) {
$query->set('post_type', 'event');
}
</code></pre>
<p>My problem is that I want to also have category archive pages that show only posts.</p>
<p>If possible these would ideally be accessed with the URL <strong>site-name.com/articles/event-category-slug</strong></p>
<p>But if that's not possible it would be OK to have a different URL, as long as it leads to a page listing just posts in that particular event category.</p>
<p>Any help with the rewrite rules needed to achieve this would be greatly appreciated.
I've found some articles that describe similar problems but I haven't been able to make them work for me.</p>
|
[
{
"answer_id": 226920,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>I am not sure how it does effect the SEO but just to answer this\n question:-</p>\n</blockquote>\n\n<p>You can not save menu item with <code>javascript:void(0);</code> because WordPress filter the URL using function <a href=\"https://codex.wordpress.org/Function_Reference/esc_url\" rel=\"noreferrer\"><code>esc_url()</code></a> thus removing bad values. And it all happens in Nav Walker class. So you need to alter the URL when WordPress done with filtering and returning final safe HTML.</p>\n\n<p>You can use filter <code>walker_nav_menu_start_el</code> if your theme does not have custom nav menu walker class OR does have this filter in walker class.</p>\n\n<p>Example:-</p>\n\n<pre><code>add_filter('walker_nav_menu_start_el', 'wpse_226884_replace_hash', 999);\n/**\n * Replace # with js\n * @param string $menu_item item HTML\n * @return string item HTML\n */\nfunction wpse_226884_replace_hash($menu_item) {\n if (strpos($menu_item, 'href=\"#\"') !== false) {\n $menu_item = str_replace('href=\"#\"', 'href=\"javascript:void(0);\"', $menu_item);\n }\n return $menu_item;\n}\n</code></pre>\n"
},
{
"answer_id": 226948,
"author": "Deepti chipdey",
"author_id": 94146,
"author_profile": "https://wordpress.stackexchange.com/users/94146",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Simple Method</strong> </p>\n\n<p>First thing you need to do is add a new menu item in your menu. You can do that by going to Appearance Β» Menus. You want to add a custom link so give it the label you want. In the URL field, enter the # sign. Once done, click on the Add to Menu button. Save your menu once this custom link is added to the menu.\nAdding a custom link to the menu without URL</p>\n\n<p>Now click on the drop down arrow next to this custom link to edit this menu item. Go ahead and remove the pound sign from the URL field and save your menu. If you go to your live website, then you will see a menu item without link. You can add sub menus to this menu item and link them to any page or custom link you want.\nRemoving # sign and creating a menu without any link.</p>\n\n<p>check this link for more detail.</p>\n\n<p><a href=\"http://www.wpbeginner.com/beginners-guide/how-to-add-titles-in-wordpress-menu-without-linking-to-a-page/\" rel=\"nofollow\">http://www.wpbeginner.com/beginners-guide/how-to-add-titles-in-wordpress-menu-without-linking-to-a-page/</a></p>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226889",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8620/"
] |
I am working on a site for a client and am using a plugin that adds an "**event**" custom post type and an "**event-category**" taxonomy.
I have also attached the "event-category" taxonomy to the default Wordpress "post" post type using the **register\_taxonomy\_for\_object\_type** function.
Now I have the following working URL scheme:
* Post are accessed using the URL structure
**site-name.com/article/post-slug**
* Events are accesed using the URL
structure **site-name.com/event/event-slug**
* Event category term archives
have the URL structure **site-name.com/events/event-category-slug**
I made the event category term archives display only events by using a **pre\_get\_posts** action with the following code:
```
if (!$query->is_admin() && $query->is_main_query() && is_tax('event-category')) {
$query->set('post_type', 'event');
}
```
My problem is that I want to also have category archive pages that show only posts.
If possible these would ideally be accessed with the URL **site-name.com/articles/event-category-slug**
But if that's not possible it would be OK to have a different URL, as long as it leads to a page listing just posts in that particular event category.
Any help with the rewrite rules needed to achieve this would be greatly appreciated.
I've found some articles that describe similar problems but I haven't been able to make them work for me.
|
>
> I am not sure how it does effect the SEO but just to answer this
> question:-
>
>
>
You can not save menu item with `javascript:void(0);` because WordPress filter the URL using function [`esc_url()`](https://codex.wordpress.org/Function_Reference/esc_url) thus removing bad values. And it all happens in Nav Walker class. So you need to alter the URL when WordPress done with filtering and returning final safe HTML.
You can use filter `walker_nav_menu_start_el` if your theme does not have custom nav menu walker class OR does have this filter in walker class.
Example:-
```
add_filter('walker_nav_menu_start_el', 'wpse_226884_replace_hash', 999);
/**
* Replace # with js
* @param string $menu_item item HTML
* @return string item HTML
*/
function wpse_226884_replace_hash($menu_item) {
if (strpos($menu_item, 'href="#"') !== false) {
$menu_item = str_replace('href="#"', 'href="javascript:void(0);"', $menu_item);
}
return $menu_item;
}
```
|
226,891 |
<p>I need to save URL's from old site, in options-permalink in admin wordpress i use </p>
<pre><code>/blog/%category%/%postname%.html
</code></pre>
<p>I do it for blog posts. <strong>But i don't need to get it for CPT</strong></p>
<p>I have created CPT</p>
<pre><code>function uslugi_init() {
$args = array(
'label' => 'Π£ΡΠ»ΡΠ³ΠΈ',
'public' => true,
'show_ui' => true,
'capability_type' => 'page',
'hierarchical' => false,
'rewrite' => array('slug' => 'uslugi-i-czenyi'),
'query_var' => true,
'menu_icon' => 'dashicons-video-alt',
'supports' => array(
'title',
'editor',
'excerpt',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'thumbnail',
'author',
'page-attributes',)
);
register_post_type( 'uslugi', $args );
}
add_action( 'init', 'uslugi_init' );
</code></pre>
<p>BUT i have a big problem - my CPT url is</p>
<p><code>site.com/blog/uslugi-i-czenyi/test</code></p>
<p>but i need </p>
<p><code>site.com/uslugi-i-czenyi/test</code></p>
<p>Also i need to get templates from pages...</p>
<p>Is it fixable?</p>
<p><strong>How to separate CPT url from blog permalink?</strong></p>
<p>Help me, please!</p>
|
[
{
"answer_id": 226920,
"author": "Sumit",
"author_id": 32475,
"author_profile": "https://wordpress.stackexchange.com/users/32475",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>I am not sure how it does effect the SEO but just to answer this\n question:-</p>\n</blockquote>\n\n<p>You can not save menu item with <code>javascript:void(0);</code> because WordPress filter the URL using function <a href=\"https://codex.wordpress.org/Function_Reference/esc_url\" rel=\"noreferrer\"><code>esc_url()</code></a> thus removing bad values. And it all happens in Nav Walker class. So you need to alter the URL when WordPress done with filtering and returning final safe HTML.</p>\n\n<p>You can use filter <code>walker_nav_menu_start_el</code> if your theme does not have custom nav menu walker class OR does have this filter in walker class.</p>\n\n<p>Example:-</p>\n\n<pre><code>add_filter('walker_nav_menu_start_el', 'wpse_226884_replace_hash', 999);\n/**\n * Replace # with js\n * @param string $menu_item item HTML\n * @return string item HTML\n */\nfunction wpse_226884_replace_hash($menu_item) {\n if (strpos($menu_item, 'href=\"#\"') !== false) {\n $menu_item = str_replace('href=\"#\"', 'href=\"javascript:void(0);\"', $menu_item);\n }\n return $menu_item;\n}\n</code></pre>\n"
},
{
"answer_id": 226948,
"author": "Deepti chipdey",
"author_id": 94146,
"author_profile": "https://wordpress.stackexchange.com/users/94146",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Simple Method</strong> </p>\n\n<p>First thing you need to do is add a new menu item in your menu. You can do that by going to Appearance Β» Menus. You want to add a custom link so give it the label you want. In the URL field, enter the # sign. Once done, click on the Add to Menu button. Save your menu once this custom link is added to the menu.\nAdding a custom link to the menu without URL</p>\n\n<p>Now click on the drop down arrow next to this custom link to edit this menu item. Go ahead and remove the pound sign from the URL field and save your menu. If you go to your live website, then you will see a menu item without link. You can add sub menus to this menu item and link them to any page or custom link you want.\nRemoving # sign and creating a menu without any link.</p>\n\n<p>check this link for more detail.</p>\n\n<p><a href=\"http://www.wpbeginner.com/beginners-guide/how-to-add-titles-in-wordpress-menu-without-linking-to-a-page/\" rel=\"nofollow\">http://www.wpbeginner.com/beginners-guide/how-to-add-titles-in-wordpress-menu-without-linking-to-a-page/</a></p>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226891",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88709/"
] |
I need to save URL's from old site, in options-permalink in admin wordpress i use
```
/blog/%category%/%postname%.html
```
I do it for blog posts. **But i don't need to get it for CPT**
I have created CPT
```
function uslugi_init() {
$args = array(
'label' => 'Π£ΡΠ»ΡΠ³ΠΈ',
'public' => true,
'show_ui' => true,
'capability_type' => 'page',
'hierarchical' => false,
'rewrite' => array('slug' => 'uslugi-i-czenyi'),
'query_var' => true,
'menu_icon' => 'dashicons-video-alt',
'supports' => array(
'title',
'editor',
'excerpt',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'thumbnail',
'author',
'page-attributes',)
);
register_post_type( 'uslugi', $args );
}
add_action( 'init', 'uslugi_init' );
```
BUT i have a big problem - my CPT url is
`site.com/blog/uslugi-i-czenyi/test`
but i need
`site.com/uslugi-i-czenyi/test`
Also i need to get templates from pages...
Is it fixable?
**How to separate CPT url from blog permalink?**
Help me, please!
|
>
> I am not sure how it does effect the SEO but just to answer this
> question:-
>
>
>
You can not save menu item with `javascript:void(0);` because WordPress filter the URL using function [`esc_url()`](https://codex.wordpress.org/Function_Reference/esc_url) thus removing bad values. And it all happens in Nav Walker class. So you need to alter the URL when WordPress done with filtering and returning final safe HTML.
You can use filter `walker_nav_menu_start_el` if your theme does not have custom nav menu walker class OR does have this filter in walker class.
Example:-
```
add_filter('walker_nav_menu_start_el', 'wpse_226884_replace_hash', 999);
/**
* Replace # with js
* @param string $menu_item item HTML
* @return string item HTML
*/
function wpse_226884_replace_hash($menu_item) {
if (strpos($menu_item, 'href="#"') !== false) {
$menu_item = str_replace('href="#"', 'href="javascript:void(0);"', $menu_item);
}
return $menu_item;
}
```
|
226,899 |
<p>I've added the following code to <code>functions.php</code> of my activated child theme:</p>
<pre><code>function fullpagejs() {
$slimscroll = get_stylesheet_directory_uri() . '/library/fullPage.js-master/vendors/jquery.slimscroll.min.js' ;
wp_register_script('fullpage-slimscroll', $slimscroll, false, null);
//some more files will be added here later
}
add_action("wp_enqueue_scripts", "fullpagejs");
</code></pre>
<p>However when I check the page source, I can't find the script <code>jquery.slimscroll.min.js</code> registered.</p>
|
[
{
"answer_id": 226900,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": true,
"text": "<p>You must not only register the script, but also enqueue it after that, like this:</p>\n\n<pre><code>wp_enqueue_script('fullpage-slimscroll');\n</code></pre>\n"
},
{
"answer_id": 226908,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 1,
"selected": false,
"text": "<p>You are registering the script instead on enqueueing.</p>\n\n<p>Also, slimScroll depends on jQuery. So you have to point it out explicitly.</p>\n\n<pre><code>function fullpagejs() {\n $slimscroll = get_stylesheet_directory_uri() . '/library/fullPage.js-master/vendors/jquery.slimscroll.min.js' ;\n wp_enqueue_script( // see here\n 'fullpage-slimscroll',\n $slimscroll,\n array('jquery'), // dependency\n null\n );\n //some more files will be added here later\n}\nadd_action(\"wp_enqueue_scripts\", \"fullpagejs\");\n</code></pre>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226899",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94239/"
] |
I've added the following code to `functions.php` of my activated child theme:
```
function fullpagejs() {
$slimscroll = get_stylesheet_directory_uri() . '/library/fullPage.js-master/vendors/jquery.slimscroll.min.js' ;
wp_register_script('fullpage-slimscroll', $slimscroll, false, null);
//some more files will be added here later
}
add_action("wp_enqueue_scripts", "fullpagejs");
```
However when I check the page source, I can't find the script `jquery.slimscroll.min.js` registered.
|
You must not only register the script, but also enqueue it after that, like this:
```
wp_enqueue_script('fullpage-slimscroll');
```
|
226,916 |
<p>I am trying to search through post meta for keyword matches but I'm new to MySQL and I don't know how to write my query. I can write a basic query for <code>post_title</code> matches but I don't know how to properly jump across tables.</p>
<p>In pseudo code, my query would be </p>
<pre><code>"SELECT post_id FROM $wpdb->postmeta
WHERE meta_key LIKE '%$query%' AND post_type = 'project'"
</code></pre>
<p>My problem is that the <code>post_type</code> is only available in the <code>posts</code> table and I don't know how to make the connection between <code>postmeta</code> and <code>posts</code> to check if the <code>ID</code> is in fact the correct post type.</p>
|
[
{
"answer_id": 226925,
"author": "Pawel J",
"author_id": 93877,
"author_profile": "https://wordpress.stackexchange.com/users/93877",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not an expert but try this one:</p>\n\n<pre><code>SELECT wp_posts.ID, wp_postmeta.meta_value FROM wp_postmeta\nLEFT JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id\nWHERE wp_postmeta.meta_key = '%$query%'\nAND wp_posts.post_type = 'project'\n</code></pre>\n\n<p>it worked for me</p>\n"
},
{
"answer_id": 226934,
"author": "Howard E",
"author_id": 57589,
"author_profile": "https://wordpress.stackexchange.com/users/57589",
"pm_score": 2,
"selected": false,
"text": "<p>Is this what you're trying to do?</p>\n\n<pre><code>// WP_Query arguments\n$args = array (\n 'post_type' => array( 'project' ),\n 'meta_query' => array(\n array(\n 'key' => 'meta_key',\n 'value' => '%$query%',\n ),\n ),\n);\n\n// The Query\n$query = new WP_Query( $args );\n</code></pre>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226916",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44937/"
] |
I am trying to search through post meta for keyword matches but I'm new to MySQL and I don't know how to write my query. I can write a basic query for `post_title` matches but I don't know how to properly jump across tables.
In pseudo code, my query would be
```
"SELECT post_id FROM $wpdb->postmeta
WHERE meta_key LIKE '%$query%' AND post_type = 'project'"
```
My problem is that the `post_type` is only available in the `posts` table and I don't know how to make the connection between `postmeta` and `posts` to check if the `ID` is in fact the correct post type.
|
Is this what you're trying to do?
```
// WP_Query arguments
$args = array (
'post_type' => array( 'project' ),
'meta_query' => array(
array(
'key' => 'meta_key',
'value' => '%$query%',
),
),
);
// The Query
$query = new WP_Query( $args );
```
|
226,922 |
<p>I have a video gallery, and all the titles are generated by <code>php</code>. They are coming from my Wordpress media library's attachment titles.</p>
<p>The lightbox for these videos, however, is customized in javascript. How can I put the <code>php</code> titles inside the <code>iframe</code> <code>markup</code>?</p>
<p>PHP - need to use <code>$attachment_data['title']</code>:</p>
<pre><code> <?php
$the_query = new WP_Query(array( 'post_type' => 'attachment','category_name' => 'video'));
while ( $the_query->have_posts() ) : $the_query->the_post();?>
<?php $attachment_data = wp_prepare_attachment_for_js( $attachment->ID );
echo'<div class="title"><h2>'.$attachment_data['title'].'</h2></div>';?>
<?php endwhile; wp_reset_postdata();?>
</code></pre>
<p>Javascript:</p>
<pre><code> $('.video').Lightbox({
type: 'iframe'
iframe: {
markup: '<div class="lightbox_container">'+
'<iframe class="iframe" frameborder="0" allowfullscreen></iframe>'+
'<div class="title"> PHP GOES HERE </div>'+
'</div>',
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
});
</code></pre>
|
[
{
"answer_id": 226927,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>First, don't echo your php, but assemble everything in a string, let's say <code>$titlestring</code>.</p>\n\n<p>Next, make this string available for access by the javascript (the slug is the one you used to register the script):</p>\n\n<pre><code>$params = array (\n 'titlestring' => $titlestring,\n );\nwp_localize_script ('your-script-slug', 'IframeTitle', $params);\n</code></pre>\n\n<p>Finally, access the variable in the script:</p>\n\n<pre><code>'<div class=\"title\">' + IframeTitle.titlestring + '</div>' +\n</code></pre>\n"
},
{
"answer_id": 252335,
"author": "BlueHelmet",
"author_id": 93909,
"author_profile": "https://wordpress.stackexchange.com/users/93909",
"pm_score": 1,
"selected": true,
"text": "<p>The developer included a solution for this, discussed here: <a href=\"https://stackoverflow.com/questions/17612258/title-for-iframe-video-in-magnific-popup\">https://stackoverflow.com/questions/17612258/title-for-iframe-video-in-magnific-popup</a> </p>\n\n<p>First I needed to include the title in my <code>php</code>:</p>\n\n<pre><code>echo'<figure><a class=\"video\" title=\"'.$attachment_data['title'].'\" href=\"'.get_post_meta($post->ID, 'credit_url', true).'\">';\n</code></pre>\n\n<p>And then, I needed the callback:</p>\n\n<pre><code>callbacks: {\n markupParse: function(template, values, item) {\n values.title = item.el.attr('title');\n }\n</code></pre>\n\n<p>Thank you for your help!</p>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226922",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93909/"
] |
I have a video gallery, and all the titles are generated by `php`. They are coming from my Wordpress media library's attachment titles.
The lightbox for these videos, however, is customized in javascript. How can I put the `php` titles inside the `iframe` `markup`?
PHP - need to use `$attachment_data['title']`:
```
<?php
$the_query = new WP_Query(array( 'post_type' => 'attachment','category_name' => 'video'));
while ( $the_query->have_posts() ) : $the_query->the_post();?>
<?php $attachment_data = wp_prepare_attachment_for_js( $attachment->ID );
echo'<div class="title"><h2>'.$attachment_data['title'].'</h2></div>';?>
<?php endwhile; wp_reset_postdata();?>
```
Javascript:
```
$('.video').Lightbox({
type: 'iframe'
iframe: {
markup: '<div class="lightbox_container">'+
'<iframe class="iframe" frameborder="0" allowfullscreen></iframe>'+
'<div class="title"> PHP GOES HERE </div>'+
'</div>',
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
});
```
|
The developer included a solution for this, discussed here: <https://stackoverflow.com/questions/17612258/title-for-iframe-video-in-magnific-popup>
First I needed to include the title in my `php`:
```
echo'<figure><a class="video" title="'.$attachment_data['title'].'" href="'.get_post_meta($post->ID, 'credit_url', true).'">';
```
And then, I needed the callback:
```
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
```
Thank you for your help!
|
226,923 |
<p>I've seen this question posted in different forms before, but most of those solutions are centered around the admin interface, and I haven't found any answers that apply to the front end.</p>
<p>I've got a custom post type, and an associated custom taxonomy. I'm using the archive page (<code>archive-{custom_type}.php</code>) to display the items, and using <code>wp_list_categories</code> to show a list of the custom taxonomy terms. I can manually alter the posts displayed by adding a <code>tax_query</code> parameter to the <code>WP_Query</code> call, but the problem I'm running into is I cannot figure out how to alter the taxonomy links so they point to this archive page so I can filter dynamically. I'd rather not duplicate this template's markup and code in a <code>taxonomy-{custom_type}.php</code> file.</p>
<p>Do I need to just output the taxonomy links manually? How should the URL be structured so I can get the query param? I have <code>query_var => true</code> set and a rewrite rule on the custom taxonomy definition, but haven't been able to get <code>get_query_var()</code> to return anything.</p>
<p>The end result should be a template that can list all items in the custom post type, or filter those items by their associated custom taxonomy.</p>
|
[
{
"answer_id": 226927,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>First, don't echo your php, but assemble everything in a string, let's say <code>$titlestring</code>.</p>\n\n<p>Next, make this string available for access by the javascript (the slug is the one you used to register the script):</p>\n\n<pre><code>$params = array (\n 'titlestring' => $titlestring,\n );\nwp_localize_script ('your-script-slug', 'IframeTitle', $params);\n</code></pre>\n\n<p>Finally, access the variable in the script:</p>\n\n<pre><code>'<div class=\"title\">' + IframeTitle.titlestring + '</div>' +\n</code></pre>\n"
},
{
"answer_id": 252335,
"author": "BlueHelmet",
"author_id": 93909,
"author_profile": "https://wordpress.stackexchange.com/users/93909",
"pm_score": 1,
"selected": true,
"text": "<p>The developer included a solution for this, discussed here: <a href=\"https://stackoverflow.com/questions/17612258/title-for-iframe-video-in-magnific-popup\">https://stackoverflow.com/questions/17612258/title-for-iframe-video-in-magnific-popup</a> </p>\n\n<p>First I needed to include the title in my <code>php</code>:</p>\n\n<pre><code>echo'<figure><a class=\"video\" title=\"'.$attachment_data['title'].'\" href=\"'.get_post_meta($post->ID, 'credit_url', true).'\">';\n</code></pre>\n\n<p>And then, I needed the callback:</p>\n\n<pre><code>callbacks: {\n markupParse: function(template, values, item) {\n values.title = item.el.attr('title');\n }\n</code></pre>\n\n<p>Thank you for your help!</p>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226923",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50668/"
] |
I've seen this question posted in different forms before, but most of those solutions are centered around the admin interface, and I haven't found any answers that apply to the front end.
I've got a custom post type, and an associated custom taxonomy. I'm using the archive page (`archive-{custom_type}.php`) to display the items, and using `wp_list_categories` to show a list of the custom taxonomy terms. I can manually alter the posts displayed by adding a `tax_query` parameter to the `WP_Query` call, but the problem I'm running into is I cannot figure out how to alter the taxonomy links so they point to this archive page so I can filter dynamically. I'd rather not duplicate this template's markup and code in a `taxonomy-{custom_type}.php` file.
Do I need to just output the taxonomy links manually? How should the URL be structured so I can get the query param? I have `query_var => true` set and a rewrite rule on the custom taxonomy definition, but haven't been able to get `get_query_var()` to return anything.
The end result should be a template that can list all items in the custom post type, or filter those items by their associated custom taxonomy.
|
The developer included a solution for this, discussed here: <https://stackoverflow.com/questions/17612258/title-for-iframe-video-in-magnific-popup>
First I needed to include the title in my `php`:
```
echo'<figure><a class="video" title="'.$attachment_data['title'].'" href="'.get_post_meta($post->ID, 'credit_url', true).'">';
```
And then, I needed the callback:
```
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
```
Thank you for your help!
|
226,956 |
<p>I inherited a problem that no one in my office can figure out. </p>
<p>Our company website has page titles in the format of "Page Name Company Name - Company Name." The first instance of Company Name is a duplicate and needs to be deleted (it should be Page Name - Company Name), but I'm not sure how to proceed from looking at the code. This is a custom WP theme that is a child of the 2014 stock theme. Does anything in this title code snippet stand out?</p>
<pre><code><title>
<?php
if (function_exists('is_tag') && is_tag()) {
single_tag_title("Tag Archive for &quot;"); echo '&quot; - '; }
elseif (is_archive()) {
wp_title(''); echo ' Archive - '; }
elseif (is_search()) {
echo 'Search for &quot;'.wp_specialchars($s).'&quot; - '; }
elseif (!(is_404()) && (is_single()) || (is_page())) {
wp_title(''); echo ' - '; }
elseif (is_404()) {
echo 'Not Found - '; }
if (is_home()) {
bloginfo('name'); echo ' - '; bloginfo('description'); }
else {
bloginfo('name'); }
if ($paged>1) {
echo ' - page '. $paged; }
?>
</title>
</code></pre>
|
[
{
"answer_id": 226958,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 1,
"selected": false,
"text": "<p>You're on a page and if we read through the list of conditionals it should hit this one specifically:</p>\n\n<pre><code>elseif( ! ( is_404() ) && ( is_single() ) || ( is_page() ) ) {\n wp_title( '' );\n echo ' - ';\n}\n</code></pre>\n\n<p>It will also hit the below conditional in the next set:</p>\n\n<pre><code>else {\n bloginfo( 'name' );\n}\n</code></pre>\n\n<p>Given page <code>Test Page</code> we should see <code>Page Name - Company Name</code> but the parent Twenty Fourteen theme has this filter on <code>wp_title()</code>:</p>\n\n<pre><code>function twentyfourteen_wp_title( $title, $sep ) {\n global $paged, $page;\n\n if ( is_feed() ) {\n return $title;\n }\n\n // Add the site name.\n $title .= get_bloginfo( 'name', 'display' );\n\n // Add the site description for the home/front page.\n $site_description = get_bloginfo( 'description', 'display' );\n if ( $site_description && ( is_home() || is_front_page() ) ) {\n $title = \"$title $sep $site_description\";\n }\n\n // Add a page number if necessary.\n if ( ( $paged >= 2 || $page >= 2 ) && ! is_404() ) {\n $title = \"$title $sep \" . sprintf( __( 'Page %s', 'twentyfourteen' ), max( $paged, $page ) );\n }\n\n return $title;\n}\nadd_filter( 'wp_title', 'twentyfourteen_wp_title', 10, 2 );\n</code></pre>\n\n<p>Notice that it is also appending the Website Name to the title ( directly after the feed conditional ) which is why we end up seeing the company name twice. You can comment out the above line to remove the duplication.</p>\n\n<pre><code>function twentyfourteen_wp_title( $title, $sep ) {\n global $paged, $page;\n\n if ( is_feed() ) {\n return $title;\n }\n\n // DONT Add the site name.\n // $title .= get_bloginfo( 'name', 'display' );\n\n // Add the site description for the home/front page.\n $site_description = get_bloginfo( 'description', 'display' );\n if ( $site_description && ( is_home() || is_front_page() ) ) {\n $title = \"$title $sep $site_description\";\n }\n\n // Add a page number if necessary.\n if ( ( $paged >= 2 || $page >= 2 ) && ! is_404() ) {\n $title = \"$title $sep \" . sprintf( __( 'Page %s', 'twentyfourteen' ), max( $paged, $page ) );\n }\n\n return $title;\n}\nadd_filter( 'wp_title', 'twentyfourteen_wp_title', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 226963,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 0,
"selected": false,
"text": "<p>Check the <code>add_theme_support( 'title-tag' );</code></p>\n\n<p><a href=\"https://make.wordpress.org/core/2014/10/29/title-tags-in-4-1/\" rel=\"nofollow\">https://make.wordpress.org/core/2014/10/29/title-tags-in-4-1/</a></p>\n\n<pre><code>function theme_slug_setup() {\n add_theme_support( 'title-tag' );\n}\nadd_action( 'after_setup_theme', 'theme_slug_setup' );\n</code></pre>\n\n<blockquote>\n <p>By declaring support like this, themes acknowledge that they are not defining titles on their own and WordPress can add it safely without duplication.</p>\n</blockquote>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226956",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92178/"
] |
I inherited a problem that no one in my office can figure out.
Our company website has page titles in the format of "Page Name Company Name - Company Name." The first instance of Company Name is a duplicate and needs to be deleted (it should be Page Name - Company Name), but I'm not sure how to proceed from looking at the code. This is a custom WP theme that is a child of the 2014 stock theme. Does anything in this title code snippet stand out?
```
<title>
<?php
if (function_exists('is_tag') && is_tag()) {
single_tag_title("Tag Archive for ""); echo '" - '; }
elseif (is_archive()) {
wp_title(''); echo ' Archive - '; }
elseif (is_search()) {
echo 'Search for "'.wp_specialchars($s).'" - '; }
elseif (!(is_404()) && (is_single()) || (is_page())) {
wp_title(''); echo ' - '; }
elseif (is_404()) {
echo 'Not Found - '; }
if (is_home()) {
bloginfo('name'); echo ' - '; bloginfo('description'); }
else {
bloginfo('name'); }
if ($paged>1) {
echo ' - page '. $paged; }
?>
</title>
```
|
You're on a page and if we read through the list of conditionals it should hit this one specifically:
```
elseif( ! ( is_404() ) && ( is_single() ) || ( is_page() ) ) {
wp_title( '' );
echo ' - ';
}
```
It will also hit the below conditional in the next set:
```
else {
bloginfo( 'name' );
}
```
Given page `Test Page` we should see `Page Name - Company Name` but the parent Twenty Fourteen theme has this filter on `wp_title()`:
```
function twentyfourteen_wp_title( $title, $sep ) {
global $paged, $page;
if ( is_feed() ) {
return $title;
}
// Add the site name.
$title .= get_bloginfo( 'name', 'display' );
// Add the site description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) ) {
$title = "$title $sep $site_description";
}
// Add a page number if necessary.
if ( ( $paged >= 2 || $page >= 2 ) && ! is_404() ) {
$title = "$title $sep " . sprintf( __( 'Page %s', 'twentyfourteen' ), max( $paged, $page ) );
}
return $title;
}
add_filter( 'wp_title', 'twentyfourteen_wp_title', 10, 2 );
```
Notice that it is also appending the Website Name to the title ( directly after the feed conditional ) which is why we end up seeing the company name twice. You can comment out the above line to remove the duplication.
```
function twentyfourteen_wp_title( $title, $sep ) {
global $paged, $page;
if ( is_feed() ) {
return $title;
}
// DONT Add the site name.
// $title .= get_bloginfo( 'name', 'display' );
// Add the site description for the home/front page.
$site_description = get_bloginfo( 'description', 'display' );
if ( $site_description && ( is_home() || is_front_page() ) ) {
$title = "$title $sep $site_description";
}
// Add a page number if necessary.
if ( ( $paged >= 2 || $page >= 2 ) && ! is_404() ) {
$title = "$title $sep " . sprintf( __( 'Page %s', 'twentyfourteen' ), max( $paged, $page ) );
}
return $title;
}
add_filter( 'wp_title', 'twentyfourteen_wp_title', 10, 2 );
```
|
226,960 |
<p>There are two <code>query_posts()</code> functions technically speaking. One <code>query_posts()</code> is actually <code>WP_Query::query_posts()</code> and the other is in global space.</p>
<p>Asking from sanity: </p>
<p>If global <code>query_posts()</code> is that "evil" why isn't deprecated? </p>
<p>Or why isn't marked as <code>_doing_it_wong</code>.</p>
|
[
{
"answer_id": 226992,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": false,
"text": "<p>I have just created a new trac ticket, <a href=\"https://core.trac.wordpress.org/ticket/36874\" rel=\"nofollow noreferrer\">ticket #36874</a>, to propose the deprecation of <code>query_posts()</code>. Whether or not it will be accepted remains a good question. </p>\n\n<p>The real big issue with <code>query_posts()</code> is, it is still widely used by plugins and themes, even though there have been really good writings on the subject of why you should <strong>NEVER EVER</strong> use it. I think the most epic post here on WPSE is the following one:</p>\n\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/q/1753/31545\">When should you use WP_Query vs query_posts() vs get_posts()?</a></li>\n</ul>\n\n<p><em>deprecation !== removal</em>, so deprecating <code>query_posts()</code> will not stop its usage by poor quality devs and people in general who do not know WordPress and who use poor quality tutorials as guidelines. Just as some proof, how many questions do we still get here where people use <code>caller_get_posts</code> in <code>WP_Query</code>? It has been deprecated for many years now.</p>\n\n<p>Deprecated functions and arguments can however be removed at any time the core devs see fit, but this will most probably never happen with <code>query_posts()</code> as this will break millions of sites. So yes, we will probably never see the total removal of <code>query_posts()</code> - which might lead to the fact that it will most probably never get deprecated.</p>\n\n<p>This is a starting point though, but one has to remember, deprecating something in WordPress does not stop its use.</p>\n\n<h1>UPDATE 19 May 2016</h1>\n\n<p>The ticket I raised is now closed and marked as duplicate to a <strong><em>4 year old</em></strong> ticket, which was closed as <em>wontfix</em> and was reopened and still remain open and unresolved.</p>\n\n<p>Seems the core developers are hanging on to this old faithful little evil. Everyone interested, here is the duplicate 4year old ticket</p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/19631\" rel=\"nofollow noreferrer\">trac ticket #19631</a></li>\n</ul>\n"
},
{
"answer_id": 227238,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>[somewhat rant]</p>\n\n<p>It is the standing core philosophy at this point that nothing is truly deprecated. Deprecation notice, while it is a nice to have, is just going to be ignored if the function will not actually be dropped at some point. There are many people that do not develop with <code>WP_DEBUG</code> on and will not notice the notice if there will not be an actual breakage.</p>\n\n<p>OTOH hand, this function is like <code>goto</code> statement. Personally I never (for smaller definition then expected) used <code>goto</code>but I can understand the arguments pointing to some situation in which it is not evil by default. Same goes with <code>query_posts</code>, it is a simple way to set up all the globals required to make a simple loop, and can be useful in ajax or rest-api context. I would never use it in those contexts as well, but I can see that there, it is more of an issue of style of coding then a function being evil by itself.</p>\n\n<p>Going a little deeper, the main problem is that globals need to be set at all. That is the main problem not the one function that helps setting them.</p>\n"
},
{
"answer_id": 248955,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 5,
"selected": true,
"text": "<h1>Essential question</h1>\n\n<p>Let's dig into the trio: <code>::query_posts</code>, <code>::get_posts</code> and <code>class WP_Query</code> to understand <code>::query_posts</code> better.</p>\n\n<p>The cornerstone for getting the data in WordPress is the <code>WP_Query</code> class. Both methods <code>::query_posts</code> and <code>::get_posts</code> use that class. </p>\n\n<blockquote>\n <p>Note that the class <code>WP_Query</code> also contains the methods with the same name: <code>WP_Query::query_posts</code> and <code>WP_Query::get_posts</code>, but we actually only consider the global methods, so don't get confused.</p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/gIk6t.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gIk6t.png\" alt=\"enter image description here\"></a></p>\n\n<h1>Understanding the <code>WP_Query</code></h1>\n\n<blockquote>\n <p>The class called <code>WP_Query</code> has been introduced back in 2004. All fields having the β (umbrella) mark where present back in 2004. The additional fields were added later.</p>\n</blockquote>\n\n<p>Here is the <code>WP_Query</code> structure:</p>\n\n<pre><code>class WP_Query (as in WordPress v4.7) \n public $query; β\n public $query_vars = array(); β\n public $tax_query;\n public $meta_query = false;\n public $date_query = false;\n public $queried_object; β\n public $queried_object_id; β\n public $request;\n public $posts; β\n public $post_count = 0; β\n public $current_post = -1; β\n public $in_the_loop = false;\n public $post; β\n public $comments;\n public $comment_count = 0;\n public $current_comment = -1;\n public $comment;\n public $found_posts = 0;\n public $max_num_pages = 0;\n public $max_num_comment_pages = 0;\n public $is_single = false; β\n public $is_preview = false; β\n public $is_page = false; β\n public $is_archive = false; β\n public $is_date = false; β\n public $is_year = false; β\n public $is_month = false; β\n public $is_day = false; β\n public $is_time = false; β\n public $is_author = false; β\n public $is_category = false; β\n public $is_tag = false;\n public $is_tax = false;\n public $is_search = false; β\n public $is_feed = false; β\n public $is_comment_feed = false;\n public $is_trackback = false; β\n public $is_home = false; β\n public $is_404 = false; β\n public $is_embed = false;\n public $is_paged = false;\n public $is_admin = false; β\n public $is_attachment = false;\n public $is_singular = false;\n public $is_robots = false;\n public $is_posts_page = false;\n public $is_post_type_archive = false;\n private $query_vars_hash = false;\n private $query_vars_changed = true;\n public $thumbnails_cached = false;\n private $stopwords;\n private $compat_fields = array('query_vars_hash', 'query_vars_changed');\n private $compat_methods = array('init_query_flags', 'parse_tax_query');\n private function init_query_flags()\n</code></pre>\n\n<h1><code>WP_Query</code> is the Swiss army knife.</h1>\n\n<p>Some things about <code>WP_Query</code>:</p>\n\n<ul>\n<li>it is something you can control via arguments you pass</li>\n<li>it is greedy by default</li>\n<li>it holds the substance for looping</li>\n<li>it is saved in the global space x2</li>\n<li>it can be primary or secondary</li>\n<li>it uses helper classes</li>\n<li>it has a handy <code>pre_get_posts</code> hook</li>\n<li>it even has support for nested loops</li>\n<li>it holds the SQL query string</li>\n<li>it holds the number of the results</li>\n<li>it holds the results</li>\n<li>it holds the list of all possible query arguments</li>\n<li>it holds the template flags</li>\n<li>...</li>\n</ul>\n\n<p>I cannot explain all these, but some of these are tricky, so let's provide short tips.</p>\n\n<h2><code>WP_Query</code> is something you can control via arguments you pass</h2>\n\n<pre><code>The list of the arguments\n---\n attachment\n attachment_id\n author\n author__in\n author__not_in\n author_name\n cache_results\n cat\n category__and\n category__in\n category__not_in\n category_name\n comments_per_page\n day\n embed\n error\n feed\n fields\n hour\n ignore_sticky_posts\n lazy_load_term_meta\n m\n menu_order\n meta_key\n meta_value\n minute\n monthnum\n name\n no_found_rows\n nopaging\n order\n p\n page_id\n paged\n pagename\n post__in\n post__not_in\n post_name__in\n post_parent\n post_parent__in\n post_parent__not_in\n post_type\n posts_per_page\n preview\n s\n second\n sentence\n static\n subpost\n subpost_id\n suppress_filters\n tag\n tag__and\n tag__in\n tag__not_in\n tag_id\n tag_slug__and\n tag_slug__in\n tb\n title\n update_post_meta_cache\n update_post_term_cache\n w\n year\n</code></pre>\n\n<blockquote>\n <p>This list from WordPress version 4.7 will certainly change in the future. </p>\n</blockquote>\n\n<p>This would be the minimal example creating the <code>WP_Query</code> object from the arguments:</p>\n\n<pre><code>// WP_Query arguments\n$args = array ( /* arguments*/ );\n// creating the WP_Query object\n$query = new WP_Query( $args );\n// print full list of arguments WP_Query can take\nprint ( $query->query_vars );\n</code></pre>\n\n<h2><code>WP_Query</code> is greedy</h2>\n\n<p>Created on the idea <code>get all you can</code> WordPress developers decided to get all possible data early as this is <a href=\"http://wordpress.tv/2012/06/15/andrew-nacin-wp_query/\" rel=\"noreferrer\">good for the performance</a>.\nThis is why by default when the query takes 10 posts from the database it will also get the terms and the metadata for these posts via separate queries. Terms and metadata will be cached (prefetched).</p>\n\n<blockquote>\n <p>Note the caching is just for the single request lifetime.</p>\n</blockquote>\n\n<p>You can disable the caching if you set <code>update_post_meta_cache</code> and <code>update_post_term_cache</code> to <code>false</code> while setting the <code>WP_Query</code> arguments. When caching is disabled the data will be requested from the database only on demand.</p>\n\n<p>For the majority of WordPress blogs caching works well, but there are some occasions when you may disable the caching.</p>\n\n<h2><code>WP_Query</code> uses helper classes</h2>\n\n<p>If you checked <code>WP_Query</code> fields there you have these three:</p>\n\n<pre><code>public $tax_query;\npublic $meta_query;\npublic $date_query;\n</code></pre>\n\n<p>You can imagine adding new in the future.</p>\n\n<p><a href=\"https://i.stack.imgur.com/3pHZb.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3pHZb.png\" alt=\"enter image description here\"></a></p>\n\n<h2><code>WP_Query</code> holds the substance for looping</h2>\n\n<p>In this code:</p>\n\n<pre><code>$query = new WP_Query( $args )\nif ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n</code></pre>\n\n<p>you may notice the <code>WP_Query</code> has the substance you can iterate. The helper methods are there also. You just set the <code>while</code> loop.</p>\n\n<blockquote>\n <p>Note. <code>for</code> and <code>while</code> loops are semantically equivalent.</p>\n</blockquote>\n\n<h2><code>WP_Query</code> primary and secondary</h2>\n\n<p>In WordPress you have one <strong>primary</strong> and zero or more <strong>secondary</strong> queries.</p>\n\n<blockquote>\n <p>It is possible not to have the primary query, but this is beyond the scope of this article. </p>\n</blockquote>\n\n<p><em>Primary query</em> known as the <em>main query</em> or the <em>regular query</em>. <em>Secondary query</em> also called a <em>custom query</em>.</p>\n\n<p>WordPress uses <code>WP_Rewrite</code> class early to create the query arguments based on the URL. Based on these arguments it stores the two identical objects in the global space. Both of these will hold the main query.</p>\n\n<pre><code>global $wp_query @since WordPress 1.5\nglobal $wp_the_query @since WordPress 2.1\n</code></pre>\n\n<p>When we say <em>main query</em> we think of these variables. Other queries can be called secondary or custom.</p>\n\n<blockquote>\n <p>It is completely legal to use either <code>global $wp_query</code> or <code>$GLOBALS['wp_query']</code>, but using the second notation is much more notable, and saves typing an extra line inside the scope of the functions.</p>\n \n <p><code>$GLOBALS['wp_query']</code> and <code>$GLOBALS['wp_the_query']</code> are separate objects. <code>$GLOBALS['wp_the_query']</code> should remain frozen. </p>\n</blockquote>\n\n<h2><code>WP_Query</code> has the handy <code>pre_get_posts</code> hook.</h2>\n\n<p>This is the action hook. It will apply to <strong>any</strong> <code>WP_Query</code> instance. You call it like: </p>\n\n<pre><code>add_action( 'pre_get_posts', function($query){\n\n if ( is_category() && $query->is_main_query() ) {\n // set your improved arguments\n $query->set( ... ); \n ... \n }\n\n return $query; \n});\n</code></pre>\n\n<p>This hook is great and it can alter any query arguments.</p>\n\n<p>Here is what you can <a href=\"https://wpseek.com/hook/pre_get_posts/\" rel=\"noreferrer\">read</a>:</p>\n\n<blockquote>\n <p>Fires after the query variable object is created, but before the actual query is run.</p>\n</blockquote>\n\n<p>So this hook is arguments manager but cannot create new <code>WP_Query</code> objects. If you had one primary and one secondary query, <code>pre_get_posts</code> cannot create the third one. Or if you just had one primary it cannot create the secondary.</p>\n\n<blockquote>\n <p>Note in case you need to alter the main query only you can use the <code>request</code> hook also.</p>\n</blockquote>\n\n<h2><code>WP_Query</code> supports nested loops</h2>\n\n<blockquote>\n <p>This scenario may happen if you use plugins, and you call plugin functions from the template.</p>\n</blockquote>\n\n<p>Here is the showcase example WordPress have helper functions even for the nested loops:</p>\n\n<pre><code>global $id;\nwhile ( have_posts() ) : the_post(); \n\n // the custom $query\n $query = new WP_Query( array( 'posts_per_page' => 5 ) ); \n if ( $query->have_posts() ) {\n\n while ( $query->have_posts() ) : $query->the_post(); \n echo '<li>Custom ' . $id . '. ' . get_the_title() . '</li>';\n endwhile; \n } \n\n wp_reset_postdata();\n echo '<li>Main Query ' . $id . '. ' . get_the_title() . '</li>';\n\nendwhile;\n</code></pre>\n\n<p>The output will be like this since I installed <a href=\"https://codex.wordpress.org/Theme_Unit_Test\" rel=\"noreferrer\">theme unit test data</a>:</p>\n\n<pre><code>Custom 100. Template: Sticky\nCustom 1. Hello world!\nCustom 10. Markup: HTML Tags and Formatting\nCustom 11. Markup: Image Alignment\nCustom 12. Markup: Text Alignment\nCustom 13. Markup: Title With Special Characters\nMain Query 1. Hello world!\n</code></pre>\n\n<p>Even though I requested 5 posts in the custom $query it will return me six, because the sticky post will go along. \nIf there no <code>wp_reset_postdata</code> in the previous example the output will be like this, because of the <code>$GLOBALS['post']</code> will be invalid.</p>\n\n<pre><code>Custom 1001. Template: Sticky\nCustom 1. Hello world!\nCustom 10. Markup: HTML Tags and Formatting\nCustom 11. Markup: Image Alignment\nCustom 12. Markup: Text Alignment\nCustom 13. Markup: Title With Special Characters\nMain Query 13. Markup: Title With Special Characters\n</code></pre>\n\n<h2><code>WP_Query</code> has <code>wp_reset_query</code> function</h2>\n\n<p>This is like a reset button. <code>$GLOBALS['wp_the_query']</code> should be frozen all the time, and plugins or themes should never alter it.</p>\n\n<p>Here is what <code>wp_reset_query</code> do:</p>\n\n<pre><code>function wp_reset_query() {\n $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];\n wp_reset_postdata();\n}\n</code></pre>\n\n<h1>Remarks on <code>get_posts</code></h1>\n\n<p><code>get_posts</code> looks like</p>\n\n<pre><code>File: /wp-includes/post.php\n1661: function get_posts( $args = null ) {\n1662: $defaults = array(\n1663: 'numberposts' => 5,\n1664: 'category' => 0, 'orderby' => 'date',\n1665: 'order' => 'DESC', 'include' => array(),\n1666: 'exclude' => array(), 'meta_key' => '',\n1667: 'meta_value' =>'', 'post_type' => 'post',\n1668: 'suppress_filters' => true\n1669: );\n... // do some argument parsing\n1685: $r['ignore_sticky_posts'] = true;\n1686: $r['no_found_rows'] = true;\n1687: \n1688: $get_posts = new WP_Query;\n1689: return $get_posts->query($r);\n</code></pre>\n\n<blockquote>\n <p>The line numbers may change in the future.</p>\n</blockquote>\n\n<p>It is just a <strong>wrapper</strong> around <code>WP_Query</code> that <strong>returns</strong> the query object posts.</p>\n\n<p>The <code>ignore_sticky_posts</code> set to true means the sticky posts may show up only in a natural position. There will be no sticky posts in the front. The other <code>no_found_rows</code> set to true means WordPress database API will not use <code>SQL_CALC_FOUND_ROWS</code> in order to implement pagination, reducing the load on the database to execute <em>found rows</em> count.</p>\n\n<p>This is handy when you don't need pagination. We understand now we can mimic this function with this query:</p>\n\n<pre><code>$args = array ( 'ignore_sticky_posts' => true, 'no_found_rows' => true);\n$query = new WP_Query( $args );\nprint( $query->request );\n</code></pre>\n\n<p>Here is the corresponding SQL request:</p>\n\n<pre><code>SELECT wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 10\n</code></pre>\n\n<p>Compare what we have now with the previous SQL request where <code>SQL_CALC_FOUND_ROWS</code> exists. </p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 10\n</code></pre>\n\n<p>The request without <code>SQL_CALC_FOUND_ROWS</code> will be faster.</p>\n\n<h1>Remarks on <code>query_posts</code></h1>\n\n<blockquote>\n <p>Tip: At first in 2004 there was only <code>global $wp_query</code>. As of WordPress 2.1 version <code>$wp_the_query</code> came.\n Tip: <code>$GLOBALS['wp_query']</code> and <code>$GLOBALS['wp_the_query']</code> are separate objects.</p>\n</blockquote>\n\n<p><code>query_posts()</code> is <code>WP_Query</code> wrapper. It returns the reference to the main <code>WP_Query</code> object, and at the same time it will set the <code>global $wp_query</code>.</p>\n\n<pre><code>File: /wp-includes/query.php\nfunction query_posts($args) {\n $GLOBALS['wp_query'] = new WP_Query();\n return $GLOBALS['wp_query']->query($args);\n}\n</code></pre>\n\n<p>In PHP4 everything, including objects, was passed by value. <code>query_posts</code> was like this:</p>\n\n<pre><code>File: /wp-includes/query.php (WordPress 3.1)\nfunction &query_posts($args) {\n unset($GLOBALS['wp_query']);\n $GLOBALS['wp_query'] =& new WP_Query();\n return $GLOBALS['wp_query']->query($args);\n}\n</code></pre>\n\n<p>Please note in typical scenario with one primary and one secondary query we have these three variables:</p>\n\n<pre><code>$GLOBALS['wp_the_query'] \n$GLOBALS['wp_query'] // should be the copy of first one\n$custom_query // secondary\n</code></pre>\n\n<p>Let's say each of these three takes 1M of memory. Total would be 3M of memory.\nIf we use <code>query_posts</code>, <code>$GLOBALS['wp_query']</code> will be unset and created again.</p>\n\n<p>PHP5+ should be smart emptying the <code>$GLOBALS['wp_query']</code> object, just like in PHP4 we did it with the <code>unset($GLOBALS['wp_query']);</code></p>\n\n<pre><code>function query_posts($args) {\n $GLOBALS['wp_query'] = new WP_Query();\n return $GLOBALS['wp_query']->query($args);\n}\n</code></pre>\n\n<p>As a result <code>query_posts</code> consumes 2M of memory in total, while <code>get_posts</code> consumes 3M of memory.</p>\n\n<p>Note in <code>query_posts</code> we are not returning the actual object, but a reference to the object.</p>\n\n<blockquote>\n <p>From <a href=\"http://php.net/manual/en/language.oop5.references.php\" rel=\"noreferrer\">php.net</a>:\n A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.</p>\n \n <p>Also in PHP5+ the assign (=) operator is smart. It will use <strong>shallow</strong> copy and not hard object copy. When we write like this <code>$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];</code> only the data will be copied, not the whole object since these share the same object type.</p>\n</blockquote>\n\n<p>Here is one example</p>\n\n<pre><code>print( md5(serialize($GLOBALS['wp_the_query']) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\nquery_posts( '' );\nprint( md5(serialize($GLOBALS['wp_the_query']) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\n</code></pre>\n\n<p>Will result:</p>\n\n<pre><code>f14153cab65abf1ea23224a1068563ef\nf14153cab65abf1ea23224a1068563ef\nf14153cab65abf1ea23224a1068563ef\nd6db1c6bfddac328442e91b6059210b5\n</code></pre>\n\n<p>Try to reset the query:</p>\n\n<pre><code>print( md5(serialize($GLOBALS['wp_the_query'] ) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\nquery_posts( '' );\nwp_reset_query();\nprint( md5(serialize($GLOBALS['wp_the_query'] ) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\n</code></pre>\n\n<p>Will result:</p>\n\n<pre><code>f14153cab65abf1ea23224a1068563ef\nf14153cab65abf1ea23224a1068563ef\nf14153cab65abf1ea23224a1068563ef\nf14153cab65abf1ea23224a1068563ef\n</code></pre>\n\n<p>You can create problems even if you use <code>WP_Query</code></p>\n\n<pre><code>print( md5(serialize($GLOBALS['wp_the_query'] ) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\nglobal $wp_query;\n$wp_query = new WP_Query( array( 'post_type' => 'post' ) ); \nprint( md5(serialize($GLOBALS['wp_the_query'] ) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\n</code></pre>\n\n<p>Of course, the solution would be to use <code>wp_reset_query</code> function again.</p>\n\n<pre><code>print( md5(serialize($GLOBALS['wp_the_query'] ) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\nglobal $wp_query;\n$wp_query = new WP_Query( array( 'post_type' => 'post' ) );\nwp_reset_query();\nprint( md5(serialize($GLOBALS['wp_the_query'] ) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\n</code></pre>\n\n<p>This is why I think <code>query_posts</code> may be better from the memory standpoint. But you should always do <code>wp_reset_query</code> trick.</p>\n"
}
] |
2016/05/17
|
[
"https://wordpress.stackexchange.com/questions/226960",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88606/"
] |
There are two `query_posts()` functions technically speaking. One `query_posts()` is actually `WP_Query::query_posts()` and the other is in global space.
Asking from sanity:
If global `query_posts()` is that "evil" why isn't deprecated?
Or why isn't marked as `_doing_it_wong`.
|
Essential question
==================
Let's dig into the trio: `::query_posts`, `::get_posts` and `class WP_Query` to understand `::query_posts` better.
The cornerstone for getting the data in WordPress is the `WP_Query` class. Both methods `::query_posts` and `::get_posts` use that class.
>
> Note that the class `WP_Query` also contains the methods with the same name: `WP_Query::query_posts` and `WP_Query::get_posts`, but we actually only consider the global methods, so don't get confused.
>
>
>
[](https://i.stack.imgur.com/gIk6t.png)
Understanding the `WP_Query`
============================
>
> The class called `WP_Query` has been introduced back in 2004. All fields having the β (umbrella) mark where present back in 2004. The additional fields were added later.
>
>
>
Here is the `WP_Query` structure:
```
class WP_Query (as in WordPress v4.7)
public $query; β
public $query_vars = array(); β
public $tax_query;
public $meta_query = false;
public $date_query = false;
public $queried_object; β
public $queried_object_id; β
public $request;
public $posts; β
public $post_count = 0; β
public $current_post = -1; β
public $in_the_loop = false;
public $post; β
public $comments;
public $comment_count = 0;
public $current_comment = -1;
public $comment;
public $found_posts = 0;
public $max_num_pages = 0;
public $max_num_comment_pages = 0;
public $is_single = false; β
public $is_preview = false; β
public $is_page = false; β
public $is_archive = false; β
public $is_date = false; β
public $is_year = false; β
public $is_month = false; β
public $is_day = false; β
public $is_time = false; β
public $is_author = false; β
public $is_category = false; β
public $is_tag = false;
public $is_tax = false;
public $is_search = false; β
public $is_feed = false; β
public $is_comment_feed = false;
public $is_trackback = false; β
public $is_home = false; β
public $is_404 = false; β
public $is_embed = false;
public $is_paged = false;
public $is_admin = false; β
public $is_attachment = false;
public $is_singular = false;
public $is_robots = false;
public $is_posts_page = false;
public $is_post_type_archive = false;
private $query_vars_hash = false;
private $query_vars_changed = true;
public $thumbnails_cached = false;
private $stopwords;
private $compat_fields = array('query_vars_hash', 'query_vars_changed');
private $compat_methods = array('init_query_flags', 'parse_tax_query');
private function init_query_flags()
```
`WP_Query` is the Swiss army knife.
===================================
Some things about `WP_Query`:
* it is something you can control via arguments you pass
* it is greedy by default
* it holds the substance for looping
* it is saved in the global space x2
* it can be primary or secondary
* it uses helper classes
* it has a handy `pre_get_posts` hook
* it even has support for nested loops
* it holds the SQL query string
* it holds the number of the results
* it holds the results
* it holds the list of all possible query arguments
* it holds the template flags
* ...
I cannot explain all these, but some of these are tricky, so let's provide short tips.
`WP_Query` is something you can control via arguments you pass
--------------------------------------------------------------
```
The list of the arguments
---
attachment
attachment_id
author
author__in
author__not_in
author_name
cache_results
cat
category__and
category__in
category__not_in
category_name
comments_per_page
day
embed
error
feed
fields
hour
ignore_sticky_posts
lazy_load_term_meta
m
menu_order
meta_key
meta_value
minute
monthnum
name
no_found_rows
nopaging
order
p
page_id
paged
pagename
post__in
post__not_in
post_name__in
post_parent
post_parent__in
post_parent__not_in
post_type
posts_per_page
preview
s
second
sentence
static
subpost
subpost_id
suppress_filters
tag
tag__and
tag__in
tag__not_in
tag_id
tag_slug__and
tag_slug__in
tb
title
update_post_meta_cache
update_post_term_cache
w
year
```
>
> This list from WordPress version 4.7 will certainly change in the future.
>
>
>
This would be the minimal example creating the `WP_Query` object from the arguments:
```
// WP_Query arguments
$args = array ( /* arguments*/ );
// creating the WP_Query object
$query = new WP_Query( $args );
// print full list of arguments WP_Query can take
print ( $query->query_vars );
```
`WP_Query` is greedy
--------------------
Created on the idea `get all you can` WordPress developers decided to get all possible data early as this is [good for the performance](http://wordpress.tv/2012/06/15/andrew-nacin-wp_query/).
This is why by default when the query takes 10 posts from the database it will also get the terms and the metadata for these posts via separate queries. Terms and metadata will be cached (prefetched).
>
> Note the caching is just for the single request lifetime.
>
>
>
You can disable the caching if you set `update_post_meta_cache` and `update_post_term_cache` to `false` while setting the `WP_Query` arguments. When caching is disabled the data will be requested from the database only on demand.
For the majority of WordPress blogs caching works well, but there are some occasions when you may disable the caching.
`WP_Query` uses helper classes
------------------------------
If you checked `WP_Query` fields there you have these three:
```
public $tax_query;
public $meta_query;
public $date_query;
```
You can imagine adding new in the future.
[](https://i.stack.imgur.com/3pHZb.png)
`WP_Query` holds the substance for looping
------------------------------------------
In this code:
```
$query = new WP_Query( $args )
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
```
you may notice the `WP_Query` has the substance you can iterate. The helper methods are there also. You just set the `while` loop.
>
> Note. `for` and `while` loops are semantically equivalent.
>
>
>
`WP_Query` primary and secondary
--------------------------------
In WordPress you have one **primary** and zero or more **secondary** queries.
>
> It is possible not to have the primary query, but this is beyond the scope of this article.
>
>
>
*Primary query* known as the *main query* or the *regular query*. *Secondary query* also called a *custom query*.
WordPress uses `WP_Rewrite` class early to create the query arguments based on the URL. Based on these arguments it stores the two identical objects in the global space. Both of these will hold the main query.
```
global $wp_query @since WordPress 1.5
global $wp_the_query @since WordPress 2.1
```
When we say *main query* we think of these variables. Other queries can be called secondary or custom.
>
> It is completely legal to use either `global $wp_query` or `$GLOBALS['wp_query']`, but using the second notation is much more notable, and saves typing an extra line inside the scope of the functions.
>
>
> `$GLOBALS['wp_query']` and `$GLOBALS['wp_the_query']` are separate objects. `$GLOBALS['wp_the_query']` should remain frozen.
>
>
>
`WP_Query` has the handy `pre_get_posts` hook.
----------------------------------------------
This is the action hook. It will apply to **any** `WP_Query` instance. You call it like:
```
add_action( 'pre_get_posts', function($query){
if ( is_category() && $query->is_main_query() ) {
// set your improved arguments
$query->set( ... );
...
}
return $query;
});
```
This hook is great and it can alter any query arguments.
Here is what you can [read](https://wpseek.com/hook/pre_get_posts/):
>
> Fires after the query variable object is created, but before the actual query is run.
>
>
>
So this hook is arguments manager but cannot create new `WP_Query` objects. If you had one primary and one secondary query, `pre_get_posts` cannot create the third one. Or if you just had one primary it cannot create the secondary.
>
> Note in case you need to alter the main query only you can use the `request` hook also.
>
>
>
`WP_Query` supports nested loops
--------------------------------
>
> This scenario may happen if you use plugins, and you call plugin functions from the template.
>
>
>
Here is the showcase example WordPress have helper functions even for the nested loops:
```
global $id;
while ( have_posts() ) : the_post();
// the custom $query
$query = new WP_Query( array( 'posts_per_page' => 5 ) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) : $query->the_post();
echo '<li>Custom ' . $id . '. ' . get_the_title() . '</li>';
endwhile;
}
wp_reset_postdata();
echo '<li>Main Query ' . $id . '. ' . get_the_title() . '</li>';
endwhile;
```
The output will be like this since I installed [theme unit test data](https://codex.wordpress.org/Theme_Unit_Test):
```
Custom 100. Template: Sticky
Custom 1. Hello world!
Custom 10. Markup: HTML Tags and Formatting
Custom 11. Markup: Image Alignment
Custom 12. Markup: Text Alignment
Custom 13. Markup: Title With Special Characters
Main Query 1. Hello world!
```
Even though I requested 5 posts in the custom $query it will return me six, because the sticky post will go along.
If there no `wp_reset_postdata` in the previous example the output will be like this, because of the `$GLOBALS['post']` will be invalid.
```
Custom 1001. Template: Sticky
Custom 1. Hello world!
Custom 10. Markup: HTML Tags and Formatting
Custom 11. Markup: Image Alignment
Custom 12. Markup: Text Alignment
Custom 13. Markup: Title With Special Characters
Main Query 13. Markup: Title With Special Characters
```
`WP_Query` has `wp_reset_query` function
----------------------------------------
This is like a reset button. `$GLOBALS['wp_the_query']` should be frozen all the time, and plugins or themes should never alter it.
Here is what `wp_reset_query` do:
```
function wp_reset_query() {
$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
wp_reset_postdata();
}
```
Remarks on `get_posts`
======================
`get_posts` looks like
```
File: /wp-includes/post.php
1661: function get_posts( $args = null ) {
1662: $defaults = array(
1663: 'numberposts' => 5,
1664: 'category' => 0, 'orderby' => 'date',
1665: 'order' => 'DESC', 'include' => array(),
1666: 'exclude' => array(), 'meta_key' => '',
1667: 'meta_value' =>'', 'post_type' => 'post',
1668: 'suppress_filters' => true
1669: );
... // do some argument parsing
1685: $r['ignore_sticky_posts'] = true;
1686: $r['no_found_rows'] = true;
1687:
1688: $get_posts = new WP_Query;
1689: return $get_posts->query($r);
```
>
> The line numbers may change in the future.
>
>
>
It is just a **wrapper** around `WP_Query` that **returns** the query object posts.
The `ignore_sticky_posts` set to true means the sticky posts may show up only in a natural position. There will be no sticky posts in the front. The other `no_found_rows` set to true means WordPress database API will not use `SQL_CALC_FOUND_ROWS` in order to implement pagination, reducing the load on the database to execute *found rows* count.
This is handy when you don't need pagination. We understand now we can mimic this function with this query:
```
$args = array ( 'ignore_sticky_posts' => true, 'no_found_rows' => true);
$query = new WP_Query( $args );
print( $query->request );
```
Here is the corresponding SQL request:
```
SELECT wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 10
```
Compare what we have now with the previous SQL request where `SQL_CALC_FOUND_ROWS` exists.
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 10
```
The request without `SQL_CALC_FOUND_ROWS` will be faster.
Remarks on `query_posts`
========================
>
> Tip: At first in 2004 there was only `global $wp_query`. As of WordPress 2.1 version `$wp_the_query` came.
> Tip: `$GLOBALS['wp_query']` and `$GLOBALS['wp_the_query']` are separate objects.
>
>
>
`query_posts()` is `WP_Query` wrapper. It returns the reference to the main `WP_Query` object, and at the same time it will set the `global $wp_query`.
```
File: /wp-includes/query.php
function query_posts($args) {
$GLOBALS['wp_query'] = new WP_Query();
return $GLOBALS['wp_query']->query($args);
}
```
In PHP4 everything, including objects, was passed by value. `query_posts` was like this:
```
File: /wp-includes/query.php (WordPress 3.1)
function &query_posts($args) {
unset($GLOBALS['wp_query']);
$GLOBALS['wp_query'] =& new WP_Query();
return $GLOBALS['wp_query']->query($args);
}
```
Please note in typical scenario with one primary and one secondary query we have these three variables:
```
$GLOBALS['wp_the_query']
$GLOBALS['wp_query'] // should be the copy of first one
$custom_query // secondary
```
Let's say each of these three takes 1M of memory. Total would be 3M of memory.
If we use `query_posts`, `$GLOBALS['wp_query']` will be unset and created again.
PHP5+ should be smart emptying the `$GLOBALS['wp_query']` object, just like in PHP4 we did it with the `unset($GLOBALS['wp_query']);`
```
function query_posts($args) {
$GLOBALS['wp_query'] = new WP_Query();
return $GLOBALS['wp_query']->query($args);
}
```
As a result `query_posts` consumes 2M of memory in total, while `get_posts` consumes 3M of memory.
Note in `query_posts` we are not returning the actual object, but a reference to the object.
>
> From [php.net](http://php.net/manual/en/language.oop5.references.php):
> A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.
>
>
> Also in PHP5+ the assign (=) operator is smart. It will use **shallow** copy and not hard object copy. When we write like this `$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];` only the data will be copied, not the whole object since these share the same object type.
>
>
>
Here is one example
```
print( md5(serialize($GLOBALS['wp_the_query']) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
query_posts( '' );
print( md5(serialize($GLOBALS['wp_the_query']) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
```
Will result:
```
f14153cab65abf1ea23224a1068563ef
f14153cab65abf1ea23224a1068563ef
f14153cab65abf1ea23224a1068563ef
d6db1c6bfddac328442e91b6059210b5
```
Try to reset the query:
```
print( md5(serialize($GLOBALS['wp_the_query'] ) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
query_posts( '' );
wp_reset_query();
print( md5(serialize($GLOBALS['wp_the_query'] ) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
```
Will result:
```
f14153cab65abf1ea23224a1068563ef
f14153cab65abf1ea23224a1068563ef
f14153cab65abf1ea23224a1068563ef
f14153cab65abf1ea23224a1068563ef
```
You can create problems even if you use `WP_Query`
```
print( md5(serialize($GLOBALS['wp_the_query'] ) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
global $wp_query;
$wp_query = new WP_Query( array( 'post_type' => 'post' ) );
print( md5(serialize($GLOBALS['wp_the_query'] ) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
```
Of course, the solution would be to use `wp_reset_query` function again.
```
print( md5(serialize($GLOBALS['wp_the_query'] ) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
global $wp_query;
$wp_query = new WP_Query( array( 'post_type' => 'post' ) );
wp_reset_query();
print( md5(serialize($GLOBALS['wp_the_query'] ) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
```
This is why I think `query_posts` may be better from the memory standpoint. But you should always do `wp_reset_query` trick.
|
226,979 |
<p>Is it possible to have two different blog layouts in the same theme? They would pull the same posts, but have a different layout structure. The only idea I've had is making a couple custom page templates that pull blog posts but have different structure/styles. Is there something simple I am missing? </p>
<p>The reasoning is to have one version of the posts (which are educational) that displays a lot of the excerpt and images in the blog index and then a different version that is more succinct for a review printout.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 226992,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": false,
"text": "<p>I have just created a new trac ticket, <a href=\"https://core.trac.wordpress.org/ticket/36874\" rel=\"nofollow noreferrer\">ticket #36874</a>, to propose the deprecation of <code>query_posts()</code>. Whether or not it will be accepted remains a good question. </p>\n\n<p>The real big issue with <code>query_posts()</code> is, it is still widely used by plugins and themes, even though there have been really good writings on the subject of why you should <strong>NEVER EVER</strong> use it. I think the most epic post here on WPSE is the following one:</p>\n\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/q/1753/31545\">When should you use WP_Query vs query_posts() vs get_posts()?</a></li>\n</ul>\n\n<p><em>deprecation !== removal</em>, so deprecating <code>query_posts()</code> will not stop its usage by poor quality devs and people in general who do not know WordPress and who use poor quality tutorials as guidelines. Just as some proof, how many questions do we still get here where people use <code>caller_get_posts</code> in <code>WP_Query</code>? It has been deprecated for many years now.</p>\n\n<p>Deprecated functions and arguments can however be removed at any time the core devs see fit, but this will most probably never happen with <code>query_posts()</code> as this will break millions of sites. So yes, we will probably never see the total removal of <code>query_posts()</code> - which might lead to the fact that it will most probably never get deprecated.</p>\n\n<p>This is a starting point though, but one has to remember, deprecating something in WordPress does not stop its use.</p>\n\n<h1>UPDATE 19 May 2016</h1>\n\n<p>The ticket I raised is now closed and marked as duplicate to a <strong><em>4 year old</em></strong> ticket, which was closed as <em>wontfix</em> and was reopened and still remain open and unresolved.</p>\n\n<p>Seems the core developers are hanging on to this old faithful little evil. Everyone interested, here is the duplicate 4year old ticket</p>\n\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/19631\" rel=\"nofollow noreferrer\">trac ticket #19631</a></li>\n</ul>\n"
},
{
"answer_id": 227238,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>[somewhat rant]</p>\n\n<p>It is the standing core philosophy at this point that nothing is truly deprecated. Deprecation notice, while it is a nice to have, is just going to be ignored if the function will not actually be dropped at some point. There are many people that do not develop with <code>WP_DEBUG</code> on and will not notice the notice if there will not be an actual breakage.</p>\n\n<p>OTOH hand, this function is like <code>goto</code> statement. Personally I never (for smaller definition then expected) used <code>goto</code>but I can understand the arguments pointing to some situation in which it is not evil by default. Same goes with <code>query_posts</code>, it is a simple way to set up all the globals required to make a simple loop, and can be useful in ajax or rest-api context. I would never use it in those contexts as well, but I can see that there, it is more of an issue of style of coding then a function being evil by itself.</p>\n\n<p>Going a little deeper, the main problem is that globals need to be set at all. That is the main problem not the one function that helps setting them.</p>\n"
},
{
"answer_id": 248955,
"author": "prosti",
"author_id": 88606,
"author_profile": "https://wordpress.stackexchange.com/users/88606",
"pm_score": 5,
"selected": true,
"text": "<h1>Essential question</h1>\n\n<p>Let's dig into the trio: <code>::query_posts</code>, <code>::get_posts</code> and <code>class WP_Query</code> to understand <code>::query_posts</code> better.</p>\n\n<p>The cornerstone for getting the data in WordPress is the <code>WP_Query</code> class. Both methods <code>::query_posts</code> and <code>::get_posts</code> use that class. </p>\n\n<blockquote>\n <p>Note that the class <code>WP_Query</code> also contains the methods with the same name: <code>WP_Query::query_posts</code> and <code>WP_Query::get_posts</code>, but we actually only consider the global methods, so don't get confused.</p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/gIk6t.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gIk6t.png\" alt=\"enter image description here\"></a></p>\n\n<h1>Understanding the <code>WP_Query</code></h1>\n\n<blockquote>\n <p>The class called <code>WP_Query</code> has been introduced back in 2004. All fields having the β (umbrella) mark where present back in 2004. The additional fields were added later.</p>\n</blockquote>\n\n<p>Here is the <code>WP_Query</code> structure:</p>\n\n<pre><code>class WP_Query (as in WordPress v4.7) \n public $query; β\n public $query_vars = array(); β\n public $tax_query;\n public $meta_query = false;\n public $date_query = false;\n public $queried_object; β\n public $queried_object_id; β\n public $request;\n public $posts; β\n public $post_count = 0; β\n public $current_post = -1; β\n public $in_the_loop = false;\n public $post; β\n public $comments;\n public $comment_count = 0;\n public $current_comment = -1;\n public $comment;\n public $found_posts = 0;\n public $max_num_pages = 0;\n public $max_num_comment_pages = 0;\n public $is_single = false; β\n public $is_preview = false; β\n public $is_page = false; β\n public $is_archive = false; β\n public $is_date = false; β\n public $is_year = false; β\n public $is_month = false; β\n public $is_day = false; β\n public $is_time = false; β\n public $is_author = false; β\n public $is_category = false; β\n public $is_tag = false;\n public $is_tax = false;\n public $is_search = false; β\n public $is_feed = false; β\n public $is_comment_feed = false;\n public $is_trackback = false; β\n public $is_home = false; β\n public $is_404 = false; β\n public $is_embed = false;\n public $is_paged = false;\n public $is_admin = false; β\n public $is_attachment = false;\n public $is_singular = false;\n public $is_robots = false;\n public $is_posts_page = false;\n public $is_post_type_archive = false;\n private $query_vars_hash = false;\n private $query_vars_changed = true;\n public $thumbnails_cached = false;\n private $stopwords;\n private $compat_fields = array('query_vars_hash', 'query_vars_changed');\n private $compat_methods = array('init_query_flags', 'parse_tax_query');\n private function init_query_flags()\n</code></pre>\n\n<h1><code>WP_Query</code> is the Swiss army knife.</h1>\n\n<p>Some things about <code>WP_Query</code>:</p>\n\n<ul>\n<li>it is something you can control via arguments you pass</li>\n<li>it is greedy by default</li>\n<li>it holds the substance for looping</li>\n<li>it is saved in the global space x2</li>\n<li>it can be primary or secondary</li>\n<li>it uses helper classes</li>\n<li>it has a handy <code>pre_get_posts</code> hook</li>\n<li>it even has support for nested loops</li>\n<li>it holds the SQL query string</li>\n<li>it holds the number of the results</li>\n<li>it holds the results</li>\n<li>it holds the list of all possible query arguments</li>\n<li>it holds the template flags</li>\n<li>...</li>\n</ul>\n\n<p>I cannot explain all these, but some of these are tricky, so let's provide short tips.</p>\n\n<h2><code>WP_Query</code> is something you can control via arguments you pass</h2>\n\n<pre><code>The list of the arguments\n---\n attachment\n attachment_id\n author\n author__in\n author__not_in\n author_name\n cache_results\n cat\n category__and\n category__in\n category__not_in\n category_name\n comments_per_page\n day\n embed\n error\n feed\n fields\n hour\n ignore_sticky_posts\n lazy_load_term_meta\n m\n menu_order\n meta_key\n meta_value\n minute\n monthnum\n name\n no_found_rows\n nopaging\n order\n p\n page_id\n paged\n pagename\n post__in\n post__not_in\n post_name__in\n post_parent\n post_parent__in\n post_parent__not_in\n post_type\n posts_per_page\n preview\n s\n second\n sentence\n static\n subpost\n subpost_id\n suppress_filters\n tag\n tag__and\n tag__in\n tag__not_in\n tag_id\n tag_slug__and\n tag_slug__in\n tb\n title\n update_post_meta_cache\n update_post_term_cache\n w\n year\n</code></pre>\n\n<blockquote>\n <p>This list from WordPress version 4.7 will certainly change in the future. </p>\n</blockquote>\n\n<p>This would be the minimal example creating the <code>WP_Query</code> object from the arguments:</p>\n\n<pre><code>// WP_Query arguments\n$args = array ( /* arguments*/ );\n// creating the WP_Query object\n$query = new WP_Query( $args );\n// print full list of arguments WP_Query can take\nprint ( $query->query_vars );\n</code></pre>\n\n<h2><code>WP_Query</code> is greedy</h2>\n\n<p>Created on the idea <code>get all you can</code> WordPress developers decided to get all possible data early as this is <a href=\"http://wordpress.tv/2012/06/15/andrew-nacin-wp_query/\" rel=\"noreferrer\">good for the performance</a>.\nThis is why by default when the query takes 10 posts from the database it will also get the terms and the metadata for these posts via separate queries. Terms and metadata will be cached (prefetched).</p>\n\n<blockquote>\n <p>Note the caching is just for the single request lifetime.</p>\n</blockquote>\n\n<p>You can disable the caching if you set <code>update_post_meta_cache</code> and <code>update_post_term_cache</code> to <code>false</code> while setting the <code>WP_Query</code> arguments. When caching is disabled the data will be requested from the database only on demand.</p>\n\n<p>For the majority of WordPress blogs caching works well, but there are some occasions when you may disable the caching.</p>\n\n<h2><code>WP_Query</code> uses helper classes</h2>\n\n<p>If you checked <code>WP_Query</code> fields there you have these three:</p>\n\n<pre><code>public $tax_query;\npublic $meta_query;\npublic $date_query;\n</code></pre>\n\n<p>You can imagine adding new in the future.</p>\n\n<p><a href=\"https://i.stack.imgur.com/3pHZb.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3pHZb.png\" alt=\"enter image description here\"></a></p>\n\n<h2><code>WP_Query</code> holds the substance for looping</h2>\n\n<p>In this code:</p>\n\n<pre><code>$query = new WP_Query( $args )\nif ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n $query->the_post();\n</code></pre>\n\n<p>you may notice the <code>WP_Query</code> has the substance you can iterate. The helper methods are there also. You just set the <code>while</code> loop.</p>\n\n<blockquote>\n <p>Note. <code>for</code> and <code>while</code> loops are semantically equivalent.</p>\n</blockquote>\n\n<h2><code>WP_Query</code> primary and secondary</h2>\n\n<p>In WordPress you have one <strong>primary</strong> and zero or more <strong>secondary</strong> queries.</p>\n\n<blockquote>\n <p>It is possible not to have the primary query, but this is beyond the scope of this article. </p>\n</blockquote>\n\n<p><em>Primary query</em> known as the <em>main query</em> or the <em>regular query</em>. <em>Secondary query</em> also called a <em>custom query</em>.</p>\n\n<p>WordPress uses <code>WP_Rewrite</code> class early to create the query arguments based on the URL. Based on these arguments it stores the two identical objects in the global space. Both of these will hold the main query.</p>\n\n<pre><code>global $wp_query @since WordPress 1.5\nglobal $wp_the_query @since WordPress 2.1\n</code></pre>\n\n<p>When we say <em>main query</em> we think of these variables. Other queries can be called secondary or custom.</p>\n\n<blockquote>\n <p>It is completely legal to use either <code>global $wp_query</code> or <code>$GLOBALS['wp_query']</code>, but using the second notation is much more notable, and saves typing an extra line inside the scope of the functions.</p>\n \n <p><code>$GLOBALS['wp_query']</code> and <code>$GLOBALS['wp_the_query']</code> are separate objects. <code>$GLOBALS['wp_the_query']</code> should remain frozen. </p>\n</blockquote>\n\n<h2><code>WP_Query</code> has the handy <code>pre_get_posts</code> hook.</h2>\n\n<p>This is the action hook. It will apply to <strong>any</strong> <code>WP_Query</code> instance. You call it like: </p>\n\n<pre><code>add_action( 'pre_get_posts', function($query){\n\n if ( is_category() && $query->is_main_query() ) {\n // set your improved arguments\n $query->set( ... ); \n ... \n }\n\n return $query; \n});\n</code></pre>\n\n<p>This hook is great and it can alter any query arguments.</p>\n\n<p>Here is what you can <a href=\"https://wpseek.com/hook/pre_get_posts/\" rel=\"noreferrer\">read</a>:</p>\n\n<blockquote>\n <p>Fires after the query variable object is created, but before the actual query is run.</p>\n</blockquote>\n\n<p>So this hook is arguments manager but cannot create new <code>WP_Query</code> objects. If you had one primary and one secondary query, <code>pre_get_posts</code> cannot create the third one. Or if you just had one primary it cannot create the secondary.</p>\n\n<blockquote>\n <p>Note in case you need to alter the main query only you can use the <code>request</code> hook also.</p>\n</blockquote>\n\n<h2><code>WP_Query</code> supports nested loops</h2>\n\n<blockquote>\n <p>This scenario may happen if you use plugins, and you call plugin functions from the template.</p>\n</blockquote>\n\n<p>Here is the showcase example WordPress have helper functions even for the nested loops:</p>\n\n<pre><code>global $id;\nwhile ( have_posts() ) : the_post(); \n\n // the custom $query\n $query = new WP_Query( array( 'posts_per_page' => 5 ) ); \n if ( $query->have_posts() ) {\n\n while ( $query->have_posts() ) : $query->the_post(); \n echo '<li>Custom ' . $id . '. ' . get_the_title() . '</li>';\n endwhile; \n } \n\n wp_reset_postdata();\n echo '<li>Main Query ' . $id . '. ' . get_the_title() . '</li>';\n\nendwhile;\n</code></pre>\n\n<p>The output will be like this since I installed <a href=\"https://codex.wordpress.org/Theme_Unit_Test\" rel=\"noreferrer\">theme unit test data</a>:</p>\n\n<pre><code>Custom 100. Template: Sticky\nCustom 1. Hello world!\nCustom 10. Markup: HTML Tags and Formatting\nCustom 11. Markup: Image Alignment\nCustom 12. Markup: Text Alignment\nCustom 13. Markup: Title With Special Characters\nMain Query 1. Hello world!\n</code></pre>\n\n<p>Even though I requested 5 posts in the custom $query it will return me six, because the sticky post will go along. \nIf there no <code>wp_reset_postdata</code> in the previous example the output will be like this, because of the <code>$GLOBALS['post']</code> will be invalid.</p>\n\n<pre><code>Custom 1001. Template: Sticky\nCustom 1. Hello world!\nCustom 10. Markup: HTML Tags and Formatting\nCustom 11. Markup: Image Alignment\nCustom 12. Markup: Text Alignment\nCustom 13. Markup: Title With Special Characters\nMain Query 13. Markup: Title With Special Characters\n</code></pre>\n\n<h2><code>WP_Query</code> has <code>wp_reset_query</code> function</h2>\n\n<p>This is like a reset button. <code>$GLOBALS['wp_the_query']</code> should be frozen all the time, and plugins or themes should never alter it.</p>\n\n<p>Here is what <code>wp_reset_query</code> do:</p>\n\n<pre><code>function wp_reset_query() {\n $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];\n wp_reset_postdata();\n}\n</code></pre>\n\n<h1>Remarks on <code>get_posts</code></h1>\n\n<p><code>get_posts</code> looks like</p>\n\n<pre><code>File: /wp-includes/post.php\n1661: function get_posts( $args = null ) {\n1662: $defaults = array(\n1663: 'numberposts' => 5,\n1664: 'category' => 0, 'orderby' => 'date',\n1665: 'order' => 'DESC', 'include' => array(),\n1666: 'exclude' => array(), 'meta_key' => '',\n1667: 'meta_value' =>'', 'post_type' => 'post',\n1668: 'suppress_filters' => true\n1669: );\n... // do some argument parsing\n1685: $r['ignore_sticky_posts'] = true;\n1686: $r['no_found_rows'] = true;\n1687: \n1688: $get_posts = new WP_Query;\n1689: return $get_posts->query($r);\n</code></pre>\n\n<blockquote>\n <p>The line numbers may change in the future.</p>\n</blockquote>\n\n<p>It is just a <strong>wrapper</strong> around <code>WP_Query</code> that <strong>returns</strong> the query object posts.</p>\n\n<p>The <code>ignore_sticky_posts</code> set to true means the sticky posts may show up only in a natural position. There will be no sticky posts in the front. The other <code>no_found_rows</code> set to true means WordPress database API will not use <code>SQL_CALC_FOUND_ROWS</code> in order to implement pagination, reducing the load on the database to execute <em>found rows</em> count.</p>\n\n<p>This is handy when you don't need pagination. We understand now we can mimic this function with this query:</p>\n\n<pre><code>$args = array ( 'ignore_sticky_posts' => true, 'no_found_rows' => true);\n$query = new WP_Query( $args );\nprint( $query->request );\n</code></pre>\n\n<p>Here is the corresponding SQL request:</p>\n\n<pre><code>SELECT wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 10\n</code></pre>\n\n<p>Compare what we have now with the previous SQL request where <code>SQL_CALC_FOUND_ROWS</code> exists. </p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 10\n</code></pre>\n\n<p>The request without <code>SQL_CALC_FOUND_ROWS</code> will be faster.</p>\n\n<h1>Remarks on <code>query_posts</code></h1>\n\n<blockquote>\n <p>Tip: At first in 2004 there was only <code>global $wp_query</code>. As of WordPress 2.1 version <code>$wp_the_query</code> came.\n Tip: <code>$GLOBALS['wp_query']</code> and <code>$GLOBALS['wp_the_query']</code> are separate objects.</p>\n</blockquote>\n\n<p><code>query_posts()</code> is <code>WP_Query</code> wrapper. It returns the reference to the main <code>WP_Query</code> object, and at the same time it will set the <code>global $wp_query</code>.</p>\n\n<pre><code>File: /wp-includes/query.php\nfunction query_posts($args) {\n $GLOBALS['wp_query'] = new WP_Query();\n return $GLOBALS['wp_query']->query($args);\n}\n</code></pre>\n\n<p>In PHP4 everything, including objects, was passed by value. <code>query_posts</code> was like this:</p>\n\n<pre><code>File: /wp-includes/query.php (WordPress 3.1)\nfunction &query_posts($args) {\n unset($GLOBALS['wp_query']);\n $GLOBALS['wp_query'] =& new WP_Query();\n return $GLOBALS['wp_query']->query($args);\n}\n</code></pre>\n\n<p>Please note in typical scenario with one primary and one secondary query we have these three variables:</p>\n\n<pre><code>$GLOBALS['wp_the_query'] \n$GLOBALS['wp_query'] // should be the copy of first one\n$custom_query // secondary\n</code></pre>\n\n<p>Let's say each of these three takes 1M of memory. Total would be 3M of memory.\nIf we use <code>query_posts</code>, <code>$GLOBALS['wp_query']</code> will be unset and created again.</p>\n\n<p>PHP5+ should be smart emptying the <code>$GLOBALS['wp_query']</code> object, just like in PHP4 we did it with the <code>unset($GLOBALS['wp_query']);</code></p>\n\n<pre><code>function query_posts($args) {\n $GLOBALS['wp_query'] = new WP_Query();\n return $GLOBALS['wp_query']->query($args);\n}\n</code></pre>\n\n<p>As a result <code>query_posts</code> consumes 2M of memory in total, while <code>get_posts</code> consumes 3M of memory.</p>\n\n<p>Note in <code>query_posts</code> we are not returning the actual object, but a reference to the object.</p>\n\n<blockquote>\n <p>From <a href=\"http://php.net/manual/en/language.oop5.references.php\" rel=\"noreferrer\">php.net</a>:\n A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.</p>\n \n <p>Also in PHP5+ the assign (=) operator is smart. It will use <strong>shallow</strong> copy and not hard object copy. When we write like this <code>$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];</code> only the data will be copied, not the whole object since these share the same object type.</p>\n</blockquote>\n\n<p>Here is one example</p>\n\n<pre><code>print( md5(serialize($GLOBALS['wp_the_query']) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\nquery_posts( '' );\nprint( md5(serialize($GLOBALS['wp_the_query']) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\n</code></pre>\n\n<p>Will result:</p>\n\n<pre><code>f14153cab65abf1ea23224a1068563ef\nf14153cab65abf1ea23224a1068563ef\nf14153cab65abf1ea23224a1068563ef\nd6db1c6bfddac328442e91b6059210b5\n</code></pre>\n\n<p>Try to reset the query:</p>\n\n<pre><code>print( md5(serialize($GLOBALS['wp_the_query'] ) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\nquery_posts( '' );\nwp_reset_query();\nprint( md5(serialize($GLOBALS['wp_the_query'] ) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\n</code></pre>\n\n<p>Will result:</p>\n\n<pre><code>f14153cab65abf1ea23224a1068563ef\nf14153cab65abf1ea23224a1068563ef\nf14153cab65abf1ea23224a1068563ef\nf14153cab65abf1ea23224a1068563ef\n</code></pre>\n\n<p>You can create problems even if you use <code>WP_Query</code></p>\n\n<pre><code>print( md5(serialize($GLOBALS['wp_the_query'] ) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\nglobal $wp_query;\n$wp_query = new WP_Query( array( 'post_type' => 'post' ) ); \nprint( md5(serialize($GLOBALS['wp_the_query'] ) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\n</code></pre>\n\n<p>Of course, the solution would be to use <code>wp_reset_query</code> function again.</p>\n\n<pre><code>print( md5(serialize($GLOBALS['wp_the_query'] ) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\nglobal $wp_query;\n$wp_query = new WP_Query( array( 'post_type' => 'post' ) );\nwp_reset_query();\nprint( md5(serialize($GLOBALS['wp_the_query'] ) ) );\nprint( md5(serialize($GLOBALS['wp_query'] ) ) );\n</code></pre>\n\n<p>This is why I think <code>query_posts</code> may be better from the memory standpoint. But you should always do <code>wp_reset_query</code> trick.</p>\n"
}
] |
2016/05/18
|
[
"https://wordpress.stackexchange.com/questions/226979",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64173/"
] |
Is it possible to have two different blog layouts in the same theme? They would pull the same posts, but have a different layout structure. The only idea I've had is making a couple custom page templates that pull blog posts but have different structure/styles. Is there something simple I am missing?
The reasoning is to have one version of the posts (which are educational) that displays a lot of the excerpt and images in the blog index and then a different version that is more succinct for a review printout.
Thanks.
|
Essential question
==================
Let's dig into the trio: `::query_posts`, `::get_posts` and `class WP_Query` to understand `::query_posts` better.
The cornerstone for getting the data in WordPress is the `WP_Query` class. Both methods `::query_posts` and `::get_posts` use that class.
>
> Note that the class `WP_Query` also contains the methods with the same name: `WP_Query::query_posts` and `WP_Query::get_posts`, but we actually only consider the global methods, so don't get confused.
>
>
>
[](https://i.stack.imgur.com/gIk6t.png)
Understanding the `WP_Query`
============================
>
> The class called `WP_Query` has been introduced back in 2004. All fields having the β (umbrella) mark where present back in 2004. The additional fields were added later.
>
>
>
Here is the `WP_Query` structure:
```
class WP_Query (as in WordPress v4.7)
public $query; β
public $query_vars = array(); β
public $tax_query;
public $meta_query = false;
public $date_query = false;
public $queried_object; β
public $queried_object_id; β
public $request;
public $posts; β
public $post_count = 0; β
public $current_post = -1; β
public $in_the_loop = false;
public $post; β
public $comments;
public $comment_count = 0;
public $current_comment = -1;
public $comment;
public $found_posts = 0;
public $max_num_pages = 0;
public $max_num_comment_pages = 0;
public $is_single = false; β
public $is_preview = false; β
public $is_page = false; β
public $is_archive = false; β
public $is_date = false; β
public $is_year = false; β
public $is_month = false; β
public $is_day = false; β
public $is_time = false; β
public $is_author = false; β
public $is_category = false; β
public $is_tag = false;
public $is_tax = false;
public $is_search = false; β
public $is_feed = false; β
public $is_comment_feed = false;
public $is_trackback = false; β
public $is_home = false; β
public $is_404 = false; β
public $is_embed = false;
public $is_paged = false;
public $is_admin = false; β
public $is_attachment = false;
public $is_singular = false;
public $is_robots = false;
public $is_posts_page = false;
public $is_post_type_archive = false;
private $query_vars_hash = false;
private $query_vars_changed = true;
public $thumbnails_cached = false;
private $stopwords;
private $compat_fields = array('query_vars_hash', 'query_vars_changed');
private $compat_methods = array('init_query_flags', 'parse_tax_query');
private function init_query_flags()
```
`WP_Query` is the Swiss army knife.
===================================
Some things about `WP_Query`:
* it is something you can control via arguments you pass
* it is greedy by default
* it holds the substance for looping
* it is saved in the global space x2
* it can be primary or secondary
* it uses helper classes
* it has a handy `pre_get_posts` hook
* it even has support for nested loops
* it holds the SQL query string
* it holds the number of the results
* it holds the results
* it holds the list of all possible query arguments
* it holds the template flags
* ...
I cannot explain all these, but some of these are tricky, so let's provide short tips.
`WP_Query` is something you can control via arguments you pass
--------------------------------------------------------------
```
The list of the arguments
---
attachment
attachment_id
author
author__in
author__not_in
author_name
cache_results
cat
category__and
category__in
category__not_in
category_name
comments_per_page
day
embed
error
feed
fields
hour
ignore_sticky_posts
lazy_load_term_meta
m
menu_order
meta_key
meta_value
minute
monthnum
name
no_found_rows
nopaging
order
p
page_id
paged
pagename
post__in
post__not_in
post_name__in
post_parent
post_parent__in
post_parent__not_in
post_type
posts_per_page
preview
s
second
sentence
static
subpost
subpost_id
suppress_filters
tag
tag__and
tag__in
tag__not_in
tag_id
tag_slug__and
tag_slug__in
tb
title
update_post_meta_cache
update_post_term_cache
w
year
```
>
> This list from WordPress version 4.7 will certainly change in the future.
>
>
>
This would be the minimal example creating the `WP_Query` object from the arguments:
```
// WP_Query arguments
$args = array ( /* arguments*/ );
// creating the WP_Query object
$query = new WP_Query( $args );
// print full list of arguments WP_Query can take
print ( $query->query_vars );
```
`WP_Query` is greedy
--------------------
Created on the idea `get all you can` WordPress developers decided to get all possible data early as this is [good for the performance](http://wordpress.tv/2012/06/15/andrew-nacin-wp_query/).
This is why by default when the query takes 10 posts from the database it will also get the terms and the metadata for these posts via separate queries. Terms and metadata will be cached (prefetched).
>
> Note the caching is just for the single request lifetime.
>
>
>
You can disable the caching if you set `update_post_meta_cache` and `update_post_term_cache` to `false` while setting the `WP_Query` arguments. When caching is disabled the data will be requested from the database only on demand.
For the majority of WordPress blogs caching works well, but there are some occasions when you may disable the caching.
`WP_Query` uses helper classes
------------------------------
If you checked `WP_Query` fields there you have these three:
```
public $tax_query;
public $meta_query;
public $date_query;
```
You can imagine adding new in the future.
[](https://i.stack.imgur.com/3pHZb.png)
`WP_Query` holds the substance for looping
------------------------------------------
In this code:
```
$query = new WP_Query( $args )
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
```
you may notice the `WP_Query` has the substance you can iterate. The helper methods are there also. You just set the `while` loop.
>
> Note. `for` and `while` loops are semantically equivalent.
>
>
>
`WP_Query` primary and secondary
--------------------------------
In WordPress you have one **primary** and zero or more **secondary** queries.
>
> It is possible not to have the primary query, but this is beyond the scope of this article.
>
>
>
*Primary query* known as the *main query* or the *regular query*. *Secondary query* also called a *custom query*.
WordPress uses `WP_Rewrite` class early to create the query arguments based on the URL. Based on these arguments it stores the two identical objects in the global space. Both of these will hold the main query.
```
global $wp_query @since WordPress 1.5
global $wp_the_query @since WordPress 2.1
```
When we say *main query* we think of these variables. Other queries can be called secondary or custom.
>
> It is completely legal to use either `global $wp_query` or `$GLOBALS['wp_query']`, but using the second notation is much more notable, and saves typing an extra line inside the scope of the functions.
>
>
> `$GLOBALS['wp_query']` and `$GLOBALS['wp_the_query']` are separate objects. `$GLOBALS['wp_the_query']` should remain frozen.
>
>
>
`WP_Query` has the handy `pre_get_posts` hook.
----------------------------------------------
This is the action hook. It will apply to **any** `WP_Query` instance. You call it like:
```
add_action( 'pre_get_posts', function($query){
if ( is_category() && $query->is_main_query() ) {
// set your improved arguments
$query->set( ... );
...
}
return $query;
});
```
This hook is great and it can alter any query arguments.
Here is what you can [read](https://wpseek.com/hook/pre_get_posts/):
>
> Fires after the query variable object is created, but before the actual query is run.
>
>
>
So this hook is arguments manager but cannot create new `WP_Query` objects. If you had one primary and one secondary query, `pre_get_posts` cannot create the third one. Or if you just had one primary it cannot create the secondary.
>
> Note in case you need to alter the main query only you can use the `request` hook also.
>
>
>
`WP_Query` supports nested loops
--------------------------------
>
> This scenario may happen if you use plugins, and you call plugin functions from the template.
>
>
>
Here is the showcase example WordPress have helper functions even for the nested loops:
```
global $id;
while ( have_posts() ) : the_post();
// the custom $query
$query = new WP_Query( array( 'posts_per_page' => 5 ) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) : $query->the_post();
echo '<li>Custom ' . $id . '. ' . get_the_title() . '</li>';
endwhile;
}
wp_reset_postdata();
echo '<li>Main Query ' . $id . '. ' . get_the_title() . '</li>';
endwhile;
```
The output will be like this since I installed [theme unit test data](https://codex.wordpress.org/Theme_Unit_Test):
```
Custom 100. Template: Sticky
Custom 1. Hello world!
Custom 10. Markup: HTML Tags and Formatting
Custom 11. Markup: Image Alignment
Custom 12. Markup: Text Alignment
Custom 13. Markup: Title With Special Characters
Main Query 1. Hello world!
```
Even though I requested 5 posts in the custom $query it will return me six, because the sticky post will go along.
If there no `wp_reset_postdata` in the previous example the output will be like this, because of the `$GLOBALS['post']` will be invalid.
```
Custom 1001. Template: Sticky
Custom 1. Hello world!
Custom 10. Markup: HTML Tags and Formatting
Custom 11. Markup: Image Alignment
Custom 12. Markup: Text Alignment
Custom 13. Markup: Title With Special Characters
Main Query 13. Markup: Title With Special Characters
```
`WP_Query` has `wp_reset_query` function
----------------------------------------
This is like a reset button. `$GLOBALS['wp_the_query']` should be frozen all the time, and plugins or themes should never alter it.
Here is what `wp_reset_query` do:
```
function wp_reset_query() {
$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
wp_reset_postdata();
}
```
Remarks on `get_posts`
======================
`get_posts` looks like
```
File: /wp-includes/post.php
1661: function get_posts( $args = null ) {
1662: $defaults = array(
1663: 'numberposts' => 5,
1664: 'category' => 0, 'orderby' => 'date',
1665: 'order' => 'DESC', 'include' => array(),
1666: 'exclude' => array(), 'meta_key' => '',
1667: 'meta_value' =>'', 'post_type' => 'post',
1668: 'suppress_filters' => true
1669: );
... // do some argument parsing
1685: $r['ignore_sticky_posts'] = true;
1686: $r['no_found_rows'] = true;
1687:
1688: $get_posts = new WP_Query;
1689: return $get_posts->query($r);
```
>
> The line numbers may change in the future.
>
>
>
It is just a **wrapper** around `WP_Query` that **returns** the query object posts.
The `ignore_sticky_posts` set to true means the sticky posts may show up only in a natural position. There will be no sticky posts in the front. The other `no_found_rows` set to true means WordPress database API will not use `SQL_CALC_FOUND_ROWS` in order to implement pagination, reducing the load on the database to execute *found rows* count.
This is handy when you don't need pagination. We understand now we can mimic this function with this query:
```
$args = array ( 'ignore_sticky_posts' => true, 'no_found_rows' => true);
$query = new WP_Query( $args );
print( $query->request );
```
Here is the corresponding SQL request:
```
SELECT wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 10
```
Compare what we have now with the previous SQL request where `SQL_CALC_FOUND_ROWS` exists.
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') ORDER BY wp_posts.post_date DESC LIMIT 0, 10
```
The request without `SQL_CALC_FOUND_ROWS` will be faster.
Remarks on `query_posts`
========================
>
> Tip: At first in 2004 there was only `global $wp_query`. As of WordPress 2.1 version `$wp_the_query` came.
> Tip: `$GLOBALS['wp_query']` and `$GLOBALS['wp_the_query']` are separate objects.
>
>
>
`query_posts()` is `WP_Query` wrapper. It returns the reference to the main `WP_Query` object, and at the same time it will set the `global $wp_query`.
```
File: /wp-includes/query.php
function query_posts($args) {
$GLOBALS['wp_query'] = new WP_Query();
return $GLOBALS['wp_query']->query($args);
}
```
In PHP4 everything, including objects, was passed by value. `query_posts` was like this:
```
File: /wp-includes/query.php (WordPress 3.1)
function &query_posts($args) {
unset($GLOBALS['wp_query']);
$GLOBALS['wp_query'] =& new WP_Query();
return $GLOBALS['wp_query']->query($args);
}
```
Please note in typical scenario with one primary and one secondary query we have these three variables:
```
$GLOBALS['wp_the_query']
$GLOBALS['wp_query'] // should be the copy of first one
$custom_query // secondary
```
Let's say each of these three takes 1M of memory. Total would be 3M of memory.
If we use `query_posts`, `$GLOBALS['wp_query']` will be unset and created again.
PHP5+ should be smart emptying the `$GLOBALS['wp_query']` object, just like in PHP4 we did it with the `unset($GLOBALS['wp_query']);`
```
function query_posts($args) {
$GLOBALS['wp_query'] = new WP_Query();
return $GLOBALS['wp_query']->query($args);
}
```
As a result `query_posts` consumes 2M of memory in total, while `get_posts` consumes 3M of memory.
Note in `query_posts` we are not returning the actual object, but a reference to the object.
>
> From [php.net](http://php.net/manual/en/language.oop5.references.php):
> A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.
>
>
> Also in PHP5+ the assign (=) operator is smart. It will use **shallow** copy and not hard object copy. When we write like this `$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];` only the data will be copied, not the whole object since these share the same object type.
>
>
>
Here is one example
```
print( md5(serialize($GLOBALS['wp_the_query']) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
query_posts( '' );
print( md5(serialize($GLOBALS['wp_the_query']) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
```
Will result:
```
f14153cab65abf1ea23224a1068563ef
f14153cab65abf1ea23224a1068563ef
f14153cab65abf1ea23224a1068563ef
d6db1c6bfddac328442e91b6059210b5
```
Try to reset the query:
```
print( md5(serialize($GLOBALS['wp_the_query'] ) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
query_posts( '' );
wp_reset_query();
print( md5(serialize($GLOBALS['wp_the_query'] ) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
```
Will result:
```
f14153cab65abf1ea23224a1068563ef
f14153cab65abf1ea23224a1068563ef
f14153cab65abf1ea23224a1068563ef
f14153cab65abf1ea23224a1068563ef
```
You can create problems even if you use `WP_Query`
```
print( md5(serialize($GLOBALS['wp_the_query'] ) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
global $wp_query;
$wp_query = new WP_Query( array( 'post_type' => 'post' ) );
print( md5(serialize($GLOBALS['wp_the_query'] ) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
```
Of course, the solution would be to use `wp_reset_query` function again.
```
print( md5(serialize($GLOBALS['wp_the_query'] ) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
global $wp_query;
$wp_query = new WP_Query( array( 'post_type' => 'post' ) );
wp_reset_query();
print( md5(serialize($GLOBALS['wp_the_query'] ) ) );
print( md5(serialize($GLOBALS['wp_query'] ) ) );
```
This is why I think `query_posts` may be better from the memory standpoint. But you should always do `wp_reset_query` trick.
|
226,990 |
<p>Is there a function, action or filter that I can use to add a third level drop-down menu to the WordPress admin menu.</p>
<p>For instance, right now in the sidebar menu, there is a menu for posts and under posts there are sub-menus for editing posts, adding a new post, categories, and tags. There is something similar for Pages.</p>
<p>What I would like to do is to add a menu item called Content and place underneath content Posts, Pages and my Custom Content Types and underneath each of those entries the relevant sub-menus (editing, adding, etc.).</p>
<p>I would like to do this through a custom plugin that I create. The problem is, I can't find any information on how to add a third-level sub-menu.</p>
<p>Any ideas?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 227002,
"author": "Karthikeyani Srijish",
"author_id": 86125,
"author_profile": "https://wordpress.stackexchange.com/users/86125",
"pm_score": 5,
"selected": true,
"text": "<p>No, it is not possible to create third level menu in admin panel. If you look at the definition of <strong>add_submenu_page</strong>, you need to mention the parent slug name. <strong>For eg:</strong></p>\n\n<pre><code>add_menu_page ( 'Test Menu', 'Test Menu', 'read', 'testmainmenu', '', '' );\nadd_submenu_page ( 'testmainmenu', 'Test Menu', 'Child1', 'read', 'child1', '');\n</code></pre>\n\n<p>The first parameter of the <strong>add_submenu_page</strong> will be parent slug name. So you may think we can write <strong>child1</strong> as <em>parent slug name</em> to create the third level. <strong>Eg:</strong></p>\n\n<pre><code>add_submenu_page ( 'child1', 'Test Menu', 'Child2', 'read', 'child2', '');\n</code></pre>\n\n<p>But this will not work. Look at the parameters definition and source section in this <a href=\"https://developer.wordpress.org/reference/functions/add_submenu_page/\" rel=\"noreferrer\">link</a>. It clearly states that, you can only use the name of '<strong>main menu of the plugin</strong>' or the <strong>file name</strong> of the WordPress plugin in <strong>parent slug name</strong>. So it is not possible to create submenus more than once in admin panel. However, you can create <em>n</em> number of sub menus in front end. To know more about creating menus and sub menus in front end, <a href=\"https://www.elegantthemes.com/blog/tips-tricks/how-to-create-custom-menu-structures-in-wordpress\" rel=\"noreferrer\">refer</a></p>\n"
},
{
"answer_id": 381236,
"author": "Olekk",
"author_id": 200125,
"author_profile": "https://wordpress.stackexchange.com/users/200125",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote it myself using JS. It's just for one project and I didn't want to spend much time on it, so you have to adjust it for your personal needs ;)</p>\n<p>It hides chosen menu elements and creates a button which toggles them.</p>\n<p>You add it to the end of file\n/wp-admin/menu-header.php</p>\n<pre><code><script>\n // Here is list of classes of chosen menu elements you want to toggle - li.menu-icon-slug\n let my_products = document.querySelectorAll("li.menu-icon-okna, li.menu-icon-drzwi, li.menu-icon-bramy_garazowe");\n \n my_products.forEach(prod => {\n prod.style.backgroundColor = "#283338";\n })\n \n // "Produkty" is a text on a toggling button, change it\n let my_button = jQuery('<li class="menu-top"><a class="menu-top"><div class="wp-menu-image dashicons-before dashicons-admin-post"></div><div class="wp-menu-name">Produkty</div></a></li>')[0];\n\n document.querySelector("ul#adminmenu").insertBefore(my_button, my_products[0]);\n\n function toggleProducts() {\n my_products.forEach(prod => {\n if(prod.style.display != "none") prod.style.display = "none";\n else prod.style.display = "block";\n })\n }\n toggleProducts();\n\n my_button.querySelector("a").addEventListener("click", toggleProducts);\n\n</script>\n\n</code></pre>\n<p>.\n.\nwith no jQuery:</p>\n<pre><code><script>\n // Here is list of classes of chosen menu elements you want to toggle - li.menu-icon-slug\n let my_products = document.querySelectorAll("li.menu-icon-okna, li.menu-icon-drzwi, li.menu-icon-bramy_garazowe");\n\n my_products.forEach(prod => {\n prod.style.backgroundColor = "#283338";\n })\n\n let prod_li = document.createElement("li");\n prod_li.classList.add("menu-top");\n\n let prod_a = document.createElement("a");\n prod_a.classList.add("menu-top");\n\n let prod_div1 = document.createElement("div");\n prod_div1.classList.add("wp-menu-image","dashicons-before","dashicons-admin-post")\n\n let prod_div2 = document.createElement("div");\n prod_div2.classList.add("wp-menu-name");\n\n // Text on a button:\n prod_div2.appendChild(document.createTextNode("Produkty"));\n\n prod_a.append(prod_div1, prod_div2);\n prod_li.append(prod_a);\n\n document.querySelector("ul#adminmenu").insertBefore(prod_li, my_products[0]);\n\n function toggleProducts() {\n my_products.forEach(prod => {\n if(prod.style.display != "none") prod.style.display = "none";\n else prod.style.display = "block";\n })\n }\n toggleProducts();\n\n prod_a.addEventListener("click", toggleProducts);\n\n</script>\n\n</code></pre>\n"
}
] |
2016/05/18
|
[
"https://wordpress.stackexchange.com/questions/226990",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94279/"
] |
Is there a function, action or filter that I can use to add a third level drop-down menu to the WordPress admin menu.
For instance, right now in the sidebar menu, there is a menu for posts and under posts there are sub-menus for editing posts, adding a new post, categories, and tags. There is something similar for Pages.
What I would like to do is to add a menu item called Content and place underneath content Posts, Pages and my Custom Content Types and underneath each of those entries the relevant sub-menus (editing, adding, etc.).
I would like to do this through a custom plugin that I create. The problem is, I can't find any information on how to add a third-level sub-menu.
Any ideas?
Thanks.
|
No, it is not possible to create third level menu in admin panel. If you look at the definition of **add\_submenu\_page**, you need to mention the parent slug name. **For eg:**
```
add_menu_page ( 'Test Menu', 'Test Menu', 'read', 'testmainmenu', '', '' );
add_submenu_page ( 'testmainmenu', 'Test Menu', 'Child1', 'read', 'child1', '');
```
The first parameter of the **add\_submenu\_page** will be parent slug name. So you may think we can write **child1** as *parent slug name* to create the third level. **Eg:**
```
add_submenu_page ( 'child1', 'Test Menu', 'Child2', 'read', 'child2', '');
```
But this will not work. Look at the parameters definition and source section in this [link](https://developer.wordpress.org/reference/functions/add_submenu_page/). It clearly states that, you can only use the name of '**main menu of the plugin**' or the **file name** of the WordPress plugin in **parent slug name**. So it is not possible to create submenus more than once in admin panel. However, you can create *n* number of sub menus in front end. To know more about creating menus and sub menus in front end, [refer](https://www.elegantthemes.com/blog/tips-tricks/how-to-create-custom-menu-structures-in-wordpress)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.