Created
May 6, 2020 01:47
Dynamic WP shortcodes from each post - custom post type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Load causing_forms_query() function after WP loads. | |
add_action( 'init', 'causing_forms_query' ); | |
function causing_forms_query() { | |
add_shortcode('cforms', 'cforms_scode'); | |
} | |
function cforms_scode( $attr, $content="") { | |
// connect to database with post type 'causing_forms' to get the ID of each post. You can use post_title if you want. | |
global $wpdb; | |
$post_type = 'causing_forms'; | |
$my_query = $wpdb->get_results("SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = 'causing_forms' AND post_status IN ('draft', 'publish') "); | |
if ( !is_null($my_query) ) { // check if query is not empty | |
// Loop start | |
foreach( $my_query as $cforms_query) { | |
$cforms_id = $cforms_query->ID; // post_id variable | |
$args = shortcode_atts( array( | |
'the_post_id' => $cforms_id // pass arguments post_id to shortcodes so that shortcodes can have parameters like id. ex: [cforms ID=12] | |
), $attr ); // ID is dynamic so it will detect which post ID and content to look for. | |
// get the html source from the custom field | |
$html_field = get_field( 'cforms-example_html_form', $args['the_post_id'] ); | |
// content of shortcodes | |
// displays the ID and content of html_field from ACF (html codes) | |
$output = ' | |
<div class="your_class"> | |
<h1 style="color:red";>This is the Post ID of this Shortcode: ' . $args['the_post_id'] .'</h1> | |
<p> '. $html_field .' </p> | |
</div> | |
'; | |
// return the conent of shortcodes according to post ID. | |
return $output; | |
} | |
// Loop end | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment